jQuery.fn.pgrTypeLetters = function (options) {
    var settings = jQuery.extend({
       	cursorBlinkInterval: 200,
       	typeInterval: 30,
       	startTypingDelay: 0,
       	onTypeStop: null
    }, options);
		
    $(this).each(function () {
    	var $this = $(this);
    	var _this = this;
    	$this.data("pgrTypeLetters", _this);
    	
    	var html = $this.html();
    	var cursorShow = false;
    	var cursorHandle = null;
    	var $cursor = null;
	    	
    	$this.empty();
	    	
    	_this.startCursor = function() {	    		
	    	startCursor();
    	};	    	
    	_this.stopCursor = function() {	    		
	    	stopCursor();
    	};
    	_this.startTyping = function() {
    		startCursor();
	    	typeLetters();	    			
    	};
	    	
    	function addCursor() {
    		$cursor = $('<span class="pgrTypeLetters-cursor"></span>');
    		$this.append($cursor);
    	}
    	function startCursor() {
    		if ($cursor) return;
    		addCursor();
    		cursorHandle = setInterval(function(){
    			cursorShow = !cursorShow;
    			if (cursorShow) $cursor.html("_");
    			else $cursor.html("&nbsp;");
    		}, settings.cursorBlinkInterval);
    	}
    	function removeCursor() {
    		if ($cursor && $cursor.length) $cursor.remove();
    		$cursor = null;
    	}
    	function stopCursor() {
    		if (cursorHandle) clearInterval(cursorHandle);
    		removeCursor();
    	}

    	function GetTypeArray() {
    		var typeArray = [];
    		var tempText = html;
    		var match = null;
    		var index = 0;
    		while (match = /<(\/{0,1})([^\s<>]*)[^<>]*>/igm.exec(tempText)) {
    			index = match.index; 
    			if (index > 0) typeArray.push({ type: "text", text: tempText.substr(0, index) });
    			typeArray.push({ type: "tag", match: match });
    			tempText = tempText.slice(index + match[0].length);
    		}
    		typeArray.push({ type: "text", text: tempText.substr(0) });
	    		
    		return typeArray;
    	}
    	
    	function typeLetters()
    	{	    		
	    	var typeLetterObj = GetTypeArray();
	    	var index;
	    	var typingHandler = null;
	    	var letterBuffor = [];
	    	var letter = null;
	    	
	    	function startTyping() {
	    		var $currentTypePos = null;
	    		typingHandler = setInterval(function() {
	    			letter = letterBuffor.shift(); 
	    			if (letter) {
	    				if ($currentTypePos != letter.$typePos) {
		    				letter.$typePos.after($cursor);
		    				$currentTypePos = letter.$typePos; 		    					
	    				}
	    				letter.$typePos.before(letter.letter);
	    			} else {
	    				stopTyping();
	    			}
	    		}, settings.typeInterval);
	    	}
	    	function stopTyping() {	    		
	    		$this.find(".pgrTypeLetters-pos").remove();
	    		if (typingHandler) clearInterval(typingHandler);
	    		if (settings.onTypeStop) eval(settings.onTypeStop)(_this);
	    	}
		    	
    		function prepareLetterBuffor($typePos)
    		{	    			
    			while (obj = typeLetterObj.shift()) {
    				if (obj.type == "text") {	    				
    					for (index = 0; index < obj.text.length; index++ ) {
    						letterBuffor.push({ $typePos: $typePos, letter: obj.text.charAt(index) });
    					}
    				} else if (obj.type == "tag") {
    					if (!obj.match[1]) {	    						
    						if (obj.match[2].toLowerCase() == 'br') {
    							letterBuffor.push({ $typePos: $typePos, letter: "<br />" });
    						} else {
    							var $newTypePos = $('<span class="pgrTypeLetters-pos"></span>');
    							var $tag = $(obj.match[0]);
       							$tag.html($newTypePos);    								
    							$typePos.after($tag);
    							$typePos = $('<span class="pgrTypeLetters-pos"></span>');
    							$tag.after($typePos);
    							prepareLetterBuffor($newTypePos);
    						}
    					} else {
    						return;
    					} 	    				
    				}
    			}
    		}	    		
    		
			var $firstTypePos = $('<span class="pgrTypeLetters-pos"></span>');
			$cursor.before($firstTypePos);
    		prepareLetterBuffor($firstTypePos);
    		$firstTypePos.after($cursor);
    		setTimeout(function() {
    			startTyping();
    		}, settings.startTypingDelay);
    	}	    	    	
    });
    
    return $(this);
};	

function preloadImage(src, onImageLoded) {
	var $img = $("<img />").css("display", "none").load(function() {
		$(this).remove();
		if (onImageLoded) eval(onImageLoded)();
	});
	$("body").append($img.attr("src", src));
}

function preloadImages(onImagesLoaded) {
	var images = [];
	$(".preload-image").each(function() {			
		images.push({obj: $(this), src : $(this).css("background-image") });
		$(this).css("background-image", "none");
	});
	var imagesToLoad = images.length;		
	for (var index in images) {
		var src = images[index].src.slice(4,-1);
		if (src.substr(0,1) == "\"") src = src.slice(1,-1);
		var $img = $("<img />").css("display", "none").load(function() {
			var image = images[$(this).attr("imageIndex")];			
			image.obj.css("background-image", image.src);
			imagesToLoad--;
			if ((imagesToLoad === 0) && (onImagesLoaded)) onImagesLoaded();
			$(this).remove();
		});
		$("body").append($img.attr("imageIndex", index).attr("src", src));
	}		
}

function indexStart() {
	$("#center").fadeOut(0);
	preloadImages(function() {
		var left = $("#background").offset().left - 610;
		$("#center").fadeIn("slow", function() {
			$("#background").animate({
				"left": left + "px"
			}, 6000);
		});
	});	

	
	var aboutUsHeight = $("#about-us").height();
	var contactWidth = $("#contact").width();
	$("#about-us").css("height", "0px");
	$("#contact").css("width", "0px");
	
	$("#menu-about-us").click(function() {
		$("#menu div").removeClass("selected");
		$(this).addClass("selected");
		$("#menu div:not[.seleted]").mouseout();
		menuAboutUs_In();
	});
	$("#menu-contact").click(function() {
		$("#menu div").removeClass("selected");
		$(this).addClass("selected");
		$("#menu div:not[.seleted]").mouseout();
		menuContact_In();
	});
	
	function menuAboutUs_In() {
		menuContact_Out();
		var firstRun = ($("#about-us .type1").data("pgrTypeLetters") == null); 

		if (firstRun) {
			$("#about-us .type1").pgrTypeLetters({
				startTypingDelay: 1000,
				onTypeStop: function() {
					$("#about-us .type1").get(0).stopCursor();
					$("#about-us .type2").get(0).startTyping();
				}
			});
			$("#about-us .type2").pgrTypeLetters({
				startTypingDelay: 1000,
				onTypeStop: function() {
					$("#about-us .type2").get(0).stopCursor();
					$("#about-us .type3").get(0).startTyping();
				}
			});
			$("#about-us .type3").pgrTypeLetters({
				startTypingDelay: 1000,
				onTypeStop: function() {
					$("#about-us .show1").show("slow");
					$("#about-us .type3").get(0).stopCursor();
					$("#about-us .type4").get(0).startTyping();
				}
			});
			$("#about-us .type4").pgrTypeLetters({
				startTypingDelay: 1000,
				onTypeStop: function() {
					$("#about-us .show2").show("slow");
					$("#about-us .type4").get(0).stopCursor();
					$("#about-us .type5").get(0).startTyping();
				}
			});
			$("#about-us .type5").pgrTypeLetters({
				startTypingDelay: 1000
			});
			
			$("#about-us .show1, #about-us .show2").hide();
		}
		
		$("#menu-about-us").animate({
			'height' : (672 + aboutUsHeight - 192) + 'px'
		}, "fast", "", function() {
			$("#center").animate({
				'margin-top' : "-150px"
			}, "fast", function() {
			});
			
			$("#about-us").animate({
				'height' : aboutUsHeight + "px"
			}, "fast", function() {
				if (firstRun) {
					setTimeout(function() {
						$("#about-us .type1").get(0).startTyping();
					}, 100);
				}
			});
			
		});		
	}
	function menuAboutUs_Out() {		
		$("#about-us").animate({
			'height' : "0px"
		}, "fast");

		$("#center").animate({
			'margin-top' : "0px"
		}, "fast", function() {
			$("#menu-about-us").animate({
				'height' : '383px'
			}, "fast");
		});
	}
	
	function menuContact_In() {
		menuAboutUs_Out();
		var firstRun = ($("#contact .type").data("pgrTypeLetters") == null); 

		if (firstRun) {
			$("#contact .type").pgrTypeLetters({
				startTypingDelay: 1000,
				onTypeStop: function() {
					$("#contact .type").get(0).stopCursor();
					$("#contact .show").fadeIn("slow");
				}
			});	
			
			$("#contact .show").fadeOut(0);
		}		
		$("#menu-contact").animate({
			'top' : (-195 + 432 - $("#menu-contact").height()) + 'px'
		}, "fast", function() {
			$("#contact").animate({
				'width': contactWidth + "px"
			}, "fast", function() {
				if (firstRun) $("#contact .type").get(0).startTyping();
			});
		});
	}
	function menuContact_Out() {
		$("#contact").animate({
			'width': '0px'
		}, "fast", function() {
			$("#menu-contact").animate({
				'top' : '0px'
			}, "fast");
		});
	}
	
	function initForm() {
		var $form = $("#contact form");
		$form.find("input, textarea").focusin(function() {
			var $input = $(this); 
			if ($input.hasClass("empty")) {
				$input.val("");
				$input.removeClass("empty");
			}
		}).focusout(function() {
			var $input = $(this);
			if (!$.trim($input.val())) {
				$input.val($input.attr("empty-value"));
				$input.addClass("empty");				
			}
		});
		$form.find("input, textarea").each(function() { $(this).val("").focusout(); });
		
		function showSentText() {
			var $msg = $form.find("span");
			$msg.removeClass("font-red").addClass("font-blue");
			$msg.hide().text($msg.attr("sent-text")).pgrTypeLetters({
				onTypeStop: function() {
					setTimeout(function() {
						$msg.fadeOut("slow", function() { $msg.empty(); });						
					}, 5000);
				}
			}).show();
			$msg.get(0).startTyping();			
			
			$form.find("input, textarea").each(function() {
				$(this).val("").focusout();
			});
		}
		function showInputErrorText() {
			var $msg = $form.find("span");
			$msg.removeClass("font-blue").addClass("font-red");
			$msg.hide().text($msg.attr("invalid-text")).pgrTypeLetters().show();
			$msg.get(0).startTyping();			
		}
		
		$form.find("a").click(function() {
			var isValid = true;
			$form.find(".required").each(function() {
				var $input = $(this);
				if ($input.hasClass("empty")) {
					$input.addClass("input-error");
					isValid = false;
				}
				else $input.removeClass("input-error");
			});
			
			var $msg = $form.find("span");
			if (!isValid) {
				showInputErrorText();
				return;
			}
			$msg.empty();
			
			$.post("php/mail.php", $form.serializeArray(), function(res) {
				if (res && (res.result == "OK")) {
					showSentText();
				} else {
					//showSentText();
					showInputErrorText();
				}
			}, "json");
		});
	}
	initForm();
	
	function initMenu() {		
		var currentHash = null;
		var checkHandler = null;
		
		$("#menu a").click(function() {
			if (checkHandler) clearInterval(checkHandler);
			setTimeout(function() {
				currentHash = window.location.hash.substr(1);
				startCheckingHash();
			}, 200);
		});
		
		function startCheckingHash() {
			checkHandler = setInterval(function(){
				if (currentHash != window.location.hash.substr(1)) {
					currentHash = window.location.hash.substr(1);
					$("#menu-" + currentHash.slice(0,-5)).mouseover().click();
				}
			}, 200);
		}
		startCheckingHash();
	}
	initMenu();
}

function portfolioStart() {
	$("#center").fadeOut(0);

	preloadImages(function() {
		$("#center").fadeIn("slow", loadPortofolio);
	});	
	
	$("#portfolio-preload div.portfolio-opactity").fadeTo(0, 0.6);	
	$("#portfolio-info div.portfolio-opactity").fadeTo(0, 0.9);
	$("#portfolio-image").hide();
	$("#portfolio-info").hide();
			
	var currentIndex = null;
	var portfolio = [];	
	
	function loadPortofolio() {
		$.get("/php/portfolio.php", {action: "getportfolio"}, function(res) {
			for (var key in res) {
				res[key].id = key;
				portfolio.push(res[key]);
			}
			currentIndex = 0;
			var index = 1;
			var count = portfolio.length;
			var handler = setInterval(function() {
				var imageIndex = index;
				preloadImage(portfolio[imageIndex].img, function() {
					portfolio[imageIndex].loaded = true;
				});
				index++;
				if (index == count) clearInterval(handler);
			}, 100);
			start();
		}, "json");
	}

	function getImageSrc()	{
		var src = $("#portfolio-image").css("background-image").slice(4,-1);
		if (src.substr(0,1) == "\"") src = src.slice(1,-1);
		
		return src;
	}
	
	function start() {
		preloadImage(getImageSrc(), show);
	}
	
	function getImageHeight() {
		var $img = $("<img style='position: absolute; z-index:-1' />").attr("src", getImageSrc());
		$("body").append($img);
		var imageHeight = $img.height();
		$img.remove();
		return imageHeight;
	}
	
	function slideImage() {
		var height = getImageHeight();
		setTimeout(function() {
			$("#portfolio-image").css("height", ($("#portfolio-image").height() + height) + "px").css("top", "0px").animate({
					"top": -height + "px"
			}, 20000, slideImage);
		}, 5000);		
	}
	function show() {
		//$("#portfolio-technologies").html(portfolio[currentIndex].technologies);
		//$("#portfolio-design").html(portfolio[currentIndex].design);
		$("#portfolio-info").css("height", "0px").show();
		$("#portfolio-preload").hide();
		$("#portfolio-image").fadeIn("slow", function() {	
			$("#portfolio-info").animate({ "height": "45px" }, "slow");
			slideImage();
		});		
	}
	
	$("#portfolio-image").click(function() {
		var newWindow = window.open(this.getAttribute('href'), '_blank');
		newWindow.focus();
		return false;
	});
}

$("#center").fadeOut(0);
$(function() {
	$(document).keydown(function(e) {
		if ($(e.target).is("input") || $(e.target).is("textarea")) return true;
		if (e.keyCode == 40) return false;
		if (e.keyCode == 32) return false;
	});
		
	$("#background").css({
		"left": (-200 + $("body").width() / 2 - 770) + "px"
	});	
	
	$(".fadeBtn").fadeTo(0, 0.7).hover(function(){
		$(this).stop().fadeTo(200, 1);
	}, function() {
		if ($(this).hasClass("selected")) return;
		$(this).stop().fadeTo(2000, 0.7);
	});	
});

function varDump(variable, maxDeep) {
    var deep = 0;
    var maxDeep = maxDeep || 5;

    function fetch(object, parent) {
        var buffer = '';
        deep++;

        for (var i in object) {
            if (parent) {
                objectPath = parent + '.' + i;
            } else {
                objectPath = i;
            }

            buffer += objectPath + ' (' + typeof object[i] + ')';

            if (typeof object[i] == 'object') {
                buffer += "\n";
                if (deep < maxDeep) {
                    buffer += fetch(object[i], objectPath);
                }
            } else if (typeof object[i] == 'function') {
                buffer += "\n";
            } else if (typeof object[i] == 'string') {
                buffer += ': "' + object[i] + "\"\n";
            } else {
                buffer += ': ' + object[i] + "\n";
            }
        }

        deep--;
        return buffer;
    }

    if (typeof variable == 'object') {
        return fetch(variable);
    }

    return '(' + typeof variable + '): ' + variable + "\n";
}

