/* Fill formfields with temp data */
var formFiller = {
	fill: function(fieldId, fieldValue){
		if($('#'+fieldId).length == 0) return;

        $('#'+fieldId).val(fieldValue);

		$('#'+fieldId).focus(function () {
			if($('#'+fieldId).val() == fieldValue){
				$('#'+fieldId).val('');
			}
		});

		$('#'+fieldId).blur(function () {
			if($('#'+fieldId).val() == ''){
				$('#'+fieldId).val(fieldValue);
			}
		});
	}
}

var slides = {
    childs: null,
    total: null,
    counter: 1,
    fadeInterval: null,
    intervalTime: 4000,
    transitionTime: 500,

    init: function(){
        if($("#slideshow").length == 0) return;
        slides.childs = $("#slideshow").children();
        slides.total = slides.childs.length;
        slides.counter = slides.total;
        slides.fadeInterval = setInterval("slides.crossFade()", slides.intervalTime);
        slides.childs.animate({opacity: 0}, 0, "linear");
        $(slides.childs[slides.total - 1]).animate({opacity: 1}, 0, "linear");
		$("#slideshow").click(slides.navigateTo);
    },
    crossFade: function(){
        if(slides.counter == 0) slides.counter = slides.total;
        slides.counter--;
        $(slides.childs[slides.counter]).animate({opacity: 0}, slides.transitionTime, "linear");
		

        if((slides.counter - 1) == -1){
            // startover
            $(slides.childs[slides.total - 1]).animate({opacity: 1}, slides.transitionTime, "linear");
        }else{
            // continue
            $(slides.childs[slides.counter - 1]).animate({opacity: 1}, slides.transitionTime, "linear");
        }
    },
    showTicker: function(){
        // hier moet nog iets met de ticker gebeuren...
    },
	navigateTo: function(e) {
		e.preventDefault();
		if((slides.counter - 1) == -1){
            // startover
			window.location.href = $(slides.childs[slides.total-1]).attr('href');
            
        }else{
            // continue
            window.location.href = $(slides.childs[slides.counter-1]).attr('href');
            
        }
		
	}
}

var galleryArray = new Array();

function Gallery(){
	this.container = null;
	this.childs = null;
	this.total = null;
	this.counter = 1;
	this.intervalTime = 4000;
	this.fadeInterval = 500;
	this.transitionTime = 250;
	this.direction = 'forward';
}

Gallery.prototype.prevSlide = function(){
	if(this.direction == "forward"){
		if(this.counter != 1){
			this.counter = this.counter - 2;
		}else{
			this.counter = this.total - 1;	
		}
	}
	this.direction = 'backward';
	this.childs.animate({opacity: 0}, this.transitionTime, "linear");
	
	if(this.counter == 0){
	   // startover
	   $(".img-title", this.container).html($("img", this.childs[(this.total - 1)]).attr('alt'));
	   $(this.childs[(this.total - 1)]).animate({opacity: 1}, this.transitionTime, "linear");
	   this.counter = this.total;
	   $(".current_count", this.container).text(this.counter);
	   this.counter--;
	}else{
	   // continue
	   $(".img-title", this.container).html($("img", this.childs[(this.counter - 1)]).attr('alt'));
	   $(this.childs[(this.counter - 1)]).animate({opacity: 1}, this.transitionTime, "linear");
	   $(".current_count", this.container).text(this.counter);
	   this.counter--;
	}
}

Gallery.prototype.nextSlide = function(scope){
	if(this.direction == "backward"){
		if(this.counter == this.total){
			this.counter = 1;
		}else if((this.counter + 2) > this.total){
			this.counter = 1;
		}else{
			this.counter = this.counter + 2;	
		}
	}
	
	this.direction = 'forward';
	$(".current_count", this.container).text(this.counter);
	this.childs.animate({opacity: 0}, this.transitionTime, "linear");
	
	if(this.counter == this.total){
		// startover
		$(".img-title", this.container).html($("img", this.childs[(this.total - 1)]).attr('alt'));
		$(this.childs[(this.total - 1)]).animate({opacity: 1}, this.transitionTime, "linear");
		this.counter = 1;
	}else{
		// continue
		$(".img-title", this.container).html($("img", this.childs[(this.counter - 1)]).attr('alt'));
		$(this.childs[(this.counter - 1)]).animate({opacity: 1}, this.transitionTime, "linear");
		this.counter++;
	}
}

Gallery.prototype.setFadeInterval = function(){
	var scope = this;
	return setInterval(function(){scope.nextSlide();}, this.intervalTime);
}

Gallery.prototype.clearFadeInterval = function(){
	if(this.fadeInterval != null) clearInterval(this.fadeInterval);
}

var galleries = {
	init: function(){
		if($(".gallery").length == 0) return;
		$('.gallery').each(function() {
			var gallery 		= new Gallery;
			gallery.container	= this;
			gallery.childs 		= $(".slides", this).children();
			gallery.total 		= gallery.childs.length;
			gallery.childs.animate({opacity: 0}, 0, "linear");
	
			if($("#expertise").length > 0){
				
				gallery.fadeInterval = gallery.setFadeInterval();
			}else{
				gallery.nextSlide();
			}
			
			$(".prev_slide", this).click(function(ev){gallery.clearFadeInterval(); gallery.prevSlide(); ev.preventDefault()});
        	$(".next_slide", this).click(function(ev){gallery.clearFadeInterval(); gallery.nextSlide(); ev.preventDefault()});
			
			galleryArray.push(gallery);
			
			// toegevoegd door maikel ivm instant start en bij 1 foto niet faden
			if($("#expertise").length > 0){
				gallery.nextSlide();
				if(gallery.total == 1) {
					gallery.clearFadeInterval();
				}
			}
		});
	}
}

/*
 * Menu mod
 * - Adds effect (fadeIn)
 * - Repositions submenu + wrapper DIV (grey top line)
 */
var menuMod = {
    childs: null,
   
    init:function(){
        if($("#main-nav").length == 0) return;
        menuMod.childs = $("#main-nav").children();
		
  		menuMod.childs.hover(
            function (){ // hover
            	//var parentWidth = $(this).parent().width();
                //var offsetLeft = this.offsetLeft;
                if($("div ul", this).length > 0){
					var parentWidth = $(this).parent().width();
					var offsetLft = this.offsetLeft;
                	var marginRight = $("div", this).find("ul").css("margin-right").split("px");
	                var subMenus = $("div", this).find("ul");
	                var totalSubWidth = ($(subMenus).width() * subMenus.length);
	               	//if(this.negativeOffset == undefined) this.negativeOffset = ((totalSubWidth + offsetLeft) - parentWidth) + (marginRight[0] * subMenus.length);
					if(this.negativeOffset == undefined) this.negativeOffset = ((totalSubWidth + offsetLft) - parentWidth) + (marginRight[0] * subMenus.length);
					
					$("div ul:first", this).css("margin-left", 0);
					
	                //if(this.negativeOffset >= 0){
					//	$("div ul:first", this).css("margin-left", (offsetLft - this.negativeOffset)+"px");
					//	$("div ul:first", this).css("display", "inline");
					//}else{
	                    //$("div ul:first", this).css("margin-left", offsetLeft+"px");
						$("div ul:first", this).css("margin-left", offsetLft+"px");
						$("div ul:first", this).css("display", "inline");
	                //}
	 				
	 				$("div", this).css("visibility", "visible");
	                $("div", this).css("display", "block");
	                $("div", this).css("opacity", "0");
	            	$("div", this).animate({opacity: 1}, 300, "linear");
                }
                
            },
            function(){ // out
            	//$("#main-nav div").css('display', 'none');
				if($("div", this).length > 0){
					$("div", this).css('display', 'none');
				}
            }
    	);
    },
    show:function(item){
		//temporarily show the menu | called from Home
		
		if (item == 'over') {
			menuItem = $("#main-nav > li:eq(1)");
			offsetLft = 102;
		} else if (item == 'expertise') {
			menuItem = $("#main-nav > li:eq(3)");
			offsetLft = 311;
		} else if (item == 'markten') {
			menuItem = $("#main-nav > li:eq(4)");
			offsetLft = 430;
		}

		var parentWidth = $(menuItem).parent().width();
		var marginRight = $(menuItem).find("ul").css("margin-right").split("px");
		var subMenus = $(menuItem).find("ul");
		var totalSubWidth = ($(subMenus).width() * subMenus.length);
		
		if(menuItem.negativeOffset == undefined) menuItem.negativeOffset = ((totalSubWidth + offsetLft) - parentWidth) + (marginRight[0] * subMenus.length);

		$("div ul:first", menuItem).css("margin-left", 0);

		$("div ul:first", menuItem).css("margin-left", offsetLft+"px");
		$("div ul:first", menuItem).css("display", "inline");

		$("div", menuItem).css("visibility", "visible");
		$("div", menuItem).css("display", "block");
		$("div", menuItem).css("opacity", "0");
		$("div", menuItem).css("background-color", "#FFF");
		$("div", menuItem).animate({opacity: 1}, 300, "linear");


		setTimeout
		(
			function()
			{
				$("div", menuItem).animate({opacity: 0}, 300, "linear");
			},
			3000
		);
    }
}

var googleMap = {
	map: null,
	gdir: null,
	geocoder: null,
	onLogoMarker: null,
    
    init: function(){
        if (GBrowserIsCompatible()) {
			// init map
			googleMap.map = new GMap2(document.getElementById("gmap"));
			googleMap.map.addControl( new GSmallMapControl());

			// get coordinates of location
			googleMap.geocoder = new GClientGeocoder();
			googleMap.geocoder.getLatLng('Bankaplein 3 Den Haag Netherlands', function(point) { googleMap.setOnMarker(point) });

			// init directions
			googleMap.gdir = new GDirections(googleMap.map, document.getElementById("directions"));
			GEvent.addListener(googleMap.gdir, "load", googleMap.onGDirectionsLoad);
			GEvent.addListener(googleMap.gdir, "error", googleMap.handleErrors);
		}
    },
    setOnMarker: function(){
        if(!point) {
			// backup if geocoder fails
			var point = new GLatLng(52.0931471, 4.3027829);
		}
		googleMap.map.setCenter(point, 12);

		// add custom icon
		var onLogo = new GIcon(G_DEFAULT_ICON);
		onLogo.iconSize = new GSize(38, 25);
		onLogo.shadowSize = new GSize(0, 0);
		onLogo.image = "/img/wvh_map_icon.gif";

		googleMap.onLogoMarker = new GMarker(point, { icon:onLogo });
		googleMap.map.addOverlay(googleMap.onLogoMarker);
    },
    getRouteToDestination: function(street, city){
		var toAddress = 'Bankaplein 3 Den Haag Netherlands';
		var fromAddress = street + ' ' + city + ' Nederland';

		googleMap.gdir.load("from: " + fromAddress + " to: " + toAddress, {"locale": "nl_NL"});
    },
    onGDirectionsLoad: function(){
        document.getElementById('directions').style.display = 'block';
		document.getElementById('print').style.display = 'block';
		document.getElementById('errors').innerHTML = '';
    },
    handleErrors: function(){
        if (googleMap.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	    	document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
		else if (googleMap.gdir.getStatus().code == G_GEO_SERVER_ERROR)
			document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
		else if (googleMap.gdir.getStatus().code == G_GEO_MISSING_QUERY)
	    	document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
	   	else if (googleMap.gdir.getStatus().code == G_GEO_BAD_KEY)
			document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
	   	else if (googleMap.gdir.getStatus().code == G_GEO_BAD_REQUEST)
			document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
	   	else document.getElementById('errors').innerHTML = 'Het opgegeven adres kon niet worden gevonden.';
    }
}

var tooltip = {
	init: function(selector, section){
		if($(selector).length == 0) return;
		
		if(section == "home"){
			$(selector).tooltip({
				track: true,
			    delay: 0,
			    showURL: false,
			    showBody: false,
			    extraClass: "home",
			    fixPNG: true,
			    fade: 25,
			    opacity: 0,
			    bodyHandler: function() {return "aaaa";}
			});
		}
		else if(section == "projects"){
			$(selector).tooltip({
				track: false, 
			    delay: 0, 
			    showURL: false,
			    extraClass: "projects",
			    showBody: " - ", 
			    fade: 0
			});
		}
		else{
			return;
		}
	}
}

// handles all the slider stuff
var scrollSlider = {
	projectWidth: null, 
	sliderItems: null,
	workWidth: null,
	projectPosition: null,
	projects: null,
	currentProject: 1,
	
	init: function(){
		if($('div.sliderGallery').length == 0) return;
		
		// check if hash value is given and set active project
		var hashId = scrollSlider.checkHash();
		if(hashId > 0) {
			scrollSlider.currentProject = hashId;
		}
		else {
			// set first project active
			scrollSlider.currentProject = $('.project').eq(0).attr('class').split('project item')[1];
		}
		
		
		if($(".sliderGallery").length != 0) $(".sliderGallery").css("overflow", "hidden");
		if($(".slider").length != 0) $(".slider").css("display", "block");
		
		scrollSlider.projectWidth = $(".items li.project").width();
		
		
		// rescales the list/container
		$("ul.items").css('width', (scrollSlider.projectWidth * $(".items li.project").length));
		
		$('div.sliderGallery').each(function() {
			scrollSlider.sliderItems = $('ul.items', this);
			scrollSlider.workWidth = scrollSlider.sliderItems.innerWidth() - $(this).outerWidth();
			scrollSlider.projectWidth = $("ul.items li.project").width();
			$("ul.items").css('width', (scrollSlider.projectWidth * $("ul.items li.project").length));
			
			$('.slider', this).slider({
	            'min': 0,
	            'max': scrollSlider.workWidth,
	           
				// gets called at start of sliding
				start: function (ev, ui) {},
				
				// gets called during sliding
				slide: function (ev, ui) {
					scrollSlider.jumpToProject(ui.value);
				},
				
				// gets called at end of sliding
				stop: function (ev, ui) {
					
					
					// calculate position/steps on slider and move to closest project
					var projectPosition = Math.round(ui.value / scrollSlider.projectWidth) * scrollSlider.projectWidth;
					scrollSlider.projectPosition = projectPosition;
					scrollSlider.animateToProject(projectPosition);
					
					var projectCount = (projectPosition / scrollSlider.projectWidth);
					
					scrollSlider.currentProject = $('.project').eq(projectCount).attr('class').split('project item')[1];
					scrollSlider.highlightProject(scrollSlider.currentProject);
					scrollSlider.setHash();
				}
			});
			
			if(hashId > 0) {
				var pl = $(".sliderGallery li.item"+scrollSlider.currentProject).position().left;
				var sliderBarPercentage = pl/scrollSlider.workWidth;
				
				scrollSlider.slideScrollerToProject(sliderBarPercentage);
				scrollSlider.animateToProject(pl);
			}
			scrollSlider.highlightProject(scrollSlider.currentProject);
			scrollSlider.setHash();
		});
		
		// inits the projects-filter/select
		scrollSlider.projects = $("#project-filter ul.projects, #project-filter ul.projects li ul, #project-filter ul.projects li p").children();
        scrollSlider.projects.click(function(ev){
			ev.preventDefault();
        	var projectNr = $(this).attr('class').split('project');
            if(projectNr[1] != undefined){
				scrollSlider.currentProject = projectNr[1];
				var pl = $(".sliderGallery li.item"+scrollSlider.currentProject).position().left;
				var sliderBarPercentage = pl/scrollSlider.workWidth;
				scrollSlider.slideScrollerToProject(sliderBarPercentage);
				
				scrollSlider.animateToProject(pl);
				
	            scrollSlider.highlightProject(projectNr[1]);
				scrollSlider.setHash();
            }
        });
	},
	highlightProject: function(nr){
		$("#project-filter ul.projects li").removeClass('active');
		$("#project-filter ul.projects li.project"+nr).addClass('active');
	},
	jumpToProject: function(position){
		scrollSlider.sliderItems.css('left', '-' + position + 'px');
	},
	animateToProject: function(position){
		scrollSlider.sliderItems.animate({ 'left' : '-' + position + 'px' }, 350, 'swing');
	},
	slideScrollerToProject: function(perc) {
		$('.slider a').animate({'left' : perc*100+'%'}, 200, 'swing');
	},
	setHash: function() {
		var currentItem = $('.items').find('.item'+scrollSlider.currentProject);
		var project = currentItem.find('h1').text();
		var client = currentItem.find('h2').text().substring(7);
		window.location.hash = '#/' + scrollSlider.currentProject + '/' + url_title(client).toLowerCase() + '/' + url_title(project).toLowerCase();
	},
	checkHash: function() {
		if(window.location.hash != '') {
			return window.location.hash.split('/')[1];
		}
		else {
			return 0;
		}
	}
}

$(document).ready(function(){
	$(window).bind("resize", handleResize);
	handleResize();
	
    scrollSlider.init();
    slides.init();
    menuMod.init();
	//gallery.init();
	galleries.init();
    formFiller.fill("street", "uw straat");
    formFiller.fill("city", "uw plaats");
    //tooltip.init('#slideshow a', 'home');
	tooltip.init('.projects li p span a', 'projects');

	/* --- SMALL INIT STUFF --- */
	if($("ul.shortcuts").length > 0){
    	$("ul.shortcuts li").mouseover(function(){
	      $("span.hover", this).animate({opacity: 0}, 100, "linear");
	    }).mouseout(function(){
	      $("span.hover", this).animate({opacity: 1}, 100, "linear");
	    });
    }

	// mouseovers voor de prijzen pagina
	if($("dl.prijzen").length > 0){
		var activeImage = 1;
		$("#img_display img.prijs"+activeImage).css('display', 'block');
		$("#img_display img.prijs"+activeImage).animate({opacity: 0}, 0, "linear");
		$("#img_display img.prijs"+activeImage).animate({opacity: 1}, 250, "linear");
		
		$("#img_display span.label").html($("#img_display img.prijs"+activeImage).attr('alt'));
		
		$('dl.prijzen dt').each(function(i) {
			$(this).mouseover(function(){
				if(activeImage != (i + 1)){
					$("#img_display img.prijs"+activeImage).animate({opacity: 0}, 250, "linear");
					$("#img_display img.prijs"+(i + 1)).css('display', 'block');
					$("#img_display img.prijs"+(i + 1)).animate({opacity: 0}, 0, "linear");
					$("#img_display img.prijs"+(i + 1)).animate({opacity: 1}, 250, "linear");
					$("#img_display span.label").html($("#img_display img.prijs"+(i + 1)).attr('alt'));
					activeImage = (i + 1);
				}
			});
		});
	}

	// mouseovers voor de netwerk pagina
	if($(".network").length > 0){
		var activeParter = null;
		$('#partners li').each(function(i) {
			if($(this).attr('class') != "txt"){
				$(this).mouseover(function(){
					if(activeParter != (i + 1)){
						$("#partners li a").removeClass('active');
						$("a", this).addClass('active');
	
						$("#partners li.txt").hide();
						
						$("#partners li.txt").fadeIn("fast");
						$("#partners li.txt").html($("div.project_txt", this).html());
						activeParter = (i + 1);
						
						$("#partners li.txt").css('margin-left', (activeParter*252)-252+'px');
					}
				});
				
				$(this).mouseout(function(){
					//if(activeParter != (i + 1)){
						$("#partners li a").removeClass('active');
	
						$("#partners li.txt").fadeOut("fast");
						activeParter = null;
					//}
				});
			}
		});
	}
	
	if($("#pers .detail").length > 0) {
		//alert('a');
		$('.presstext').columnize({width:380});
	}

	if($(".contact").length > 0){
		googleMap.init();
		
		// generated with: http://rot13.de/index.php
		var mr = "znvygb:vasb@jvaxryznarainaurffra.ay".replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
		$('#mr').attr('href', mr);
	}
});

function handleResize(e) {
	var windowHeight = $(window).height();
	//console.log(newWindowHeight);
	
	// windowheight - ( (wrapper-scrollcorrection) + navigation) / 2 
	var wrapperMargin = ( windowHeight - ( ($('#wrapper').height()-40) + $('#nav-wrap').height() )-90 ) / 2;
	
	if(wrapperMargin < 20) {
		wrapperMargin = 20;
	}
	$('#wrapper').css('margin-top', wrapperMargin);
}