$(document).ready(function(){
	
	jQuery.fn.replaceWith = function(replacement) {
		return this.each(function(){
			element = $(this);
			$(this)
			.after(replacement).next()
			.html(element.html())
			.prev().remove();
		});
	};
	
	jQuery.fn.stripHTML = function() {
		var matchTag = /<(?:.|\s)*?>/g;
		return this.replace(matchTag, "");
	};
		
	if( $.browser.msie && $.browser.version < 8 ){
		$("a[rel=open-box]").attr("rel","");
		$(".bg").css({left:"36%"});
	}
	
	
	/*
	* Box loading and setup
	*/
	$("a[rel=open-box]").live("click", function(){
		return initBox( $(this).attr("class") );
	});
	
	function initBox(id){
		var count	= $("#box"+id).size();
		
		if( id!="" && count==0 ){
			var obj		= $("#temp").clone();
			obj.addClass("box").attr("id","box"+id);
			obj.css({opacity:0, marginTop:-10, top:Math.random()*300+50, left:Math.random()*300, zIndex:990});
			
			$("#container").append(obj);
			makeBox(obj);
			
			$.get("/block_cfg.php", { key: id }, function(response){
				var data = JSON.parse(response);
				obj.addClass(data.classes);
				$("h3 .content", obj).append(data.title);
				$("div.content",obj).html(data.html);
				
				obj.animate({opacity:1, marginTop:0},400);
				init();
				
				_gaq.push(['_trackEvent', 'Pages', 'Box', data.title]);
			});
			
			
			window.location.hash = "/"+id+"/";
			return false;
		}
		
		return (count==0);
	}
	
	function makeBox(obj){
		if( $("h1", obj).size() > 0 ){
			$("h1", obj).prepend('<span class="close"><!-- # --></span>').replaceWith("<h3></h3>");
		} else {
			$("div.heading", obj).replaceWith("<h3></h3>");
		}
		
		$(".box.focus").css("zIndex",200).removeClass("focus");
		obj.addClass("focus");
		
		obj.mousedown(function(){
			$(".box.focus").removeClass("focus").css("zIndex", 200);
			obj.addClass("focus").css("zIndex",990);
			document.title = $("h3 .content ",this).html().replace('<a href="#" class="to-overview">\u00AB</a>','').replace("&nbsp;", "") + " \u00BB Yoeran Luteijn";
		});
		obj.draggable({ handle: "h3", stack: {group:'#container div', min:1} });
		obj.find(".close").click(function(){
			obj.animate({opacity:0, marginTop:10},400,function(){
				$(this).remove();
			});
		});
	}
	
	$(".box").each(function(){ makeBox( $(this) ); });
	
	
	function init()
	{
		/*
		* Box specifics
		*/
		
		$(".categories a:not(.contact)").click(function(){
			$(".categories .active").removeClass("active");
			$(this).addClass("active");
			
			
			if( this.rev!="all" )
			{
				$(".view a.thumb."+ $(this).attr("rev") ).animate({opacity:1},400);
				$(".view a.thumb:not(."+ $(this).attr("rev") +")").animate({opacity:0.1},400);
			}
			else
			{
				$(".view a.thumb").animate({opacity:1},400);
			}
		});
		
		$('a.thumb').click(function(){
			openItem( this );
		});
		
		var hash = window.location.hash.replace("#","");
		var url	= window.location;
		
		if( hash[0] == "/" ){
			initBox( hash.replace(/\//g, "") );
		} else if( url.pathname == "/portfolio/" && hash != "" ){
			$("a#"+hash+"-thumb").click();
		}
		
		function openItem(link){
			var obj = $(link);
			var id = obj.attr('href').replace("#","");
			
			obj.parents('.box').addClass("detail-view").find('h3 .content').html('Portfolio: '+link.title).prepend('<a href="#" class="to-overview">&laquo;</a>');
			$('.projects, .sidebar').slideUp();
			
			$(".project#" + id + " .slider").cycle({
				fx:			'scrollHorz',
				timeout:	0,
				next:		'.pager.next',
				prev:		'.pager.prev',
				pager:		'.pager.hint'
			});
			
			$("a.to-overview, .project#" + id ).slideDown();
			_gaq.push(['_trackEvent', 'Portfolio', 'Show', link.title]);
			
		}
		
		$('a.to-overview').live("click",function(){
			$(this).parents('.box').removeClass("detail-view");
			$('.pager.hint').html('');
			$('.project, .to-overview').slideUp();
			$('.projects, .sidebar').slideDown();
			$('#boxportfolio h3 .content').html('Portfolio');
			
			document.title = "Portfolio \u00BB Yoeran Luteijn";
			window.location.hash = '';
			return false;
		});
		
		/*
		* Form interactions
		*/		
		var prem = "contact";
		var posm = "yoeran";
		$(".email").html(prem+"@"+posm+".nl").attr({href: "mailto:"+prem+"@"+posm+".nl"});
		
		$("#container a[href*='http']").each(function(){
			$(this).attr('target','_blank');			
			_gaq.push(['_trackEvent', 'External', 'Goto', $(this).title]);
		});
		
		function mailCheck(str) {
			var at = "@";
			var dot = ".";
			var lat = str.indexOf(at);
			var lstr = str.length;
			var ldot = str.indexOf(dot);
			var error = 0;
			
			if (str.indexOf(at)==-1)													{ error++; }
			if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)		{ error++; }
			if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)	{ error++; }
			if (str.indexOf(at,(lat+1))!=-1)											{ error++; }
			if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)		{ error++; }
			if (str.indexOf(dot,(lat+2))==-1)											{ error++; }
			if (str.indexOf(" ")!=-1)													{ error++; }
			
			if (error>0) { return false; } else { return true; }
		}
		
		$("#contactform").submit(function(){
			var error = 0;
	
			if ( $("#name", this).val() == "" ) {
				$("#name").focus();
				$("#name").next().html("<br /> Ik zou heel graag je naam leren kennen!");
				error ++;
			}
			
			if ( !mailCheck( $("#email", this).val() ) ) {
				$("#email").focus();
				$("#email").next().html("<br /> Dit adres lijkt niet geldig =(");
				error ++;
			}
			
			if ( $("#message", this).val() == "" ) {
				$("#message").focus();
				$("#message").next().html("<br /> Zeg alsjeblieft iets!");
				error ++;
			}
			
			if (error==0) {
				$(this).append('<img src="/images/loader.gif" />').fadeTo(1000,0.5);
				$.post("/contactMe.php", { name: $("#name").val(), email: $("#email").val(), message: $("#message").val() }, function(data){
										
					if (data == "succes") {
						$("#contactform").slideUp(500).after("<p><em>Thanks! Je bericht zal spoedig in mijn inbox vallen!</em></p>");
					} else {
						$("#contactform").fadeTo(500,1).prepend("<p><em>Uh-oh! Het lijkt er op dat "+data+"... Probeer het a.u.b. nog een keer!</em></p>");
					}
				});
				return false;
			} else { return false; }
			
		});
		
	} // end init
	
	init();
});
