// browser sniffer
var Browser = function(){
  this.uA = navigator.userAgent.toLowerCase();
  this.aN = navigator.appName.toLowerCase();
  this.iE = this.aN.indexOf('microsoft') != -1 ? 1 : 0;
  this.mac =  this.uA.indexOf('mac') != -1 ? 1 : 0;
  this.win = this.uA.indexOf('windows') != -1 ? 1 : 0;
  this.safari =  this.uA.indexOf('webkit') != -1 ? 1 : 0;
  this.opera =  this.uA.indexOf('opera') != -1 ? 1 : 0;   
  this.operaMini =  this.uA.indexOf('mini') != -1 ? 1 : 0;  
  this.mozilla = this.aN.indexOf('netscape') != -1 && !this.safari ? 1 : 0;
  this.winMozilla = this.mozilla && this.win ? 1 : 0;
  this.winIE = this.iE && this.win && !this.opera ? 1 : 0;
  this.winIE6Down = this.winIE && parseInt(this.uA.split('msie ')[1].substring(0,1)) <= 6 ? 1: 0;
  this.macIE = this.iE && this.mac ? 1 : 0;
};
var browser = new Browser();
	

// addStyle
var addStyle = function(selector,properties){
  if (document.styleSheets) {
    var s = document.getElementsByTagName('STYLE');
    if (s.length == 0){
      var sheet = document.createElement('style');
      sheet.setAttribute('type','text/css');
      document.getElementsByTagName('HEAD')[0].appendChild(sheet);}
    if (browser.winIE){
      var lastSheet = document.styleSheets[document.styleSheets.length - 1];
      lastSheet.addRule(selector, properties);}
    else {var lastSheet = s[0];
      lastSheet.appendChild(document.createTextNode(selector + ' { ' + properties + ' }'));}
  	}
};
addStyle('.drempel','display:none;');
addStyle('.noscript','display: block !important;');


//incl. .js
var jsPath = "/js/";
//document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.event.hover.js"><\/scr'+'ipt>');
//document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.easing.js"><\/scr'+'ipt>');
//document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'jquery.scroll.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'mv2_zoom.js"><\/scr'+'ipt>');
//document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'AC_RunActiveContent.js"><\/scr'+'ipt>');
document.write('<scr'+'ipt type="text/javascript" src="' + jsPath + 'sifr.js"><\/scr'+'ipt>');

//layout on DomLoad
	$.fn.layOut = function(){
	
	
	//flash header hover animate
	//$("#flashheader").bind( "hover", { speed:200, delay:200 }, function(){ ... });
	// $("#flashheader").hover(function(){
	// 		$(this).animate({ height: "40em" }, { easing:'easeOutQuad', queue:false, duration:600} );
	// 	},function(){
	// 		$(this).animate({ height: "11.5em" }, { easing:'easeOutQuad', queue:false, duration:400} );
	// 	});
	
	if (browser.winIE6Down){
		$(".bg-wave-right").prepend('<div class="append-wave-white-right"><!-- --></div>');
		$(".bg-wave-left").prepend('<div class="append-wave-white-left"><!-- --></div>');
	};
	
	
	$(".wave-white-right-overlay").each(function(){ addWhiteOrGreyOverlay($(this)); });
	$(".wave-white-left-overlay").each(function(){ addWhiteOrGreyOverlay($(this)); });
	$(".wave-grey-right-overlay").each(function(){ addWhiteOrGreyOverlay($(this)); });
	$(".wave-grey-left-overlay").each(function(){ addWhiteOrGreyOverlay($(this)); });
	
	if (browser.winIE){
		$('input:checkbox, input:radio').css({ border: "none", background: "none" });
	};
	
};

//add white or gray wave on element, depending on next div
function addWhiteOrGreyOverlay(el){
	var dir = ($(el).attr('class').indexOf('-right-')>0) ? 'right' : 'left';
	var next = el.next('div.bg-light-grey:first');
	if(next.length > 0){
		el.prepend('<div class="append-wave-grey-'+dir+'"><!-- --></div>');
	}
	else{
		el.addClass('msbott');
		el.prepend('<div class="append-wave-white-'+dir+'"><!-- --></div>');
	}
}

// $(document).ready(function(){
// 	window.setTimeout(function() {
// 		$("#flashheader").animate({ height: "11.5em" }, { easing:'easeOutQuad', queue:false, duration:400} );
// 	}, 2000);
// 
// });

//autoscroll to anchor (confirms to ID from anchor)	
$.fn.scrollLinks = function() {
	$(this).click(function () { 
		var el = $('#' + this.href.split('#')[1]).parent().parent();
//		window.setTimeout(function() {
			// depends on jQuery scroll plugin
			// @TODO implement ui.harmonica
//			$.scrollTo( el, 800, { easing:'easeOutQuad' });
//		}, 500);
		return false;
	});
};

//activate thumbnailGallery
$.fn.thumbnailGallery = function(className){
	$(this).find(className).each(function(i){
		/* CONFIG */
		var useUIblock 	= false; 	// true/false to block/permit clicking thumbs when a thumb is enlarged [Boolean]
		var zIndex 		= 10; 		// enlarged image's z-index: zIndex > 0 [Integer]
		var lbOpacity 	= .25; 		// lightbox opacity: 0 < lbOpacity < 1 [Number]
		var lbColor 	= 'white'; 	// lightbox color : any valid CSS value [String]
		var wTarget 	= '_blank'; // target-attribute of the anchor's href to the full-size image : any valid HTML-target value [String]
		/* PB - This is hardly half-complete ... works for maasvlakte2 ... requires jQuery 1.2.3+
		 * z-index used: 10
		 * Mandatory HTML structure ! (TODO: do some HTML-manipulation on [className]-element to be generic):
		 * <div id="content">
		 * 	...whatever...
		 * 		<div class="two-third-pane">
		 * 			<div class="[className]">
		 * 				...whatever (but not <a>) + thumbs as:
		 * 					<div><a href="url_to_full_size_image"><img src="img_thumb_url" /></a></div>
		 * 				<div class="clearfix"></div>
		 * 			</div>
		 * 		</div>
		 * </div>
		 */
		// terrible hack to obtain fail-safe available height...
//		var contentHeight = Math.max($('#content').find('.clearfix:last').height(), 500);
		var container = $(this).parents('.padding-small:first');//.two-third-pane:first');
		var contentHeight = Math.max(container.height(), 500);
		// container's dimensions
		var cw = container.width();
		var ch = container.height();
		var cl = container.position().left;
		var ct = container.position().top;
		// slightly fuzzy padding correction ...
		var vpoffset = $(this).offset();
		var coffset = container.offset();
		var lpad = vpoffset.left-coffset.left;
		var tpad = vpoffset.top-coffset.top;
		container.append('<div class="UIblock hide" style="padding:0; position:absolute; opacity: 0; height:auto; background: '+lbColor+'; z-index:'+zIndex+';"></div>');
		container.append('<img class="viewport_img" src="" style="position:absolute; display: block; z-index:'+zIndex+';" />');
		container.append('<a class="img_link hide" href="#" target="'+wTarget+'" style="padding:0; text-align:center; font-size:10px; background:'+lbColor+'; top:0; position:absolute; opacity: 0.5; display:block; z-index:'+zIndex+'; "></a>'); //url(\'/images/icon-arrow-blue.png\') left center no-repeat
		container.find('.UIblock').css(useUIblock==true ? {} : {visibility:'hidden'})
			.click( function(){
				var UIblock = $(this);
				var viewport_img = container.find('.viewport_img');
				var img_link = container.find('.img_link');
				UIblock
					.animate({top:ct+'px', left:cl+'px', width:"0", height:"0", opacity:"0"}, 1000, "linear", function(){UIblock.hide(); container.css('height','auto');});
				viewport_img
					.animate({top:ct+'px', left:cl+'px', width:"0", opacity:"0"}, 1000, "linear", function(){viewport_img.hide();});
				img_link
					.animate({top:ct+'px', left:cl+'px'}, 1000, "linear", function(){img_link.hide();});
			}).mouseover( function(){ 
				$(this)
					.css({cursor:'pointer'})
//					.html('<div style="padding-left:'+lpad+'">close</div>')
//			}).mouseout( function(){ 
//				$(this)
//					.html('')
			})
			.hide() //hide
			.click(); //execute click
		container.find('.viewport_img').click(function(){ //define click
			container.find('.UIblock').click();
		}).mouseover( function(){ //define over
			$(this).css({cursor:'pointer'})
		});
		$(this).find('a').css({overflow:'hidden'})
		$(this).find('a').each(function(){
			//prepare the pop-up image src before the actual click; otherwise we can't read it's dimensions
			var a = $(this);
			var pos = a.offsetParent().position();
			var img = new Image();
			img.src = a.attr('href');
			a.click(function(event){
				var vpscale = Math.min(cw/img.width, Math.min(contentHeight/img.height, 1));
				var tLeft = (vpoffset.left - lpad)+cw/2-Math.min(cw, vpscale * img.width)/2;
				var tTop = (vpoffset.top - tpad)+contentHeight/2-Math.min(contentHeight, vpscale * img.height)/2;
				container.find('.img_link')
					.html(a.find('span').html())
					.attr({href: a.attr('href')})
					.show()
					.animate({left: tLeft+'px', top: tTop+'px', width: Math.max(a.width(), Math.min(cw, vpscale * img.width))+'px', opacity:'.75'}, 500);
				container.find('.viewport_img')
					.css({ left: pos.left+'px', top: pos.top+'px'})
					.attr('src', $(this).attr('href'))
					.show()
					.animate({left: tLeft+'px', top: tTop+'px', width: (vpscale * img.width)+'px'/*, height: img.height+'px'*/, opacity:'1'}, 500);
				container.animate({height:Math.max(500,container.height())+'px'},250);
				container.find('.UIblock')
					.css({ left: pos.left+'px', top: pos.top+'px'})
					.show()
					.animate({left: (vpoffset.left - lpad)+'px', top: (vpoffset.top - tpad)+'px', width: cw+'px', height: contentHeight+'px', opacity:'.25'}, 500);
				event.preventDefault();
			});
		});
	});
}

/* toggle input value */
$.fn.toggleVal = function(id, class1, class2) {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};

// toggle div sequence; 
$.fn.toggleSeq = function(id, class1, class2) {
	var class2Els = $('#'+id+' li a.'+class2);
	if(class2Els.length>0) { 	// intitialize on the html-defined compartiment
		class2Els.next('div.drempel').show();
	}else{ 						// intitialize on the 1st compartiment
		$('#'+id+' li a:first').addClass(class2);
		$('#'+id+' li div:first').show();
	}
	$('#'+id+' li a').click(function() {
		var checkElement = $(this).next();
		if((checkElement.is('div.drempel')) && (checkElement.is(':visible'))) {
			return false;
		}
		if((checkElement.is('div.drempel')) && (!checkElement.is(':visible'))) {    
			$('#'+id+' li a').removeClass(class2);
	        $(this).addClass(class2);
			$('#'+id+' div.drempel:visible').animate({ height: 'toggle' }, {queue:true, duration:600});//, opacity: 'toggle' breaks cleartype IE7	
				checkElement.animate({ height: 'toggle'}, {queue:true, duration:600});//, opacity: 'toggle' breaks cleartype IE7
			return false;
		}
	});
};

$.fn.toggleDiv = function(text1, text2, class1, class2) {
	return this.toggle(function(){
		var el = $('#' + this.href.split('#')[1]);
        $(this).text(text2);
        $(this).removeClass(class1);
        $(this).addClass(class2);
       	el.animate({ height: 'toggle'}, {queue:false, duration:600});//, opacity: 'toggle' breaks cleartype IE7
    },function(){
		var el = $('#' + this.href.split('#')[1]);
        $(this).text(text1);
        $(this).removeClass(class2);
        $(this).addClass(class1);
        el.animate({ height: 'toggle'}, {queue:false, duration:400});//, opacity: 'toggle' breaks cleartype IE7
    });
};

//open external links in new window
$.fn.externalLinks = function() {
	var localDomain = (location.href.split('/')[2]);
	var localExtensionsInNewWindow = Array('doc','xls','pdf');
	var list = $(this).find('a:not(#footer a, #header a)');
	for (var i = 0; i < list.length; i++){
		var aEl = list[i];
		var aElHref = aEl.href;
		// check for extensions
		var extension = (aElHref.substring(aElHref.length - 4,aElHref.length)).toLowerCase();
		var foundExtension = false;
		for (var j = 0; j < localExtensionsInNewWindow.length; j++){
			if (extension == '.' + localExtensionsInNewWindow[j]){
				foundExtension = true;
				break;
			}
		}
		// open in new window if conditions are right
		if ((aElHref.split('/')[2] != localDomain && aElHref.indexOf('mailto:') == -1 && aElHref.indexOf('javascript:') == -1) || foundExtension){
			var a_title = $(aEl).attr('title') ? $(aEl).attr('title') : '';
			$(aEl).addClass('external').attr('title', a_title + ' (external link)');
			aEl.onclick = function(){
				window.open(this.href);
				return false;
			}
		}
	}
};

var captureInternalAnchor = function() {
	$items = $('.captureInternalAnchor');
	$items.each(function(index, el){
		$(el).find('a.internalAnchor:first').click(function(e){e.stopPropagation()});
		$(el).bind('mouseover',function(e){	
			$(el).toggleClass('bg-light-grey').find('a').css('textDecoration', 'underline');
			e.stopImmediatePropagation()
		}).bind('mouseout',function(e){	
			$(el).toggleClass('bg-light-grey').find('a').css('textDecoration', 'none');
			e.stopImmediatePropagation()
		}).bind('click', function(e){
			// there is an event-issue with not-external links ( $.fn.externalLinks() ..? ): 
			// the event is cancelled for unknown reasons 
			// ...so we define custom behaviour here to fix this
			var ia = $(el).find('a.internalAnchor:first');
			if( ia.hasClass('external') ){
				$(el).find('a.internalAnchor:first').click();
			}else{
				document.location.href = $(el).find('a.internalAnchor:first').attr('href')
			}
			e.stopImmediatePropagation();
		});
	});
}

// lazy rollover with preload
$(document).ready( function(){
   lazy.rollover.init();
});
lazy = {};
lazy.rollover = {
   init: function() {
      this.preload();
      $(".rollover").hover(
         function () { $(this).attr( 'src', lazy.rollover.newimage($(this).attr('src')) ); }, 
         function () { $(this).attr( 'src', lazy.rollover.oldimage($(this).attr('src')) ); }
      );
   },
   preload: function(){
      $(window).bind('load', function() {
         $('.rollover').each( function( key, elm ) { $('<img>').attr( 'src', lazy.rollover.newimage( $(this).attr('src') ) ); });
      });
   },
   newimage: function( src ){ 
      return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_o' + src.match(/(\.[a-z]+)$/)[0]; 
   },
   oldimage: function( src ){ 
      return src.replace(/_o\./, '.'); 
   }
};

// FontReplacement
//, sWmode : "transparent" or , sWmode : "opaque"
$.fn.do_sIFR = function(){
	if(typeof sIFR == "function"){
		sIFR.replaceElement("div.related .docu", "/fonts/documenta.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
		sIFR.replaceElement(".docu", "/fonts/documenta.swf", named({sColor : "#001F4B", sWmode : "transparent"}));
		sIFR.replaceElement(".wdocu", "/fonts/documenta.swf", named({sColor : "#FFFFFF", sWmode : "transparent"}));
		sIFR.replaceElement(".futu", "/fonts/futura.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
		sIFR.replaceElement(".page_column h3.wfutu", "/fonts/futura.swf", named({sFlashVars: "&offsetTop=4", sColor : "#FFFFFF", sWmode : "transparent"}));
		sIFR.replaceElement(".wfutu", "/fonts/futura.swf", named({sColor : "#FFFFFF", sWmode : "transparent"}));
// disabled: zie ticket #175
//		sIFR.replaceElement(".html-editor h2", "/fonts/futura.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
//		sIFR.replaceElement(".html-editor h3", "/fonts/futura.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
//		sIFR.replaceElement(".html-editor h4", "/fonts/futura.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
//		sIFR.replaceElement(".html-editor h5", "/fonts/futura.swf", named({sColor : "#009CDA", sWmode : "transparent"}));
	}
};

//DOM loader
function init() {
	if (arguments.callee.done) return;
	arguments.callee.done = true;
	
	$('html').layOut();
	$('html').do_sIFR();
	$('html').externalLinks();
	$('.togval').toggleVal();
	//$('a.toggle').toggleDiv('meer opties','minder opties','','');
	//$('a.togplusmin').toggleDiv(null,null,'plus','min');
	$('html').toggleSeq('faq','faq-plus','faq-min');
	$('html').toggleSeq('actueel','actueel-plus','actueel-min');
	
	$('.tablist').each(function() {
//		var tablist = $(this);
//		tablist.tabs({fx: { opacity: 'toggle' } })
//		.find('ul:eq(0) > li a.top-icon').each(function(i) {
//			$(this)
//			.bind('mouseover', function(event) {
//				tablist.tabs('select',i);
//			})
////			.bind('click', function(event) {
////				//console.log($(this).attr('href'))
////			})
//			;
//		});
//		console.log(tablist.tabs('option', 'tabTemplate'));
//		console.log(tablist.tabs('length'));
	});
	$('.scroll').scrollLinks();
	$('html').thumbnailGallery('.gallerythumbs.image');
	$('form').find('.required').each( function(){
		var str = $(this).html();
		$(this).html( str + ' *' ); 
	});
	captureInternalAnchor();
	if(browser.winIE) {try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {};}
	if (browser.safari) { $('input[type=file]').css({ backgroundColor: "transparent", border: "none"}); };
	
};
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, null);
}
if (/WebKit/i.test(navigator.userAgent)) {  
var _timer = setInterval(function() {        
	if (/loaded|complete/.test(document.readyState)) {            
		clearInterval(_timer); init();}}, 10);
};
// for Internet Explorer (using conditional comments)
/*@cc_on @*/
/*@if (@_win32)document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {    
	if (this.readyState == "complete") {        
		init();  
	}
};
/*@end @*/

window.onload = init;


