$(document).ready(function() {
/*	staat onder in pagina deze is ter referentie 
	Cufon.replace('h1, h2');
	Cufon.replace($('#nav-main li a.cufon, #nav-main li div.big h4 span'),{ hover: true });
	Cufon.replace($('#nav-meta a'), { hover : true });
	Cufon.replace($('#cta-latest-reactions li a'),{ hover: true });
	Cufon.replace($('#cta-latest-news li a'),{ hover: true });
	Cufon.replace($('#cta-events li a'),{ hover: true });
	Cufon.replace($('#cta-locations li span'),{ hover: true });
	Cufon.replace($('#cta-locations li a'),{ hover: true });
	Cufon.replace($('#cta-programm li span'));
	Cufon.replace($('#cta-newsletter h3'),{ hover: true });
	Cufon.replace($('#footer #nav-footer a'),{ hover: true });	
	Cufon.replace($('#social-extras a'));
	Cufon.replace($('#social-media h3'));
	Cufon.replace($('#homepage-items .homepage-item a.share-twitter'),{ hover: true });
	Cufon.replace($('#cta-programm li a.showall'),{ hover: true });
	Cufon.replace($('#nav-sub li a'),{ hover: true });
	
	Cufon.replace($('#frm-programm-filters label, .event h3, .event h4, #programm-overview-switch a, #programm-overview-switch span'), { hover: true });
	Cufon.replace($('#frm-photovideo-filters label'));
	Cufon.replace($('#frm-locations-overview label'));
	Cufon.replace($('form span.intro-text'));
	Cufon.replace($('#programm-carrousel a'), { hover : true });
*/
	if(typeof(DD_belatedPNG) != 'undefined') {
		DD_belatedPNG.fix('*');
	}

	if(!$.cookie('endfestivalpopup')) { 
		if($(document).height() > $(window).height()) {
			oHeight = $(document).height()
		} else {
			oHeight = $(window).height();	
		}
		$('#popupEndOverlay').css({position: 'absolute',top: 0, left: 0, height: oHeight, width: '100%', zIndex: '10000',	opacity: '0.75', background: '#000'}).fadeIn();
		$('#popupEndBox').fadeIn();
		$('#popupEnd ').click(function(event) { event.stopPropagation(); });
		$('#popupEndClose, #popupEndBox').click( function () { $('#popupEndOverlay, #popupEnd').fadeOut(); return false;} )
		$.cookie('endfestivalpopup', 'true', { expires: 1, path : '/' });
	}
	
	if(window.print) {
		$('#print-btn').show().click(function(){
			if ($('#iframe-mac').length) {
				window.frames['iframe-mac'].print();
			} else {
				window.print();
			}
		});	
	}
	
	$('#social-extras a.btn-staf').click( function() { $('#frm-staf').toggleClass('show'); if(!$('#frm-staf').hasClass('show')){ return false; }});
	$('#social-extras a.btn-comment').click( function() { $('#frm-comment').toggleClass('show'); if(!$('#frm-comment').hasClass('show')){ return false; } });
	$('#social-extras a.btn-ecard').click( function() { $('#frm-ecard').toggleClass('show'); if(!$('#frm-ecard').hasClass('show')){ return false; } });

	if ($('#googlemap').length) {
		init_googleMap();
	}
	if(String(window.location.hash) == '#comment'){
		if(!$('#frm-comment').hasClass('show')){
			$('#social-extras a.btn-comment').click();
		}
	}

	secsToStart = $('#startTime').val();
	calculateCountDown();
	$('#cta-countdown').css({'display':'block'});
	/*
	$('.animation').each(function(){
		$(this).find('a').bannerAnimation();
	});
	*/
	$('.animation').each(function(){
		$(this).find('div.banner').bannerAnimation();
	});
	
	$('#search-q').focus().select();
	
	if($('#programm-carrousel-js').length == 1){
		var flashvars = {
			huidige_taal: $('#programm-carrousel-js').attr('lang'),
			schuif_delay: 5000
		}; 
		var params = { 
		  allowscriptaccess: "always",
		  wmode: "transparent",
		  menu: false
		}; 
		var attributes = { }; 
		swfobject.embedSWF("/swf/programma_header.swf?"+$('#swf-version').val(), "programm-carrousel-js", "960", "260", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
	}
	
	
	if($('#programm-overview-block-flash').length == 1){
		var flashvars = {
			huidige_taal: $('#programm-overview-block-flash').attr('lang'),
			datum: $('#programm-overview-block-flash #datum').val()
		}; 
		var params = { 
		  allowscriptaccess: "always",
		  wmode: "transparent",
		  menu: false,
		  salign: "lt"
		}; 
		var attributes = { }; 


		swfobject.embedSWF("/swf/programma_blokken.swf?"+$('#swf-version').val(), "programm-overview-block-flash", "610", "1100", "9.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);

	}	
	
	$('#photovideo-overview a.fancyboxphotos').fancybox({
		'titleShow'     : true,
		'titlePosition' : 'inside',
		'transitionIn'	: 'fade',
		'transitionOut'	: 'fade',
		'easingIn'      : 'easeOutBack',
		'easingOut'     : 'easeInBack'

	})
});

/*
*	Countdown script;
*/
var secsToStart;	
function calculateCountDown() {
	secsToStart--;
	
	var days = Math.floor(secsToStart/(60*60*24));
	var hours = Math.floor((secsToStart/(60*60)))%24;
	
	var minutes = Math.floor(secsToStart/(60))%60;
	var seconds = Math.floor(secsToStart)%60;

	if(days < 2 && days > 0 ) { 
		$('#cta-countdown .days small.long').hide();
		$('#cta-countdown .days small.short').show(); 
	}
	if(days > 1 || days == 0 ) { 
		$('#cta-countdown .days small.long').show();
		$('#cta-countdown .days small.short').hide(); 
	}
	if(hours < 10) { hours = '0' + hours }
	if(minutes < 10) { minutes = '0' + minutes }
	if(seconds < 10) { seconds = '0' + seconds }
	
	$('#cta-countdown .days big').html(days);
	$('#cta-countdown .time big').html(hours + ':' + minutes + ':' + seconds  );
	
	if(secsToStart > 0 ) { 
		window.setTimeout(calculateCountDown, 1000);
	}
}

/*
*	Sponsor banner script
*/
$.fn.bannerAnimation = function(options) { 
	var defaults = {
		speed : 5000,
		fadeSpeed : 1000,
		activeImage : 0,
		imageCount : 0,
		TO : ''
	};	
	
	var options = $.extend(defaults, options);
	var jQueryMatchedObj = this; 
	options.imageCount = jQueryMatchedObj.length;
				
	function start() {
		window.clearTimeout(options.TO);
		options.TO = window.setTimeout(function() { animateOut() }, options.speed); 
	} 	
	
	function animateIn()  {
		if (options.activeImage+1 < options.imageCount) {
			if($(jQueryMatchedObj[(options.activeImage+1)]).children('div.hiddenswf-container').length > 0) {
				$(jQueryMatchedObj[(options.activeImage+1)]).children('div.flash').html($(jQueryMatchedObj[(options.activeImage+1)]).children('div.hiddenswf-container').html());
			}
			$(jQueryMatchedObj[(options.activeImage+1)]).fadeIn(options.fadeSpeed, endAnimation);
		} else {
			if($(jQueryMatchedObj[0]).children('div.hiddenswf-container').length > 0) {
				$(jQueryMatchedObj[0]).children('div.flash').html($(jQueryMatchedObj[0]).children('div.hiddenswf-container').html());
			}
			$(jQueryMatchedObj[0]).fadeIn(options.fadeSpeed, endAnimation);
		}
	}
	
	function animateOut () {
		$(jQueryMatchedObj[(options.activeImage)]).fadeOut(options.fadeSpeed, function() { 
			if($(jQueryMatchedObj[(options.activeImage)]).children('div.flash').length > 0) {
				$(jQueryMatchedObj[(options.activeImage)]).children('div.flash').empty();
			}
			animateIn();
		});
	}
	
	function endAnimation() {
		if (options.activeImage+1 < options.imageCount) {
			options.activeImage++;
		} else {
			options.activeImage = 0;
		}
		start();
	}
	
	if($(jQueryMatchedObj[0]).children('div.hiddenswf-container').length > 0) {
			$(jQueryMatchedObj[0]).children('div.flash').html($(jQueryMatchedObj[0]).children('div.hiddenswf-container').html());
	}
	if(options.imageCount > 1) { 
		start(jQueryMatchedObj);
	}
	
}

/*
*	Googlemap script
*/

var kmlOverlay;
var googleMap;

function init_googleMap() {
	if (GBrowserIsCompatible()) {
		googleMap = new GMap($('#googlemap')[0]);
		googleMap.setCenter(new GLatLng(52.0782886, 4.313685), 15);

		var datum = $('#datum').val();
		var evenement_id = $('#evenement_id').val();
		var exclude = $('#gmap_exclude_id').val();
		var language = $('#googlemap').attr('lang');
		var url = 'http://' + getCurrentDomain() + '/xml/locaties.kml.php?a=a&lang=' + language + (datum ? '&datum='+datum : '' )+(evenement_id ? '&evenement_id='+evenement_id : '' )+(exclude ? '&exclude_id='+exclude : '');//+'&time='+(new Date().getTime());
		
		googleMap.setUIToDefault();
		loadKmlOverlay(url);
		
		GEvent.addListener(googleMap, "infowindowopen", function() {
			$('#googlemap a').attr("target","_self");
		});
	}
}

function loadKmlOverlay(url) {
	kmlOverlay = new GGeoXml(url, function() {
		_kmlOverlayLoader();
	});
}

var gm_timeout;

function _kmlOverlayLoader() {
	if (kmlOverlay.loadedCorrectly()) {
		/**
		* Listener die ervoor zorgt dat bij het aanklikken van een
		* placemark (en dus openen van de balloon) de KML niet opnieuw 
		* ingeladen wordt.
		* Daarnaast een fix om de links in de balloon niet in een nieuw
		* venster te laten openen
		*/          
		
		var defaultCenter = kmlOverlay.getDefaultCenter();
		if (defaultCenter.x > 0 || defaultCenter.y > 0) {
			googleMap.addOverlay(kmlOverlay);
			googleMap.setZoom(googleMap.getBoundsZoomLevel(kmlOverlay.getDefaultBounds(), googleMap.getSize())); 
			googleMap.panTo(defaultCenter);
		}
				
		var x = $('#gmap_x').val();
		var y = $('#gmap_y').val();
		var locationTitle = $("h1").text();
		
		if (x && y) {
			var latlng = new GLatLng(y, x);
			var icon = new GIcon();
			icon.image = "/img/2010/pointer-actief.png";
			icon.iconSize = new GSize(32, 37);
			icon.iconAnchor = new GPoint(16, 37);
			
			var marker = new GMarker(latlng, {
				icon : icon,
				title : locationTitle
			});
			
			googleMap.addOverlay(marker);
			googleMap.setCenter(latlng, 15);
		
		}
	
	} else {
		gm_timeout = window.setTimeout(function(){ _kmlOverlayLoader() }, 500);
	}
}



// if(GBrowserIsCompatible()) {
// 	googleMap.
// 	var customUI = map.getDefaultUI();	
// 	map.setCenter(new GLatLng(51.532415,4.446),15);
	
// 	var latlng = new google.maps.LatLng(-34.397, 150.644);
//     var myOptions = {
//       zoom: 15,
//       center: new google.maps.LatLng(51.535015,4.446),
//       mapTypeId: google.maps.MapTypeId.ROADMAP
//     };
//     var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);
    
// 	var myLatLng = new google.maps.LatLng(51.532536, 4.446845);
// 	new GMarker(point)
// 	var marker = new google.maps.Marker({
// 	    position: myLatLng,
// 	    map: map,
// 	    title:"SES - West-brabant",
// 	    icon: 'http://maps.gstatic.com/intl/en_ALL/mapfiles/ms/micons/blue-dot.png'
// 	});
// 	var html = '<div style="margin-top:10px;">' +
// 					'<p>Uw adres (straat, woonplaats) of postcode</p><form action="http://maps.google.nl/maps" method="get" target="_blank">' +
// 					'<input type="text" size="20" maxlength="40" name="saddr" id="saddr" value="" class="text" />' +
// 					'<input value="Routebeschrijving" type="submit" class="button" />' +
// 					'<input type="hidden" name="daddr" id="daddr" value="corneliusflat roosendaal, Nederland" /></form></div>';
// 
// 
// 	var infowindow = new google.maps.InfoWindow({
// 	    content: '<span style="font-weight: bold; font-size: medium; margin-bottom: 0em;">SES - West-brabant</span><div dir="ltr">Cornelius - Flat 11-12<br>4703 BV Roosendaal</div>'+html
// 	});
// 	
// 	google.maps.event.addListener(marker, 'click', function() {
// 	  infowindow.open(map,marker);
// 	});
// 	infowindow.open(map,marker);
// 	google.maps.event.click();
//     var myParser = new geoXML3.parser(map);
// 	myParser.parse(defaultKML);
//     KMLoverlays['pageDefault'] = load_KML(defaultKML,'pageDefault');
// }


function entireDivClick () {
		if($(this).find("a").attr("target") == '_blank'){
			if(typeof $(this).find("a").attr("href") != 'undefined'){
				window.open($(this).find("a").attr("href"));
			}
		}else{
			if(typeof $(this).find("a").attr("href") != 'undefined'){
				window.location = $(this).find("a").attr("href");
			}
		}
		return false;
	}


function getCurrentDomain() {
	return document.domain;
}


function register_flash_click(click_url) {
	pageTracker._trackPageview('/uitgaandelink/banner/'+click_url);
}




/**
 	* jquery.cookie.js - rev 2
 	* Requires: jQuery 1.2+ 
 	* Author: Stephan van Opstal <stephan@netvlies.nl>
 	* Created: 2008-09-23 | Updated: 2008-09-24
	* (This plugin is a rewrite of jquery.cookie.js by Klaus Hartl/klaus.hartl@stilbuero.de)
	*
	* Usage:
	* $.cookie(cookiename, value, options);
	*
	* Examples:
	* $.cookie('cookiename'); // get cookie
	* $.cookie('cookiename', 'cookievalue'); // set cookie
	* $.cookie('cookiename', null); // destroy cookie
	* $.cookie('cookiename', 'cookievalue', { expire: 7 }); // destroy cookie after 7 days
	* 
	* Options:
	* expire: integer // An expiry date after which it is no longer valid
	* path: string // The path of the server it should be sent to
	* domain: string // The domain it should be sent to
 	*/


(function($)
{
	$.cookie = function(name, value, options)
	{
		// set cookie
		if (typeof value != 'undefined')
		{
			// extend options
			options = options || {};
			
			// destroy cookie if value is set to null
			if (value === null) { options.expires = -1; }
			
			var cookieExpires = '';
		
			// only set expiration date if parameter was set
			if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString))
			{
	            if (typeof options.expires == 'number')
				{
	                var date = new Date();
	                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
	            }
				else
				{
	                var date = options.expires;
	            }
				
				var cookieExpires = '; expires=' + date.toUTCString();
			}
			
			var cookieName = name +'='+ encodeURIComponent(value);
			var cookiePath = options.path ? '; path=' + (options.path) : '';
			var cookieDomain = options.domain ? '; domain=' + (options.domain) : '';
			
			// write cookie
			document.cookie = cookieName + cookieExpires + cookiePath + cookieDomain;
		}
		// get cookie
		else
		{
			var cookieValue = null;
			
			if (document.cookie != '')
			{
				var cookies = document.cookie.split(';');

				for (var i=0; i<cookies.length; i++)
				{
					var cookie = $.trim(cookies[i]);
					
					// check if this is the correct cookie
					if (cookie.substring(0, name.length + 1) == (name + '='))
					{
						cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						break;
					}
				}
			
				return cookieValue;
			}
		}
	};
})(jQuery);
