//global timer
//var timer;
var uri = '';

//genereert een random getal tussen v-10 en v+10
function rg(v,verschil) {
	if (verschil == null) {
		verschil = 8
	}
	return parseInt(v)+(-verschil) + Math.floor(1+Math.random()*(verschil*2));
}


//schudden van een element
jQuery.fn.shakeit = function(times,speed){
	if(times == 'undefined') {
		times=1;
	}
	
	this.each(
		function(init){
			
			var jqNode = $(this);
			var b_top = parseInt(jqNode.css('top'));
			var b_left = parseInt(jqNode.css('left'));
			var b_width = parseInt(jqNode.css('width'));
			var b_height = parseInt(jqNode.css('height'));
			
			
			for (var x = 1; x <= times; x++){
				jqNode
				.animate({ left: rg(b_left)+"px", top: rg(b_top)+"px", width: rg(b_width)+"px", height: rg(b_height)+"px"},speed)
				.animate({ left: b_left+"px", top: b_top+"px", width: b_width+"px", height: b_height+"px"},speed);
			}
		}
	);
	return this;
}

//laadt alle plaatjes in
function load_all_bgs(nr) {
	var images = new Array("b1.jpg","b2.jpg","b3.jpg")

	if (!nr) {
		nr = 0;
	}
	
	if (!images[nr]) {
		return false
	}
	
	//console.log('images/'+images[nr])

     var img = new Image();			
	$(img).load(function () {
		load_all_bgs(nr+1)
	}).attr('src','images/'+images[nr])
	
}

//achtergrond veranderen
function changebg(bg) {

	setTimeout(function() {
		
		var img = new Image();			
		$(img)
		  .load(function () {
		   
			  //voeg em als div toe met bg
		  	var new_element = $(document.createElement("div")).css({opacity:0,'background-image':'url(/images/'+bg+')'});
		  	var bgslides = $("#slides").append(new_element);

		
			new_element.animate({opacity:1},500,function(){
				bgslides.find("div:eq(0)").remove()
			});
		  })
		  .attr('src', 'images/'+bg);
		
	},500);
}

//shake om de zoveel tijd
var shaketimeout = null;
var menu1leuzen = new Array("zucht","pff","kreun","hmm..");
var menu1teller = 0;
function initshake(el,msec) {
 	
 	shaketimeout = setTimeout(function() {
 		el.shakeit(6,1.5);
 		
 		try {
 			$("#b1 h1.bigger").text(menu1leuzen[menu1teller]);
 		} catch (err) {}
 		menu1teller++;
 		if (menu1teller >= (menu1leuzen.length-1)) {
			menu1teller = 0; 
		}
 		initshake(el,msec)
 	},msec);	
}


var selected = null;
var ignoremouseover = false;
var ignoremouseout = true;
var outtimeout = null;

//open menublok
function openblok(ss) {
	try {
		clearTimeout(outtimeout);
	} catch (err) {}
	
	if (!ignoremouseover) {
	
	     if (selected != ss) {
			selected = $(ss)
			
			//niet meer schudden
			try {
				clearTimeout(shaketimeout);
			} catch (err) {}
			
			ignoremouseout = true;
			ignoremouseover = true;
			
			//andere menuitems verbergen
			//$('#content .menu').not(selected).fadeOut();
			$('#content div.menu').not(selected).css({display:'none'});
			
			//wanneer het item niet open is, open deze
			if (!selected.open) {
			
				$("#b1_link,#b2_link,#b3_link").css({display:'none'});
			
				selected.find('h1.title').fadeOut();
				
				//sluitknopje er bij
				selected.append("<a id='sluiten' href='javascript:;'></a>");
				$("#sluiten").click(function() {
					sluitblok(selected)
				})
			
				selected.animate({top:'0px'})
				selected.find('div.animator_bg').animate({opacity:0.9})
				var newwidth = 883;
				if (document.location.pathname == "/kerstgroet") {
				    //selected.find('div.animator_bg').animate({opacity:0.7})
					newwidth = 710;
				}
				selected.find('div.animator').animate({width:newwidth+'px',height:'405px'},function() {
					selected.open = true;
					
					ignoremouseout = false;
					ignoremouseover = true;
					
					//ajax page ophalen
				
					setTimeout(function(){
						//uri kan iets anders zijn, doordat bijv /heemgaard wordt aangeroepen, de 1e x opent ie dan de heemgaard
						if (uri == '') {
							uri = selected.attr('href');
						}
						
						try {
							pageTracker._trackPageview(uri);
						} catch (errr) {}
						
						$.post(uri, {ajax:true}, function(html){
							uri = '';
							
							selected.find('div.animator_2').append("<div class='ajax_content'>"+html+"</div>");
							
							bindlinks_for_ajax(selected)
							
							setTimeout(function() {
								cleanup();
								init_first_animation($('#rails_lijst'),10000);
							},1500);
						});
					},1);
				})
				
				if (document.location.pathname != "/kerstgroet") {
					changebg(selected.attr("id")+".jpg")
				}
			}
		}
	}
}

//hang ajax request aan links naar subpagina's
function bindlinks_for_ajax(sss) {
	//var links = $(sss).find('a.desc, a.terug, a[target!=_blank]')
	var links = $(sss).find('a[target!=_blank]').not('#b1_link,#b2_link,#b3_link,a[href*=mailto]')
	links.each(function(ee) {
		var thiss = $(this)
		thiss.click(function(e) {
			//achtergrond veranderen indien daarnaar gelinkt wordt
			if (thiss.attr('href') == '/contact') {
				changebg("b3.jpg")
			}
			if (thiss.attr('href') == '/ons-bedrijf') {
				changebg("b2.jpg")
			}
			if (thiss.attr('href') == '/portfolio') {
				changebg("b1.jpg")
			}
			
			try {
				pageTracker._trackPageview(thiss.attr('href'));
			} catch (errr) {}
		
			$.post(thiss.attr('href'), {ajax:true,prevurl:$(sss).attr('href')}, function(html2){
				$(sss).find('div.ajax_content').html(html2);
				
				//recursief, want anders is dit na 1 ajax refresh weer weg
				bindlinks_for_ajax(sss)
				
				setTimeout(function() {
					cleanup();
					init_first_animation($('#rails_lijst'),10000);
				},1500);
			});
			return false;
		});
	});
}

//menu blok dichtklappen
function sluitblok(ss) {
     if (!ignoremouseout) {
		if (selected.open && selected == ss) {
			$("#b1_link,#b2_link,#b3_link").css({display:'block'});
		
			ignoremouseout = true;
			ignoremouseover = true;
			
			selected.find('h1.title').fadeIn();
			$("#sluiten").remove()
		
			//$('#content .menu').not(selected).animate({opacity:1})
			//$('#content .menu').not(selected).fadeIn();
			$('#content div.menu').not(selected).css({display:'block'});
			
			var idd = selected.attr('id');
			if (idd == 'b2') {
				selected.animate({top:'145px'})	
			}
			if (idd == 'b3') {
				selected.animate({top:'290px'})	
			}
			
			
			//remove ajax content  
			try {
				pause_animation('#rails_lijst');
				cleanup();
			} catch (err) {}
			$('div.ajax_content').remove();
			
			selected.find('div.animator_bg').animate({opacity:'0.8'})
		     selected.find('div.animator').animate({width:'115px',height:'115px'},function() {
				ignoremouseout = true;
				ignoremouseover = false;

				//begin weer met schudden, als het item niet b1 is geweest
				//if (idd == 'b1') {
					try {
						$("#b1 h1.bigger").removeClass("bigger")
						$("#b1 h1").text("Portfolio")
					} catch (err) {}
				//}
				//else {
				//	if ($("#b1 h1").hasClass("bigger")) {
				//		initshake($("#b1 .animator"),4000)
				//	}
				//}
			})
			
			changebg("b_standard.jpg")
			
			selected.open = false
			selected = null
		}
	}
}


/* RAILS ANIMATIE */
var left_side = 0;
var starttime = 0;
var speed_per_pixel = 0;
var prev_mutated = null
var width = 0;
var orig_width = 0;
var orig_height = 0;
var disable_mouseover_rails = false;
var disable_mouseout_rails = false;
var no_animation_needed = false;

function cleanup() {
	left_side = 0;
	starttime = 0;
	speed_per_pixel = 0;
	prev_mutated = null
	width = 0;
	orig_width = 0;
	orig_height = 0;
	disable_mouseover_rails = false;
	disable_mouseout_rails = false;
	no_animation_needed = false;
}

var submenutimer = null;
function init_first_animation(selector,speed) {

	//selector = $(selector)

	//eindstand wanneer de elementen op nul komen
	var init = false;
	if (left_side == 0) {
		init = true;
		left_side = parseInt(selector.find('div.move:last').css('left'));
		speed_per_pixel = speed/(parseInt(selector.find('div.move:eq(4)').css('left')));
		
		var firstel = selector.find('div.move:first');
		orig_width = $(firstel).width();
		orig_height = $(firstel).height();
		width = parseInt($($(firstel).next()).css('left')) - parseInt($(firstel).css('left'))
		
		if (selector.find("div.move").length <= 4) {
			no_animation_needed = true
		}
	}
	
	//ga ze ook echt verplaatsen
	selector.find('div.move').each(function(e){
		
	     var thiss = $(this)
		//hang pause knop er aan
		if (init) {
		
			thiss.click(function(e) {
				thiss.find('a.desc').trigger('click')
			});
			
			
		
			//uitklappen per individueel blokje
			thiss.mouseenter(function(e) {
				
				if (disable_mouseover_rails && !thiss.isopengeklapt) {
					//var ooo = this
					try {
						clearTimeout(submenutimer)
					} catch (errrr) {}
					submenutimer = setTimeout(function() {
						try {
							thiss.trigger('mouseenter')
						} catch (err) {}
					},1000)
				}
				else if (!disable_mouseover_rails) {
				
					//schuiven van het plaatje afhankelijk van de cursor
					thiss.find('div.innerspan').mousemove(function(ee) {
						//console.log("ee.pageX: " + ee.pageX + ", ee.pageY: " + ee.pageY);
						var offset = thiss.offset();
						var top = (ee.pageY-offset.top)
						var left = (ee.pageX-offset.left)

						var leftperc = 30-(left)/10
						var topperc = 30-(top)/((10/3)*2)
						
						var img = thiss.find('img')
						img.css('left',(leftperc-30) + "px")
						img.css('top',(topperc-30) + "px")
					})
			
					thiss.isopengeklapt = true;
					disable_mouseover_rails = true;
					disable_mouseout_rails = true;
					//animatie op pauze
					pause_animation(selector)
					
					thiss.css('z-index','2')
				
					var vanaflinks = parseInt(thiss.css('left'));
					//kijk of het blokje naar links of naar rechts moet openklappen
					if (vanaflinks > ($("#rails_lijst").width()/2)) {
						thiss.naarlinks = true;
						thiss.links_opslaan = vanaflinks
						
						disable_mouseout_rails = false;
						
						//openklappen naar links
						thiss.animate({width:'300px',height:'200px',left:(vanaflinks-(300-orig_width))+'px'},500)
					}
					else {
						thiss.naarlinks = false;
						disable_mouseout_rails = false;
						thiss.animate({width:'300px',height:'200px'},500)
					}
				}
			})
			//inklappen per individueel blokje
			thiss.mouseleave(function() {
				
				if (!disable_mouseout_rails && thiss.isopengeklapt) {
					thiss.isopengeklapt = false
					if (thiss.naarlinks) {
						
						thiss.stop(true,true).animate({width:orig_width+'px',height:orig_height+'px',left: thiss.links_opslaan+"px"},500,function() {
							init_first_animation(selector,speed)
							thiss.css('z-index','1')
							disable_mouseover_rails = false;
						})
					}
					else {
						thiss.stop(true,true).animate({width:orig_width+'px',height:orig_height+'px'},500,function() {
							init_first_animation(selector,speed)
							thiss.css('z-index','1')
							disable_mouseover_rails = false;
						})
					}
				}
				
			})
		}
	
		//bereken hoeveel elk blokje nog moet animeren naar links, afhankelijk van de speed
		var left_side2 = parseInt(thiss.css('left'))
		//console.log(thiss,left_side2)
		
		if (!no_animation_needed) {
			thiss.animate({left:'0px'},(left_side2*speed_per_pixel),'linear',function() {
				recursive_animation(thiss,speed);
			});
		}
	});
}

function recursive_animation(element,speed) {
	element = $(element)

	var new_left_side = left_side;
	if (left_side == 0) {
		return "";
	}
	
	//bereken verschil tussen het laatste blokje en deze, door vertraging kunnen de elementen anders niet goed terecht komen
	if (prev_mutated != null) {
		var left_prev = parseInt(prev_mutated.css('left'))
		new_left_side = left_prev + width
	}
	
	element.css({left:new_left_side+"px"})
	element.animate({left:'0px'},new_left_side*speed_per_pixel,'linear',function() {
		recursive_animation(element,speed)
	});
	
	//dit element opslaan als laatst gemuteerd
	prev_mutated = element;
}

function pause_animation(selector) {
	$(selector).find('div.move').stop(true,false)
}
/* EINDE RAILS ANIMATIE*/



function changeleus_onderin() {
	setTimeout(function() {
		var activeleus = $("#bottom div.activeleus");
		activeleus.removeClass('activeleus');
		activeleus.fadeOut(1000);
		var nextleus = activeleus.next();
		
		//opnieuw beginnen
		if (nextleus.length==0) {
			nextleus = $("#bottom div:first");
		}
		nextleus.addClass('activeleus');
		nextleus.fadeIn(1000);
		changeleus_onderin();
	},6000);
}


//instancieer alles
$(document).ready(function() {

// Sneeuw door Dirk
//$(document).snowfall({round : true, maxSize:4}); // add rounded

	$("#b1_link,#b2_link,#b3_link").css({display:'block',opacity:0.0})
	
	
	$("#content div.animator_bg").css("opacity","0.8");
	
	
	
	$("#b1_link,#b2_link,#b3_link").click(function() {
		return false;
	})


	$("#b1_link,#b2_link,#b3_link").mouseenter(function() {
		$('#'+$(this).attr('id').replace(/_link/,'')).trigger('mouseenter')
		return false;
	})

	$("#b1_link,#b2_link,#b3_link").mouseleave(function() {
		$('#'+$(this).attr('id').replace(/_link/,'')).trigger('mouseleave')
		return false;
	})
	

	$("#content div.menu").bind('mouseenter',function() {
		openblok(this)
	});
	
	
	
	if (document.location.pathname == '/kerstgroet') {
	     changebg("kerst.jpg")
	}
	else {
		changebg("b_standard.jpg")
		load_all_bgs(false);
	}
	

	
	$("#content div.menu").bind('mouseleave',function() {
		if (!ignoremouseout) {
			var el = this
			outtimeout = setTimeout(function() {
				//sluitblok(el);
			},500);
		}
	});
	
	
 	//initshake($("#b1 div.animator"),4000)
 	$("#b1 h1.bigger").removeClass("bigger")
	$("#b1 h1").text("Portfolio")
 	
 	
 	$("#bottom div.activeleus").fadeIn(1000);
	changeleus_onderin();
	
	vacatureanim();
	jQuery('#vacature').mouseover(function() {
		jQuery(this).data("pauze",true);
		jQuery('#vacature').stop(false,true).animate({top:'7'},200,'linear');
	});
	jQuery('#vacature').mouseout(function() {
	     jQuery(this).data("pauze",false);
		jQuery('#vacature').stop(false,true).animate({top:'0'},200,'linear');
	});
});

function vacatureanim() {
	setTimeout(function() {
		if (!jQuery('#vacature').data("pauze")) {
			jQuery('#vacature').animate({top:'7'},200,'linear',function() {
				jQuery('#vacature').animate({top:'0'},200,'linear');
			})
		}
		vacatureanim();
	},4000)
}


function contactform(f) {
	$.post("/contact",$(f).serialize()+"&ajax=true",function(re) {
		$(f).html(re);
	})
	return false;
}

function hostingform(f) {
	$.post($(f).attr("action"),$(f).serialize()+"&ajax=true",function(re) {
		$(f).html(re);
	})
	return false;
}

