/////////////////////////////////////////// BASIC FUNCTIONS, DON'T EDIT ///////////////////////////////////////////

/*
 * Starts executing the initializing functions when either the DOM structure of the page has been loaded ('domready'), or the entire page ('load').
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses Mootools 1.2.1 JavaScript Library
 */
window.addEvents({
	'domready': function() {
		initExternalLinks();
		initLightbox();
		initHoverFixIE6();
		fixIESendButtonRemoveLines();
		loadRouteMap();
		initFormSubmitButton();
		initLightboxCloseButton();
		f04_pushboxSlideShow();
		f5_aanmelden_submit();
		f6_bestellen_submit();
		initFormF23();
		initFormF26();
		initTopSearch();
		submitForm();
//		initSubscriptionTooltips();
		
		if (document.getElements('form.formcontainer div.block-datum').length > 0) {
			makeEqualHeight(document.getElements('form.formcontainer div.block-datum'), 3);
		}
		
	},
	'load': function() {
		fixHeaderTranspIE6();
		f13PromoBoxEqualHeight();
		f14PromoBoxSmallEqualHeight();
		initF34SitemapSubcatHeights();
		//initGoogleAnalytics();
	}
});


/**
* equals the height of the elements in an array
*
* @author Mirjam
* @since 1.0, dec 2010
* @param array - elements to equalize
* @param integer - optional amount of columns per row
*/

function makeEqualHeight(arrElements, intColumns) {
	
	var intMaxheight = 0;
	var arrCurrentRow = new Array();
	
	arrElements.each(function(item, index) {
		
		item.setStyle('height', 'auto');
		var intHeight = item.getSize().y;
		if (intHeight > intMaxheight) {
			intMaxheight = intHeight;
		}
		arrCurrentRow.push(item);
		
		
		if((index+1)%intColumns == 0) {
			arrCurrentRow.each(function(el) {
				el.setStyle('height', intMaxheight);
			});
			intMaxheight = 0;
			arrCurrentRow = [];
		}
		
	});
	
	arrCurrentRow.each(function(el) {
		el.setStyle('height', intMaxheight);
	});
	
}


/*
 * initExternalLinks
 * Opens external links valid in a new window without the target attribute.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses <a href="http://www.efocus.nl/" class="external">eFocus</a>
 */
function initExternalLinks() {
	var arrExternalLinks = $$('a.external');
	if (arrExternalLinks.length == 0) return;
	
	arrExternalLinks.each(function(elExternalLink) {
		elExternalLink.addEvent('click', function(event) {
			event.stop();
			window.open(this.get('href'));   
		});
	});
}



/*
 * fixIESendButtonRemoveLines
 * Removes the dotted lines around the form_button links.
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 */
function fixIESendButtonRemoveLines() {
	$$('a.form_button').addEvent('focus', function(){this.blur()});
}



/*
 * initLightbox
 * Initializes the Shadowbox lightbox (shadowbox.js and shadowbox-mootools.js adapter needed!).
 * 
 * @author CSD (clientsidedevelopers[AT]efocus.nl)
 * @uses <a href="/siteimg/temp/visual.jpg" rel="shadowbox">View image in lightbox</a>
 */
function initLightbox() {
	var options = {
		overlayColor: '#000000',
		overlayOpacity: 0.8,
		continuous: true,
		counterType: 'skip'
	};

	Shadowbox.init(options);
}



/////////////////////////////////////////// CLIENT-SIDE JAVASCRIPT FUNCTIONS ///////////////////////////////////////////

/*
 * fixHeaderTranspIE6
 * 
 * fixes png transparency for header logo_overlay div in IE6
 * 
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 */
function fixHeaderTranspIE6() {
	if(Browser.Engine.trident && Browser.Engine.version < 5) {
		var overlay = document.getElement('div.logo_overlay');
		if(!overlay) return false;
		
		var bgUrl = overlay.getStyle('background-image');
		bgUrl = bgUrl.substring(4, bgUrl.length - 1);
		
		overlay.removeProperty('style');
		overlay.set('html', '<div style=\'filter: progid:DXImageTransform.Microsoft.AlphaImageLoader (src="/' + bgUrl + '", sizingMethod="image")\'></div>');
		overlay.getElement('div').setStyles({
			background: 'none',
			width: overlay.getSize().x,
			height: overlay.getSize().y
		});
		
	}
}



/*
 * initHoverFixIE6
 * 
 * fixes layer hover for ie6
 * 
 * @author Phison Do(phison.do[AT]efocus.nl)
 * @editor Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 */
function initHoverFixIE6 (){
	if (Browser.Engine.trident && Browser.Engine.version < 5) {
	
		if (!$('main_nav')) return;
		
		var arrMenuListItems = $('main_nav').getElements('li');
		
		arrMenuListItems.each(function(elMenuListItem){
			elMenuListItem.addEvent('mouseenter', function(){
				this.addClass('hover');
				showHideSelects(false);
			});
			elMenuListItem.addEvent('mouseleave', function(){
				this.removeClass('hover');
				showHideSelects(true);
			});
		});		
	}
}



/**
 * showHideSelects
 * hide selects: ie6
 *
 * @author Mirjam <mirjam{AT}efocus.nl>
 * @return void
*/

function showHideSelects(show) {

    var selects = $$('select');
    selects.each(function(item) {
        if (show == false) {
            item.setStyle('visibility', 'hidden');
        } else if (show == true) {
            item.setStyle('visibility', 'visible');
        }
    });
   
}


/*
 * loadRouteMap
 * Loads a map with a custom icon using Google Maps.
 * @author Ralph Meeuws (ralph-meeuws[AT]efocus.nl)
 * @editor Erhan Karadeniz (erhan.karadeniz[AT]efocus.nl
 */
function loadRouteMap() {
	if (!$('route_map')) return;
	
	var elRouteMap = $('route_map');
	var elRouteZip = $('route_zip');
	var elRouteBtn = $('route_button');
	var elRouteDir = $('route_directions');

	var strCompanyName = $('company_name').innerHTML;
	var strCompanyStreet = $('company_street').innerHTML;
	var strCompanyCity = $('company_city').innerHTML;
	var strBalloonContent = '<h4>' + strCompanyName + '</h4>' + '<p>' + strCompanyStreet + '<br />' + strCompanyCity + '</p>';
	var locale = 'nl_NL';

	if (GBrowserIsCompatible()) {
		var map = new GMap2(elRouteMap);
		var geocoder = new GClientGeocoder();
	
		var gdir = new GDirections(map, elRouteDir);
		
		var strAddress = strCompanyStreet + ', ' + strCompanyCity;

		function showAddress(address) {
			geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						map.setCenter(point, 12);
						
						var diagoIcon = new GIcon();
						diagoIcon.image = "../../img/icon_iir_logo.png";
						diagoIcon.iconSize = new GSize(24, 32);
						diagoIcon.iconAnchor = new GPoint(9, 34);
						diagoIcon.infoWindowAnchor = new GPoint(7, 20);
						diagoIcon.shadow = "../../img/icon_iir_logo_shadow.png";
						diagoIcon.shadowSize = new GSize(40, 32);
						
						markerOptions = { icon:diagoIcon };
						var marker = new GMarker(point, markerOptions);
											
						map.addOverlay(marker);
//						map.addControl(new GLargeMapControl());
//						map.addControl(new GMapTypeControl());
						map.setUIToDefault();

						marker.openInfoWindowHtml(strBalloonContent);
						
						GEvent.addListener(marker, "click", function() {
							marker.openInfoWindowHtml(strBalloonContent);
						});

					}
				}
			);
		}
		
		showAddress(strAddress);
	}
	
	elRouteBtn.addEvent('click', function(){
	  	strRouteZip = elRouteZip.value;
		gdir.load('from: ' + strRouteZip + ' to: ' + strAddress, { 'locale': locale });
	});
	
	elRouteZip.addEvent('keydown', function(event){
		if (event.key == 'enter') {
	  		strRouteZip = elRouteZip.value;
			gdir.load('from: ' + strRouteZip + ' to: ' + strAddress, { 'locale': locale });
		}
	});
}



/**
 * initFormSubmitButton
 *
 * form button submits
 *
 * @author Phi Son do <phison.do{AT}efocus.nl>
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @return void
 */

function initFormSubmitButton() {
	if (!document.getElement('.formulier form a.send_button')) return false;
	
	var elFormContact = document.getElement('.formulier form');	
	var elFormButton = elFormContact.getElement('a.send_button');

	elFormButton.addEvent('click', function(){
		elFormContact.submit();
	});	
}


/**
 * f6_bestellen_submit
 *
 * form button submits
 *
 * @author Gijs Oliemans <gijs.oliemans{AT}efocus.nl>
 * @return void
 */
function f6_bestellen_submit(){
	if (!document.getElement('.f6_bestellen form')) return false;
	
	var elF6Form = document.getElement('.f6_bestellen form');	
	var elF6Button = elF6Form.getElement('a.button');
	var elF6Select =  elF6Form.getElement('select');

	elF6Button.addEvent('click', function(){
		if(elF6Select.selectedIndex != 0){
			elF6Form.submit();
			return false;
		}else{
			return false;
		}
	});	
}




/**
 * f5_aanmelden_submit
 *
 * form button submits
 *
 * @author Gijs Oliemans <gijs.oliemans{AT}efocus.nl>
 * @return void/false
 */
 
function f5_aanmelden_submit(){
	if (!document.getElement('.f5_aanmelden')) return;
	
	var elF5Form = document.getElement('.f5_aanmelden').getElement('form');
	var elF5Select =  elF5Form.getElement('select');		

	if (elF5Form) {

		var elF5Button = elF5Form.getElement('a.button');

		elF5Button.addEvent('click', function(){			
			if(elF5Select.selectedIndex != 0) {
				window.location = elF5Select.options[elF5Select.selectedIndex].value;
				return false;
			}else{
				return false;
			}
		});
			
	}

}



/**
 * f13PromoBoxEqualHeight
 * Calculates equal heights to all promoboxes
 * 
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function f13PromoBoxEqualHeight() {
	if (!document.getElement('.subcolumn')) return;
	var arrF13PromoBoxes = document.getElement('.subcolumn').getElements('.f13_promobox');
	if (arrF13PromoBoxes.length == 0) return;
	
	var intF13PromoBoxHeightMax = 0;
	
	arrF13PromoBoxes.each(function(elF13PromoBox){
		if (elF13PromoBox.getHeight() > intF13PromoBoxHeightMax) {
			intF13PromoBoxHeightMax = elF13PromoBox.getHeight();
		}
	});
	arrF13PromoBoxes.each(function(elF13PromoBox){
		elF13PromoBox.setStyle('height', intF13PromoBoxHeightMax);
	});
}



/**
 * f14PromoBoxSmallEqualHeight
 * Calculates equal heights to all small promoboxes
 * 
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function f14PromoBoxSmallEqualHeight(){
	if (!document.getElement('.subcolumn')) return;
	var arrF14PromoBoxesSmall = document.getElement('.subcolumn').getElements('.f14_promobox_small');
	if (arrF14PromoBoxesSmall.length == 0) return;

	var intF14PromoBoxSmallHeightMax = 0;
	
	arrF14PromoBoxesSmall.each(function(elF14PromoBoxSmall){
		if (elF14PromoBoxSmall.getHeight() > intF14PromoBoxSmallHeightMax) {
			intF14PromoBoxSmallHeightMax = elF14PromoBoxSmall.getHeight();
		}
	});
	arrF14PromoBoxesSmall.each(function(elF14PromoBoxSmall){
		elF14PromoBoxSmall.setStyle('height', intF14PromoBoxSmallHeightMax);
	});
}



/**
 * initF34SitemapSubcatHeights
 * Calculates equal heights to pairs of subcat listitems.
 * 
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function initF34SitemapSubcatHeights() {
	if (!document.getElement('.f34_sitemap') || !document.getElement('.sub_categories')) return;
	
	var intSitemapSubcatListItemHeightMax = 0;
	
	var arrSitemapSubcatListItems = document.getElement('.f34_sitemap').getElement('.sub_categories').getChildren('li');
	
	arrSitemapSubcatListItems.each(function(elSitemapSubcatListItem, n){
		if (elSitemapSubcatListItem.getHeight() > intSitemapSubcatListItemHeightMax) {
			intSitemapSubcatListItemHeightMax = elSitemapSubcatListItem.getHeight();
		}
		
		if (n % 2) {
			arrSitemapSubcatListItems[n-1].setStyle('height', intSitemapSubcatListItemHeightMax);
			arrSitemapSubcatListItems[n].setStyle('height', intSitemapSubcatListItemHeightMax);
			intSitemapSubcatListItemHeightMax = 0;
		}
	});
}



/**
 * initLightboxCloseButton
 *
 * close shadowbox with textlink
 *
 * @author Phi Son do <phison.do{AT}efocus.nl>
 * @return void
 */

function initLightboxCloseButton() {
	if (!document.getElement('.close_window')) return;
	
	var elLightboxCloseButton = document.getElement('.close_window');	

	elLightboxCloseButton.addEvent('click', function(){
		parent.Shadowbox.close();
	});	
}



/**
 * initFormF23
 *
 * Apply multiple persons
 *
 * @author Phi Son do <phison.do{AT}efocus.nl>
 * @return void
 */

function initFormF23() {
	if (!document.getElement('.f23_aanmeldformulier')) return;

	var elF23 = document.getElement('.f23_aanmeldformulier');
	var elF23Form = elF23.getElement('form');
	var arrFormSubmitButtons = elF23Form.getElements('.send_button');
	
	var elApplyMoreButton = $('apply_more_persons');
	var elInputAddMore = $('add_more_persons');
	var event = $('event');
	
	elApplyMoreButton.addEvent('click', function (){
		event.set('disabled', false);
		elInputAddMore.setProperty('value', 1);
		elF23Form.submit();
	});
	
	// JIRA IIR-182; submit in onclick werd in IE voor elInputAddMore eerder uitgevoerd dan 
	// setProperty van hidden input. Nu submit in aparte onclicks voor buttons
/*	arrFormSubmitButtons.each(function (elFormSubmitButton){
		elFormSubmitButton.addEvent('click', function(){
			elF23Form.submit();
		});	
	});
*/
	var elSubmitButton = $('verzenden');
	elSubmitButton.addEvent('click', function (){
		event.set('disabled', false);
		elF23Form.submit();
	});
}



/**
 * initFormF26
 *
 * Submit search, show/hide search hint, add/remove search hint class
 *
 * @author Gijs Oliemans <gijs.oliemans{AT}efocus.nl>
 * @return void
 */
 
function initFormF26() {
	if (!document.getElement('.f26_search')) return;
	
	var elF26 = document.getElement('.f26_search');
	var elF26Form = elF26.getElement('form');
	var elF26Button = elF26Form.getElement('.button');
	
	var elF26Input = $('searchkeyword');
	var searchHint = $('search_hint').innerHTML;
	
	elF26Button.addEvent('click', function (){
		if(elF26Input.value.trim() != searchHint.trim() && elF26Input.value.trim() != '') {
			elF26Form.submit();
			return false;
		}else{
			//alert('Vul een zoekwoord in!');
			return false;
		}
	});
	
	elF26Input.addEvent('blur', function (){
		if(elF26Input.value.trim() == '') {
			elF26Input.value = searchHint;
			elF26Input.removeClass('focus');
		}
	});

	elF26Input.addEvent('focus', function (){
		if(elF26Input.value.trim() == searchHint.trim()) {
			elF26Input.value = '';
			elF26Input.addClass('focus');
		}
	});
	
	if(elF26Input.value.trim() == ''){
		elF26Input.value = searchHint;
	}else if(elF26Input.value != searchHint){
		elF26Input.addClass('focus');
	}		
}



/**
 * initTopSearch
 *
 * Submit top searchbox
 *
 * @author Gijs Oliemans <gijs.oliemans{AT}efocus.nl>
 * @return void
 */

function initTopSearch(){
	if (!$('top_searchbox')) return;
	
	var elForm = $('top_searchbox');	
	var elFormButton = elForm.getElement('a.search_button');

	elFormButton.addEvent('click', function(){
		elForm.submit();
		return false;
	});
	
}



/**
 * replaceHeads
 *
 * replaces certain heads with sIFR Flash font
 *
 * @author phison do <phison.do{AT}efocus.nl>
 * @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
 * @return void
 */
function replaceHeads() {
	
	var avenir = {
		src: '/fileadmin/templates/flash/avenir.swf'
		,ratios: [6, 1.41, 9, 1.35, 15, 1.29, 21, 1.25, 22, 1.22, 27, 1.24, 29, 1.21, 34, 1.22, 41, 1.21, 45, 1.2, 46, 1.21, 59, 1.2, 68, 1.19, 69, 1.2, 96, 1.19, 97, 1.18, 102, 1.19, 103, 1.18, 107, 1.19, 108, 1.18, 112, 1.19, 114, 1.18, 116, 1.19, 120, 1.18, 121, 1.19, 1.18]
	};

    sIFR.activate(avenir);
	
	sIFR.replace(avenir, {
		selector: '#main_nav li span',
		wmode: 'transparent',
		fitExactly : true,
		useDomLoaded : true,
		css: {
			'.sIFR-root': {
				'background-color': '#292929',
				'color': '#ffffff',
				'font-size': '12px',
				'text-transform' : 'uppercase'
			},
			'a': {
				'color': '#ffffff',
				'text-decoration': 'none'
			},
			'a:hover': {
				'color': '#ffffff',
				'text-decoration': 'none'
			},
			'.active': {
				'color': '#ffffff',
				'text-decoration': 'none'
			}
		}
	});  
	
    sIFR.replace(avenir, {
      selector: 'h1',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { text-align: left; color: #aa1d37; paddingBottom: 0 }'
      ]
    });

    sIFR.replace(avenir, {
      selector: '.f4_pushbox h2',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #ffffff; }'
      ]
    });  
	
    sIFR.replace(avenir, {
      selector: '#footer h2',
	  wmode: 'transparent'
      ,css: {
        '.sIFR-root': { 'color': '#d8d6d5' }
      }
    });  
  
    sIFR.replace(avenir, {
      selector: 'h2',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #aa1d37 }'
        ,'a { text-decoration: none; }'
        ,'a:link { color: #aa1d37; }'
        ,'a:hover { color: #aa1d37; text-decoration: underline; }'
      ]
    });

    sIFR.replace(avenir, {
      selector: 'h3.subtitel',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #262424; text-transform: uppercase; }'
      ]
    });

    sIFR.replace(avenir, {
      selector: 'h3.teasertop',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #ffffff }'
      ]
    });
	
    sIFR.replace(avenir, {
      selector: '.col_right h3',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #000000 }'
      ]
    });	

    sIFR.replace(avenir, {
      selector: '.col_left h3',
	  wmode: 'transparent'
      ,css: [
        '.sIFR-root { color: #ae0014 }'
        ,'a { text-decoration: none; }'
        ,'a:link { color: #ae0014; }'
        ,'a:hover { color: #ae0014; text-decoration: underline; }'
      ]
    });
  
    sIFR.replace(avenir, {selector: 'h2,h3'});
}



/**
 * f04_pushboxSlideShow
 * Animates the header slideshow on the homepage and defines the interaction.
 *
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @editor Phi Son do <phison.do{AT}efocus.nl>
 * @param arrSlides, intStartSlide, blnLoop, intInterval, blnAutoPlay, blnPlaying
 * @param strOutEffectProperty, intOutEffectStartValue, intOutEffectEndValue, intOutEffectDuration
 * @param strInEffectProperty, intInEffectStartValue, intInEffectEndValue, intInEffectDuration
 * @param elNav, strLabelPrev, strLabelNext, strLabelFirst, strLabelLast, strLabelPlay, strLabelPause
 * @return EfxNavSlideShow Class instance
 */
function f04_pushboxSlideShow(){
	arrF04 = $$('.f4_pushbox');
	if (arrF04.length == 0) return;
	
	var elMySs = arrF04[0];
	var arrMySlides = elMySs.getElements('.slide');
	
	var elMyNav = elMySs.getElement('.slideshow_nav');

	var objSlideShow = new EfxNavSlideShow({
		arrSlides: arrMySlides,
		elNav: elMyNav,
		strOutEffectProperty: 'left',
		intOutEffectStartValue: 0,
		intOutEffectEndValue: -696,
		strInEffectProperty: 'left',
		intInEffectStartValue: 696,
		intInEffectEndValue: 0,
		intInterval: 10000
	});
}


/*
 * initGoogleAnalytics
 * Initializes Google Analytics.
 * 
 * @author Ralph Meeuws (ralph.meeuws[AT]efocus.nl)
 * @return void
 */
function initGoogleAnalytics(pagetrackname) {
	if (typeof(pagetrackname) == 'undefined') pagetrackname = '';
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	new Asset.javascript(gaJsHost + "google-analytics.com/ga.js", {
		onload: function() {
			try {
				var pageTracker = _gat._getTracker("UA-3721085-2");
				pageTracker._trackPageview(pagetrackname);
			} catch(err) {}
		}
	});
}


/**
* submits form for redirection to next step
*
* @author Richard van Yperen <richardvy[at]efocus.nl
* @since 1.0, jan 2011
* @param int - id of step
*/

function submitForm() {
	if ($('form_tabs_box')) {
		$('form_tabs_box').getElements('a.submit_form').each(function(el) {
			el.addEvent('click', function() {
				var elId = el.id.replace(/tab/, '');	
				$('nextstep').value = elId;
				$('form_1').submit();
			});
		});
	}
	
	if ($('factuuradres')) {
		$('factuuradres').addEvent('click', function() {
			$('nextstep').value = 2;
			$('form_1').submit();
		});
	}
	
	if ($('totalprice') && $('persons')) {
		
		$('form_1').getElements('div.block-datum').each(function(el) {
			el.getElements('input.radio').each(function(elfield) {
				elfield.addEvent('click', function () {
					var price = Math.round(this.title);
					var persons = Math.round($('persons').value) + 1;
					$('totalprice').set('html', '&euro; '+number_format(price*persons, 0, ',', ''));
					$('totalpriceblock').removeClass('hidden');
				});
			});
		});
	}
	

}

function number_format( number, decimals, dec_point, thousands_sep ) {
	var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
	var d = dec_point == undefined ? "," : dec_point;
	var t = thousands_sep == undefined ? "." : thousands_sep, s = n < 0 ? "-" : "";
	var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}


/*
 * initSubscriptionTooltips
 * Shows tooltips subscription
 * 
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @return void
 */
function initSubscriptionTooltips() {
	var arrLabels = $$('.block-datum label span');
	if (arrLabels.length == 0) return false;
	
	var labelTips = new Tips(arrLabels);
}
