//==================
// GLOBAL VARIABLES
//==================
var objectArray = new Array();
var i;

//=================================================
// IMPORTANT!!! ON DOCUMENT.READY --> FINALIZEPAGE
//=================================================
function finalizePage(){
	createDropDownMenu();
	checkActiveState();
	checkLeftnavDimension();
	setTimeout('checkModulesDimension()', 100);
	
	$('#content div.faq div.question').removeClass('opened');
	$('#content div.faq div.question').addClass('closed');
	$('#content div.faq div.toggable').removeClass('open');
	$('#content div.faq div.toggable').addClass('close');
	
	$('#modules p.search-query').corner({
		tl:{radius: 8}, 
		tr:{radius: 8},
		bl:{radius: 8}, 
		br:{radius: 8},
		antiAlias: true,
		autoPad: true,
		validTags: ['p']
	});

	
	$('.date-pick').datePicker({
		startDate:			'01/01/2000',
		clickInput:			true
	});	
}

//===========================
// CALENDAR: CREATE CALENDAR
//===========================
function createCalendar(sEventUrl, sDatesUrl){
	$('.turn-me-into-datepicker').datePicker({
		inline:				true,
		showYearNavigation:	false,
		startDate:			'01/01/2000',
		hoverClass:			false,
		renderCallback:		checkDate
	}).bind(
		'dateSelected',
		function(e, selectedDate, $td){
			getAJAXDates(selectedDate.getDate(),selectedDate.getMonth(), selectedDate.getFullYear(), sEventUrl, 'calendar-event-view');
		}
	);
	
	function checkDate($td, thisDate, month, year){
		if(thisDate.getDate() == '1'){
			i = 0;
			getAJAXDates('',month, year, sDatesUrl, 'calendar-view');
		}
	
		if(month == thisDate.getMonth()){
			objectArray[i] = $td;					
			i++;
		}
	}		
}

//============================
// CALENDAR: HELPER FUNCTIONS
//============================
function showCalendar(){
	if(document.getElementById('calendar-header').className == "close"){
		$('#calendar-header').removeClass('close')
		$('#calendar-header').addClass('open');
		$('div.turn-me-into-datepicker').fadeIn('800');
		setTimeout ("$('#calendar-event-view').fadeIn('slow')", 800);
	}
	else{
		$('#calendar-header').removeClass('open')
		$('#calendar-header').addClass('close');
		$('#calendar-event-view').fadeOut('800');
		setTimeout ("$('div.turn-me-into-datepicker').fadeOut('slow')", 800);
	}
}
						
//=====================
// CALENDAR: AJAX CALL
//=====================
var xmlHttp;

function getAJAXDates(lDay, lMonth, lYear, sUrl, sView){
	var sMonth = lMonth + 1;
		
	try{
  		// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	} catch(e){
  		// Internet Explorer
  		try{
  			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  		} catch(e){
    		try{
      			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      		} catch(e){
      			alert("Your browser does not support AJAX!");
      			return false;
      		}
    	}
  	}
  	if (sView == 'calendar-view'){
  		xmlHttp.onreadystatechange=stateCalendarChanged;
  	}
  	else if(sView == 'calendar-event-view'){
  		xmlHttp.onreadystatechange=stateCalendarEventViewChanged;
  	}
    
	xmlHttp.open("GET", sUrl + "?d=" + lDay + "&m=" + sMonth + "&y=" + lYear,true);
	xmlHttp.send(null);
}
function stateCalendarChanged(){
	if(xmlHttp.readyState==4){
  		var dateString = xmlHttp.responseText;
  		var splitted = dateString.split(',')
		for(var j = 0; j < splitted.length; j++){
			objectArray[splitted[j] - 1].addClass("hasActivity");
		}
  	}
 }
 		
function stateCalendarEventViewChanged(){
	if(xmlHttp.readyState==4){
		$("#calendar-event-view div.events").html(xmlHttp.responseText);
	}
}

//=============================================
// FLASH: CREATE FLASH OBJECT (VIDEO OR AUDIO)
//=============================================
function createFlashObject(sPlayerPath, sMovie, sStartImage, sSkin, sId, sWidth, sHeight, sVersion){
	var s1 = new SWFObject(sPlayerPath,'player', sWidth, sHeight, sVersion);
	s1.addParam('allowfullscreen','true');
	s1.addParam('allowscriptaccess','always');
	s1.addParam('wmode','transparent');
	s1.addParam('flashvars','file=' + sMovie + '&image=' + sStartImage + '&skin=' + sSkin + '&stretching=fill');
	s1.write(sId);
}

//============================================
// CAROUSSEL BASED ON PICTURES in SDL TRIDION
//============================================
function createTridionCaroussel(sCollectionId, sThumbWidth, sThumbHeight, sEffect, sPreviousId, sNextId, sCaptionId){
	$('#' + sCollectionId + ' a img').width(sThumbWidth + 'px');
	$('#' + sCollectionId + ' a img').each(function(index, image){
		var sHeight = $(image).height();
		//if (sHeight > sThumbWidth){
		//	$(image).height(sThumbWidth + 'px');
		//} 
	});
	$('#' + sCollectionId).cycle({
		fx:				sEffect,
		timeout:		8000,
		next:			'#' + sNextId,
		prev:			'#' + sPreviousId
	});
	$('#' + sCaptionId).cycle({
		fx:				'fade',
		timeout:		8000,
		next:			'#' + sNextId,
		prev:			'#' + sPreviousId
	});
	$('#' + sCollectionId + ' a').lightBox();
}

//============================================
// CAROUSSEL BASED ON SPLASH SCREEN PICTURES
//============================================
function createSplashCaroussel(sCollectionId){
	$('#' + sCollectionId).cycle({
		fx:				'fade',
		timeout:		10000
	});
}

//=========================================
// CAROUSSEL BASED ON PICTURES FROM FLICKR
//=========================================
function createFlickrCaroussel(sCollectionId, sApiKey, sType, sUserId, sPhotosetId, sThumbSize, lAmount, sCaptionId, sListView, sEffect, sPreviousId, sNextId){
	jQuery(function(){   
		$('#' + sCollectionId).flickr({     
			api_key: sApiKey,
			type: sType,
			user_id: sUserId,
			photoset_id: sPhotosetId,
			thumb_size: sThumbSize,	
			per_page: lAmount,
			image_collection_id: '#' + sCollectionId,
			image_caption_id: '#' + sCaptionId,
			listview: sListView,
			callback: createCarousel
		});
	});
	function createCarousel(){
		$('#' + sCollectionId).cycle({
			fx:				sEffect,
			timeout:		8000,
			next:			'#' + sNextId,
			prev:			'#' + sPreviousId
		});
		
		$('#' + sCaptionId).cycle({
			fx:				'fade',
			timeout:		8000,
			next:			'#' + sNextId,
			prev:			'#' + sPreviousId
		});
		$('#' + sCollectionId + ' a').lightBox();
	}
}

//==========================================
// GALLERY BASED ON PICTURES in SDL TRIDION
//==========================================
function createTridionGallery(sCollectionId, sMainImageId){
	$('#' + sCollectionId + ' ul').galleria({
		history   : true, // activates the history object for bookmarking, back-button etc.
		clickNext : true, // helper for making the image clickable
		insert    : '#' + sMainImageId, // the containing selector for our main image
		onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
			// fade in the image & caption
			if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
				image.css('display','none').fadeIn(1000);
			}
			caption.css('display','none').fadeIn(1000);
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			// fade out inactive thumbnail
			_li.siblings().children('img.selected').fadeTo(500,0.3);
			// fade in active thumbnail
			thumb.fadeTo('fast',1).addClass('selected');
			// add a title for the clickable image
			image.attr('title','Next image >>');
		},
		onThumb : function(thumb) { // thumbnail effects goes here
			// fetch the thumbnail container
			var _li = thumb.parents('li');
			// if thumbnail is active, fade all the way.
			var _fadeTo = _li.is('.active') ? '1' : '0.3';						
			// fade in the thumbnail when finnished loading
			thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
			// hover effects
			thumb.hover(
				function() { thumb.fadeTo('fast',1); },
				function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
			)
		}
	});
	$('#' + sCollectionId).jcarousel({
		scroll: 8,
		visible: 8,
		buttonNextHTML: "<div></div>",
		buttonPrevHTML: "<div></div>",
		buttonNextEvent: "click",
		buttonPrevEvent: "click"
	});
}

//=========================================
// GALLERY BASED ON PICTURES FROM FLICKR
//=========================================
function createFlickrGallery(sCollectionId, sApiKey, sType, sUserId, sPhotosetId, sThumbSize, sListView, sMainImageId){
	jQuery(function(){
		$('#' + sCollectionId).flickr({     
			api_key: sApiKey,
			type: sType,
			user_id: sUserId,
			photoset_id: sPhotosetId,
			thumb_size: sThumbSize,	
			listview: sListView,
			callback: createGallery
		});		
	});
	function createGallery(){
		$('#' + sCollectionId + ' ul').galleria({
			history   : true, // activates the history object for bookmarking, back-button etc.
			clickNext : true, // helper for making the image clickable
			insert    : '#' + sMainImageId, // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				// fade in the image & caption
				if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
					image.css('display','none').fadeIn(1000);
				}
				caption.css('display','none').fadeIn(1000);
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500,0.3);
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				// add a title for the clickable image
				image.attr('title','Next image >>');
			},
			onThumb : function(thumb) { // thumbnail effects goes here
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.3';						
				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast',1); },
					function() { _li.not('.active').children('img').fadeTo('fast',0.3); } // don't fade out if the parent is active
				)
			}
		});
		$('#' + sCollectionId).jcarousel({
			scroll: 8,
			visible: 8,
			buttonNextHTML: "<div></div>",
			buttonPrevHTML: "<div></div>",
			buttonNextEvent: "click",
			buttonPrevEvent: "click"
		});
	}
}

//================================================
// NEWS SHORTLIST: CHANGE OF PICTURE ON MOUSEOVER
//================================================
function changePicture(oObject){
	var elementId = oObject.id;
	var result = elementId.split('-');
	$('#main div.news-shortlist p.active').removeClass('active');
	$('#main div.news-shortlist img.active').removeClass('active');
	$('#main div.news-shortlist img#' + result[1]).addClass('active');
	$('#main div.news-shortlist p#' + elementId).addClass('active');
}

//==================================
// LEFT NAVIGATION: CHECK DIMENSION
//==================================
function checkLeftnavDimension(){
	if(document.getElementById("leftnav") != null) {		
		var heightLeftnav = $("#leftnav").height();
		var heightContent = $("#central-content").height();
				
		if(heightLeftnav > heightContent){
			$("#content-container").height(heightLeftnav + 10 + "px");
		}
	}
}

//===========================
// MODULES: CHECK DIMENSION
//===========================
function checkModulesDimension(){
	if(document.getElementById("modules") != null) {		
		
		var heightModules = $("#modules").height();
		var heightContent = $("#central-content").height();
				
		if(heightModules > heightContent){
			$("#central-content").height(heightModules + 10 + "px");
		}
	}
}

//===============================
// TOPNAVIGATION: DROPDOWN MENUS
//===============================
function createDropDownMenu(){
	var timeout = 500;
	var closetimer = 0;
	var ddmenuitem = 0;

	function jsddm_open(){
		jsddm_canceltimer();
		jsddm_close();
		ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
	}

	function jsddm_close(){
		if(ddmenuitem)
			ddmenuitem.css('visibility', 'hidden');
	}

	function jsddm_timer(){
		closetimer = window.setTimeout(jsddm_close, timeout);
	}

	function jsddm_canceltimer(){
		if(closetimer){
			window.clearTimeout(closetimer);
			closetimer = null;
		}
	}

	$('#topnavigation > li').bind('mouseover', jsddm_open);
	$('#topnavigation > li').bind('mouseout',  jsddm_timer);
	
	document.onclick = jsddm_close;
}

//===================
// FONT SIZER COOKIE
//===================
function setFontSize(dimension){	
	$("#container").css("font-size", dimension);
	$.cookie("font-size", dimension);
}

function checkActiveState(){
	var dimension = $.cookie("font-size");	
		
	if (dimension == "1.5em")
		$("#fontsize-large").addClass("active");
	else if (dimension == "1.25em")
		$("#fontsize-medium").addClass("active");
	else
		$("#fontsize-normal").addClass("active");
}

//===============================================================
// ONCLICK EVENT THAT REMOVES THE DEFAULT KEYWORD OF INPUTFIELDS
//===============================================================
function cleanUpKeyword(oObject){
	oObject.value = '';
}

//==========================================
// FAQ + REACTION FUNCTIONALITY: TOGGLEPANE
//==========================================
function togglePane(sElementId, sEffect, sBoolean){
	if(sBoolean == 'true'){
		if($('.open').attr('id') != sElementId){
			togglePane($('.open').attr('id'), sEffect, 'false');
		}	
	}
	
	if($('#' + sElementId).hasClass('close')){
		if (sEffect == 'slide'){
			$('#' + sElementId).slideDown('slow');
		}else if(sEffect == 'fade'){
			$('#' + sElementId).fadeIn('slow');
		}else{
			$('#' + sElementId).show('slow');
		}
		$('#' + sElementId).removeClass('close');
		$('#' + sElementId).addClass('open');
	}else{
		if (sEffect == 'slide'){
			$('#' + sElementId).slideUp('slow');
		}else if(sEffect == 'fade'){
			$('#' + sElementId).fadeOut('slow');
		}else{
			$('#' + sElementId).hide('slow');
		}
		$('#' + sElementId).removeClass('open')
		$('#' + sElementId).addClass('close');
	}
}

//================================
// FAQ FUNCTIONALITY: SHOWANSWER
//================================
function showAnswer(sElementId, sEffect){
	if($('#' + sElementId).hasClass('closed')){
		$('#' + sElementId).removeClass('closed')
		$('#' + sElementId).addClass('opened');
	}
	else{
		$('#' + sElementId).removeClass('opened')
		$('#' + sElementId).addClass('closed');
	}
	
	var splitted = sElementId.split('_')
	togglePane('toggable_' + splitted[1], sEffect, 'false');
}

//====================
// DOORMAT NAVIGATION
//====================
function setHover(field){
	$(field).parent().removeClass('gradient1');
	$(field).parent().addClass('gradient3');
}
function releaseHover(field){
	$(field).parent().removeClass('gradient3');
	$(field).parent().addClass('gradient1');
}
function redirect(url){
	if (url.match('http')) {
		window.open(url);
	}
	else {
		window.location = url;
	}
}

//============================
// SHOW GOOGLE DIRECTIONS MAP
//============================
function showGoogleMap(sElementId){
	if($('#' + sElementId).hasClass('close')){
		$('#' + sElementId).fadeIn('slow');
		$('#' + sElementId).removeClass('close');
		$('#' + sElementId).addClass('open');
	}else{
		$('#' + sElementId).fadeOut('slow');
		$('#' + sElementId).removeClass('open');
		$('#' + sElementId).addClass('close');
	}
}


//==================
// GOOGLE MAPS CODE
//==================
var map = null;
var geocoder = null;
var gdir;
var geocoder = null;
var addressMarker;

function initialize(address, coordinateLat, coordinateLong, zoom, bGMapTypeControl, bGSmallMapControl, bGOverviewMapControl) {
	if (GBrowserIsCompatible()) {
      	if (zoom == null || zoom == '')
      		zoom = 14;
      		
      	if(coordinateLat != null && coordinateLat != '' && coordinateLong != null && coordinateLong != '')
      		address = coordinateLat + ',' + coordinateLong;
      	
      	map = new GMap2(document.getElementById('map_canvas'));
      	map.setCenter(new GLatLng(50.879, 4.700), zoom);
      	
      	if(bGMapTypeControl == 'true')
      		map.addControl(new GMapTypeControl());
      	if(bGSmallMapControl == 'true')
      		map.addControl(new GSmallMapControl());
      	if(bGOverviewMapControl == 'true')
      		map.addControl(new GOverviewMapControl());
      	
		if(address != null && address != ''){
			geocoder = new GClientGeocoder();
			geocoder.getLatLng(address,
				function(point) {
					if (!point) {
						alert(address + ' not found');
					} else {
						map.setCenter(point, zoom);
						var marker = new GMarker(point);
						map.addOverlay(marker);
					}
				}
			);
		}
		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", onGDirectionsLoad);
		GEvent.addListener(gdir, "error", handleErrors);
	}
}

function setDirections(form) {
	if(checkMandatoryFields(form)){
		var fromAddress = form.from.value;
		var toAddress = form.to.value;
		var locale = "nl";
	
		checkMandatoryFields(fromAddress);
		gdir.load("from: " + fromAddress + " to: " + toAddress,{ "locale": locale });
		$('#directions').slideDown('slow');
		$('#resetbtn').css('display', 'block');
		$('#map_canvas').css('height',  '500px');	
	}
}

function resetGoogleMap(address){
	$('#directions').slideUp('slow');
	$('#resetbtn').css('display', 'none');
	$('#map_canvas').css('height',  '300px');
	initialize(address, '', '', 14, 'false', 'true', 'false');
	$('#directions').html('');
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	//else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//	alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");   
}

function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
}


//========================
// CHECK MANDATORY FIELDS
//========================
function checkMandatoryFields(form){
	if (form.id == 'googlemap'){
		if(checkField(form.from))
			return true;
		else 
			return false;
	}
	else
		return false;
}

function checkField(Element){
	var sElementValue = Element.value;
	
	if(sElementValue != '' && sElementValue != null){
		document.getElementById(Element.id + "-error").style.display = "none";
		return true;	
	}
	else {
		document.getElementById(Element.id + "-error").style.display = "block";
		return false;	
	}
}