var pageTracker = null;

$(document).ready(function(){
	
	globalAjaxCursorChange();
	externalLinks();
	loadWorldMap();
	loadGoogleMaps();
	loadZien();
	loadLightbox();
	loadShowhidediv();
	setCapitalAtBackgroundPage();
	loadInputfields();
	//loadSearchAssistant();
});			

$(window).bind('load', function(){
	initCenterBoxesVertAlignment();
	initPhotoCarrousel();
	initPhotoCarrouselNews();
	fixIE7OverlayHolderWidth();
});

function loadSearchAssistant() {
	
}

function search() {
	searchStr = $('#search').val();
		
	if (searchStr == 'zoeken') {
		searchStr = '';
	} 
	window.location.href = '/zoeken.html?words='+searchStr;
	
}

function loadInputfields() {
	if ($("input#email")) {
		$("input#email").bind("click", function(el){
			if($("input#email").val() == "e-mailadres") {
				$("input#email").val("");
			}
		});	
	}
	if ($("input#email_footer")) {
		$("input#email_footer").bind("click", function(el){
			if($("input#email_footer").val() == "e-mailadres") {
				$("input#email_footer").val("");
			}
		});	
	}
	if ($("input#email_out")) {
		$("input#email_out").bind("click", function(el){
			if($("input#email_out").val() == "e-mailadres") {
				$("input#email_out").val("");
			}
		});	
	}
	
	
	$("a#searchbutton").bind("click", function(el){
		search();
	});
	
	if ($("#search")) {
		
		$("#search").bind("click", function(el){
			if ($("input#search").val() == "zoeken") {
				$("input#search").val("");
			}
		});
		
		
		
/*		$("input#search").bind("keyup", function(el){
			
			value = $("input#search").val();
			if (value.length > 2) {
				
				$.ajax({
					type: "POST",
					url: "/module/94/",
					data: "action=getAssistent&value="+value,
					success: function(html){
						$("div#assistentHolder").show();
						$("div#assistentHolder").html(html);
					}
				});
			}
		});
*/		
		$("#search").keypress(function(e){
			if(e.which == 13){
				search();
			}
		});
	}
	


}

function loadWorldMap() {
	if ($('#worldmap').size() == 0) {
		return;
	}
	
	$('#worldmap p').css('visibility', 'hidden');
	
	$('#worldmap:first').flash({
		src: '/flash/worldmap.swf',
		width: 1000,
		height: 775,
		flashvars: {
			flashCookie: $.cookie('flash_intro_cookie'),
			xmlLoc: '/flash/worldmap_dynamic.xml'
		}
	});
}

function loadShowhidediv() {

	if($(".showhide").size() == 0){
		return;
	}

	var firstActive = true;
	
	// als er al een div een active class heeft niets doen,
	// nog niet, dan een active op de eerste
	$.each($(".showhide"), function(el, obj){
		
		if ($(this).hasClass("active")) {
			firstActive = false;
		}
	});
	
	if (firstActive) {
		$(".showhide:first").addClass("active");	
	}	
	var i = 1;
	// alles op niet zichtbaar zetten, behalve diegene met active
	$.each($(".showhide"), function(el, obj){
		if (!$(this).hasClass("active")) {
			$(this).css("display", "none");
		} else {
			// huidige pagina op die van de actieve zetten
			$('.page_number').html(i);
		}
		i++;
	});
	
	$('.total_page_number').html($(".showhide").size());
	
	$(".showhide_next").bind("click", function(el){
		switchShowHide('next');
		fixIE7OverlayHolderWidth();
	});
	$(".showhide_prev").bind("click", function(el){
		switchShowHide('prev');
		fixIE7OverlayHolderWidth();
	});

	if ($(".showhide").size() == 1) {
		$('.paginator').css("display", "none");
	}
	
	
	// 2 de pagina actief tonen. Vieze hack!
	if (window.location.search == '?page=2' && $(".showhide").size() == 2) {
				
		$(".showhide:first").toggleClass("active");
		$(".showhide:first").css("display", "none");
		$(".showhide:last").addClass("active");
		$(".showhide:last").css("display", "block");
		$('.page_number').html("2");
		
		eval($(".showhide:last").find('ul.tickerItems li:first a').attr("onclick"));
		// getTickerItem(lookupId, publicitemId, countryId, dreamplaceId)
	}
	
}

function switchShowHide(direction){
	
	if($(".showhide").size() == 0){
		return;
	}

	var i = 0;	
	var prev = null;
	var next = null;
	var takeNext = false;
	var currentPage = parseInt($('.page_number').html());

	

	$.each($(".showhide"), function(el, obj){
		if (takeNext == true) {
			
			prev.removeClass("active");
			prev.toggle();
			$(this).toggleClass("active");
			$(this).toggle();
			$('.page_number').html(currentPage+1);
			
			return false;
		}
		
		if (direction == 'prev'){
		
			if (i != 0) {
				if ($(this).hasClass("active")){
					$(this).removeClass("active");
					$(this).toggle();

					prev.toggleClass("active");
					prev.toggle();
					$('.page_number').html(currentPage-1);	
				}
			}
			
		}else{
			if (i != $(".showhide").length) {
				if ($(this).hasClass("active")){
					takeNext = true;
				}
			}
		}
		prev = $(this);
		i++;
	});
}


/**
* alle a elementen met een rel lightbox een lightbox ding meegeven
*
*
*/
function loadLightbox(){
	$('a[@rel*=lightbox]').lightBox();
}

/**
* alle a elementen met een rel external een target blank geven
*
*
*/
function externalLinks() {
 if (!document.getElementsByTagName) return;
 
 var anchors = document.getElementsByTagName("a");
 
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "external" || anchor.getAttribute("rel") == "nofollow")) {
	anchor.target = "_blank";  
   }
     
 }
}


/**
* als de zien div aan de linkerkant van de pagina 
* geladen is de afbeeldingen erin een lightbox tag geven
*
*/
function loadZien(){
	if($("#phototicker").size() == 0){
		return;
	}
	$(function() {		
		$('#phototicker a').lightBox();
	});
}


/**
*
*
*
*/
function loadGoogleMaps(){

	if($("#map").size() == 0){
		return;
	}

	loadGm();
}

function loadGm() {
	
	var lon = $("#lon").html();	
	var lat = $("#lat").html();	
	var zoom = $("#gm_zoom_level").html();	
	
	// op de gaan pagina zijn er 2 span's met lat lon, als die er zijn moeten die coordinaten doorgegeven worden
	if (lon != null && lat != null) {
		var latLon = new GLatLng(lon, lat);
	} else {
		var latLon = new GLatLng(52.469397, 5.509644);
	}	
	
	// ook op de gaan pagina is er een value met zoom level, die ook overrulen
	if (zoom != null) {
		var zoomLevel = parseInt(zoom);
	} else {
		var zoomLevel = parseInt(6);
	}
	
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(latLon, zoomLevel);
		map.setMapType(G_HYBRID_MAP);		
		map.addControl(new GLargeMapControl());
		var mapControl = new GMapTypeControl();
		map.addControl(mapControl);
	}
}


/**
* ajax call om landen lijst op te halen voor landenindex module
*
*
*/
function loadCountriesStartingWith(moduleId, startingCharacter){
	if(!$("#country_index")) return;
	
	$.ajax({
		type: "POST",
		url: "/module/"+moduleId+"/.html",
		data: "action=ajax&character="+startingCharacter,
		success: function(html){
			$("#country_index").html(html);
		}
	});
	
	trackCountryIndex(startingCharacter);
}


function globalAjaxCursorChange()   
{  
  $("html").bind("ajaxStart", function(){  
     $(this).addClass('busy');  
   }).bind("ajaxStop", function(){  
     $(this).removeClass('busy');  
   });  
}  

/**
* ajax call om nieuwsbrief inschrijving te doen
*
*
*/
function optinNewsletter(moduleId, email){
	
	if(!$("#emailform")) return;
	
	$.ajax({
		type: "POST",
		url: "/module/"+moduleId+"/.html",
		data: "action=ajax&email="+email,
		success: function(html){
			$("#emailform").html(html);
		}
	});
}
function opoutNewsletter(moduleId, email){
	
	if(!$("#emailform_out")) return;
	
	$.ajax({
		type: "POST",
		url: "/module/"+moduleId+"/.html",
		data: "action=ajax&email_out="+email,
		success: function(html){
			$("#emailform_out").html(html);
		}
	});
}



/**
 * initCenterBoxesVertAlignment
 * Vertical alignment of blocks in the center column.
 */
function initCenterBoxesVertAlignment() {
	arrLeftBoxes = $('#center .subcol_left').children('div');
	arrRightBoxes = $('#center .subcol_right').children('div');
	
	arrLeftBoxes.each(function(i){
		if ((arrLeftBoxes.length != arrRightBoxes.length) && (i == arrLeftBoxes.length - 1)) {
			elLeftBoxContent = $(arrLeftBoxes[i]).children('div:last');
			intRightBoxesHeight = $(arrRightBoxes[i]).height() + parseInt($(arrRightBoxes[i]).css('marginBottom')) + $(arrRightBoxes[i+1]).height();
			intLeftBoxContentHeight = intRightBoxesHeight - ($(arrLeftBoxes[i]).children('div.block_header').height() + parseInt(elLeftBoxContent.css('paddingTop')) + parseInt(elLeftBoxContent.css('paddingBottom')) + parseInt(elLeftBoxContent.css('borderTopWidth')) + parseInt(elLeftBoxContent.css('borderBottomWidth')));
			
			elLeftBoxContent.height(intLeftBoxContentHeight);
		} else if (arrLeftBoxes[i] && arrRightBoxes[i]) {
			elLeftBoxContent = $(arrLeftBoxes[i]).children('div:last');
			elRightBoxContent = $(arrRightBoxes[i]).children('div:last');
			intLeftBoxContentHeight = elLeftBoxContent.height();
			intRightBoxContentHeight = elRightBoxContent.height();
			
			if (intLeftBoxContentHeight > intRightBoxContentHeight) {
				elRightBoxContent.height(intLeftBoxContentHeight);
			} else {
				elLeftBoxContent.height(intRightBoxContentHeight);
			}
		}
	});
		
}

/**
 * setCapitalAtBackgroundPage
 * Makes a capital letter of the first character of the first paragraph on the Background page.
 */
function setCapitalAtBackgroundPage() {
	if (!$('.background')) return false;
	
	var elBackgroundFirstParagraph = $('.background > p:first');
	elBackgroundFirstParagraph.attr('class', 'intro_capital');
}

/**
 * getTickerItem
 * Haalt een publiekstrekker item op een ververst de content
 * 
 * @author: vincent
 */
function getTickerItem(lookupId, publicitemId, countryId, dreamplaceId, trackerurl) {
	
	$.ajax({
		type: "POST",
		url: "/module/"+lookupId+"/",
		data: "action=ajax&publicitemId="+publicitemId,
		success: function(html){
			$("#tickerActive").html(html);
			loadLightbox();
			externalLinks();
		}
	});
	$.ajax({
		type: "POST",
		url: "/module/"+lookupId+"/",
		data: "action=ajaxGetTitle&publicitemId="+publicitemId+"&country="+countryId+"&dreamplace="+dreamplaceId,
		success: function(responseTitle){
			document.title = responseTitle;		
		}
	});
	
	if (pageTracker) {
		pageTracker._trackPageview(trackerurl);
	}
}

//Replace characters not supported by Google Analytics  
function convertToAnalyticsReadable(str) {
	return str.match(/^([http|https]*):\/\/?([^\/]+)/g, "").toString().replace(new RegExp(/^([http|https]*)?:\/\//i),"");	
}

function trackImageLink(url) {
	url = url.replace(" ", "_");
	if (pageTracker) {
		str = "/image"+url;
		pageTracker._trackPageview(str);
	}
}


function trackCountryIndex(letter) {
	
	if (pageTracker) {
		str = "/countryindex/"+letter;
		pageTracker._trackPageview(str);
	}
}

function trackWebguideLink(url) {
	if (pageTracker) {
		str = "/webguide/"+convertToAnalyticsReadable(url);
		pageTracker._trackPageview(str);
	}
}

function trackReferenceLink(url) {
	if (pageTracker) {
		str = "/reference/"+convertToAnalyticsReadable(url);
		pageTracker._trackPageview(str);
	}
}

function trackOutgoingLink(url) {
	if (pageTracker) {
		str = "/outgoinglink/"+convertToAnalyticsReadable(url);
		pageTracker._trackPageview(str);
	}
}

function trackTodoTip(url) {
	if (pageTracker) {
		str = "/todo_showreel"+url;
		pageTracker._trackPageview(str);
	}
}
function trackVoteLink(url) {
	if (pageTracker) {
		str = "/awards/travvies2010/"+convertToAnalyticsReadable(url);
		pageTracker._trackPageview(str);
	}
}
 /**
 * initPhotoCarrousel
 * Creates a carrousel of the phototicker.
 */
function initPhotoCarrouselNews() {
	if (!$('.latest_news_slider')) return false;
	
	jQuery('.latest_news_slider').jcarousel({
		vertical: false,
		scroll: 4
	});
	
//	$('.jcarousel-clip-horizontal').width(600);
}
 /**
 * initPhotoCarrousel
 * Creates a carrousel of the phototicker.
 */
function initPhotoCarrousel() {
	if (!$('.thumblist')) return false;
	
	jQuery('.thumblist').jcarousel({
		vertical: true,
		scroll: 6
	});
	
	if (!$('.jcarousel-clip-vertical') || !$('#center')) return false;
	
	intThumbListItemHeight = $('.thumblist li').height() + parseInt($('.thumblist li').css('marginBottom'));
	intMaxThumbListItems = Math.floor($('#center').height() / intThumbListItemHeight);
	$('.jcarousel-clip-vertical').height(intMaxThumbListItems * intThumbListItemHeight);
}
/**
 * fixIE7OverlayHolderWidth
 * Fixes the width of the overlay holder in IE7.
 */
function fixIE7OverlayHolderWidth() {
	if (!jQuery.browser.msie) return false;
	if (jQuery.browser.version != '7.0') return false;
	arrOverlayHolders = $('.overlay_holder');
	$.each(arrOverlayHolders, function(index, elOverlayHolder){
		$(elOverlayHolder).css('width', $(elOverlayHolder).find('img').width() + 2);
	});
}

