$(document).ready(function(){
	
	jQuery.fn.replaceWith = function(replacement) {
		return this.each(function(){
			element = $(this);
			$(this)
			.after(replacement).next()
			.html(element.html())
			.prev().remove();
		});
	};
	
	$("#topmenu .rollover").hover(
		function(){
			$("#topmenu .sub").show().animate({opacity:1, marginTop:0},400);
		},
		function(){
			$("#topmenu .sub").animate({opacity:0, marginTop:10},400, function(){ $(this).hide(); });
		}
	);
		
	if( $.browser.msie && $.browser.version < 8 ){
		$("a[rel=open-box]").attr("rel","");
		$(".bg").css({left:"36%"});
	}
	
	
	/*
	* Box loading and setup
	*/
	$("a[rel=open-box]").click(function(){
		var id 		= $(this).attr("class");
		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:9999});
			
			$("#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();
			});
						
			window.location.hash = "/"+id+"/";
			return false;
		}
		
		return (count==0);
	});
	
	function makeBox(obj){
		if( $("h1", obj).size() > 0 ){
			$("h1", obj).prepend('<span class="close">X</span>').replaceWith("<h3></h3>");
		} else {
			$("div.heading", obj).replaceWith("<h3></h3>");
		}
		
		obj.click(function(){
			document.title = $("h3 .content ",this).html().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
		*/
		$("a.fancybox").fancybox();
		
		$(".cloud").click(function(){formCloud()});
		function formCloud() {
			$(".cloud strong").each(function(){
				var newSize = (Math.random() * 2) + 0.8;
				$(this).animate({fontSize: newSize+"em"});
			});
		}
		formCloud();
		
		$('a.thumb').click(function(){
			openItem( $(this) );
		});
		
		var hash = window.location.hash.replace("#","");
		var url	= window.location;
		if( url.pathname == "/portfolio/" && hash != "" ){
			$("a#"+hash+"-thumb").click();
		}
		
		function openItem(link){
			$('#slide_holder, .to-overview').slideDown();
			$('.projects').slideUp();
			
			var title = $('span', link).html();
			$('#boxportfolio h3 .content').html("Portfolio: "+title);
			pageTracker._trackEvent('Portfolio','Show',title);
		}
		
		$('a.to-overview').click(function(){
			$('#slide_holder, .to-overview').slideUp();
			$('.projects').slideDown();
			$('#boxportfolio h3 .content').html('Portfolio');
			window.location.hash = '';
			return false;
		});
		
		/*
		* Form interactions
		*/
		$("input, textarea").focus(function(){ $(this).parent().addClass("active"); }).blur(function(){ $(this).parent().removeClass("active"); });
		
		var prem = "contact";
		var posm = "yoeran";
		$("a.email").html(prem+"@"+posm+".nl").attr({href: "mailto:"+prem+"@"+posm+".nl"});
		
		$("#container a[href*='http']").each(function(){
			$(this).attr('target','_blank');
			pageTracker._trackEvent('External','Goto',$(this).remove("img").html() );
		});
		
		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();
});