window.addEvents({
    'domready': function() {
        initEventDetail();
        initAgendaFilter();
        initFAQtoggling();
        startPushbox();
        insertGoogleMap();
        insertNSwidget();
        insertWMVplayer();
        startCarrousel();
        initRating();
        initContactTabs();
        initSearchForm();
        fixExternalLinks();
        makePreview();
    },
    'load': function() {
        alignContentOverview();
        initAlignNewsblock();

        makeEqualHeight($$('div.faplist>ul>li'));
        makeEqualHeight($$('div.col2of4 div.container>ul.highlighted_products>li'));

        $$('dl.speclist dt').each(function(item, index) {
            var tempAr = new Array;
            tempAr[0] = $$('dl.speclist dt')[index];
            tempAr[1] = $$('dl.speclist dd')[index];
            makeEqualHeight(tempAr);
        });
    }
});

/**
* initEventDetail
* Changes the parent column so the left innercolumn can break out and will be visible.
* 
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @return void
*/

function initEventDetail() {
	if (!document.getElement('.event_detail')) return;

	var elEventDetail = document.getElement('.event_detail');
	elEventDetail.getParent().setStyle('overflow', 'visible');
	elEventDetail.getElement('div.col1of4').setStyle('top', (elEventDetail.getElement('h1').getHeight() + elEventDetail.getElement('h1').getStyle('margin-bottom').toInt()));
}

/**
* makeEqualHeight
*
* makes multiple different elements all the same height,
* assuming the height of the highest element
*
* @param arElements, Array of DOM elements to compare fix height
*
* @author Klaas Dieleman <klaas{AT}efocus.nl>
*
* @return h, height of highest element in px
*/

function makeEqualHeight(arElements) {
	var h = 0;
	
	for(var i = 0 ; i < arElements.length ; i++) {
		if(arElements[i].getSize().y > h) h = arElements[i].getSize().y;
	}
	
	arElements.each(function(item) {
		var ch = 0;
		var ah = item.getStyle('padding-top').toInt();
		ah += item.getStyle('padding-bottom').toInt();
		ah += item.getStyle('border-top-width').toInt();
		ah += item.getStyle('border-bottom-width').toInt();
		ch = h - ah;
		item.setStyle('height', ch);
	});
	
	return h;
}

/**
 * alignContentOverview
 *
 * align two columns content overviews next to each other
 *
 * @author Klaas Dieleman <klaas{AT}efocus.nl>
 */
 
function alignContentOverview() {
	if($$('div.contentoverview div.twocolumn div').length < 2) return false;
	
	$$('div.contentoverview div.twocolumn div:even').each(function(item, index) {
		if($$('div.contentoverview div.twocolumn div')[index+1]) {
			var twoCols = new Array;
			twoCols[0] = item;
			twoCols[1] = $$('div.contentoverview div.twocolumn div')[index+1];
			makeEqualHeight(twoCols);
		}
	});
}

/**
* initAlignNewsblock
* Equal alignment of the newsblock intro and links list.
* 
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @return void
*/

function initAlignNewsblock() {
	if (!document.getElement('.newsblock')) return;

	var elNewsBlock = document.getElement('.newsblock');
	var arrNewsblockHighlights = elNewsBlock.getElements('.news_highlight');
	var arrNewsblockRelatedLists = elNewsBlock.getElements('.related_list_container ul');
	
	makeEqualHeight(arrNewsblockHighlights);
	makeEqualHeight(arrNewsblockRelatedLists);
}

/**
 * initAgendaFilter
 * Adds calendar tooltips to the date fields, and refreshes the page with passed down date variables.
 * 
 * @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
 * @since 1.1, 26 aug, 2009
 * @return void
 */

function initAgendaFilter() {
	if (!document.getElement('.filter') || (document.getElement('.filter').getElements('.date_field').length == 0)) return;

	// Calendar script from: http://www.monkeyphysics.com/mootools/script/2/datepicker
	var objAgendaFilterDate = new DatePicker('.date_field', {
		pickerClass: 'datepicker_vista',
		allowEmpty: true,
		inputOutputFormat: 'd-m-Y',
		//minDate: { date: '12-08-2009', format: 'd-m-Y' },
		//maxDate: { date: '27-08-2009', format: 'd-m-Y' },
		toggleElements: '.calendar_button',
		onSelect: function() {
			reloadPageWithFilter();
		}
	});
	
	document.getElement('.filter').getElements('.date_field').each(function(elDateField) {
		elDateField.addEvent('keydown', function(event) {
			if (event.key == 'enter') {
				reloadPageWithFilter();
			}
		});
	});

	var arrDateFields = $$('input.date_field');
	elDateFieldFrom = arrDateFields[1];
	elDateFieldTill = arrDateFields[3];
	
	if (Cookie.read('filterDateFrom')) elDateFieldFrom.setProperty('value', Cookie.read('filterDateFrom'));
	if (Cookie.read('filterDateTill')) elDateFieldTill.setProperty('value', Cookie.read('filterDateTill'));

	if (!Cookie.read('filterWindowURI')) {
		var filterWindowURICookie = new Cookie.write('filterWindowURI', window.location.href);
	}

	reloadPageWithFilter = function() {
		var filterDateFromCookie = new Cookie.write('filterDateFrom', elDateFieldFrom.getProperty('value'));
		var filterDateTillCookie = new Cookie.write('filterDateTill', elDateFieldTill.getProperty('value'));
		
		if ((elDateFieldFrom.getProperty('value') == '') && (elDateFieldTill.getProperty('value') == '')) {
			strDateRange = '';
		} else if (elDateFieldFrom.getProperty('value') == '') {
			strDateRange = '?tot=' + elDateFieldTill.getProperty('value');
		} else if (elDateFieldTill.getProperty('value') == '') {
			strDateRange = '?van=' + elDateFieldFrom.getProperty('value');
		} else {
			strDateRange = '?van=' + elDateFieldFrom.getProperty('value') + '&tot=' + elDateFieldTill.getProperty('value');
		}

		window.location.href = Cookie.read('filterWindowURI') + strDateRange;
	}

	document.getElement('.reset').addEvent('click', function() {
		elDateFieldFrom.setProperty('value', '');
		elDateFieldTill.setProperty('value', '');
		Cookie.dispose('filterDateFrom');
		Cookie.dispose('filterDateTill');
	});
}

/**
* GetEnter
* Gets the key "enter" on the input
*
* @author Jeroen Datema <jeroen.datema[at]efocus.nl>
* @return void
*/

function GetEnter(url, e, queryString) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        var connector = url.toString().indexOf("?") >= 0 ? "&" : "?";
        var newLocation = url + connector + "q=" + encodeURIComponentNew(queryString);
        window.location = newLocation;
        return false;
    }
    else
        return true;
}

function GetEnterWithQS(url, e, zoekstring, queryString) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        var newLocation = url + "?q=" + encodeURIComponentNew(zoekstring);
        if (queryString != '' && queryString != undefined && queryString.toString().indexOf('?') < 0) {
            newLocation = queryString + "?q=" + encodeURIComponentNew(zoekstring);
        }
        window.location = newLocation;
        return false;
    }
    else
        return true;
}

/**
* RedirectZoek
*
* @author Jeroen Datema <jeroen.datema[at]efocus.nl>
* @return void
*/

function RedirectSearch(url, zoekstring) {
    window.location = url + "?q=" + encodeURIComponentNew(zoekstring);
    return false;
}

function RedirectSearch(url, zoekstring, categorie) {
    window.location = url + "?q=" + encodeURIComponentNew(zoekstring) + "&categorieen=" + categorie;
    return false;
}

function RedirectSearchWithQS(url, zoekstring, queryString) {
    var newLocation = url + "?q=" + encodeURIComponentNew(zoekstring);
    if (queryString != '' && queryString != undefined) {
        newLocation = queryString + "?q=" + encodeURIComponentNew(zoekstring);
    }
    window.location = newLocation;
    return false;
}

/** 
* functie encodeURIComponentNew() doet escape() maar dan netjes unicode 
*
* @author Barend <barend[at]efocus.nl>
*/

var hexchars = "0123456789ABCDEF";
var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
function encodeURIComponentNew(s) {
    var s = utf8(s);
    var c;
    var enc = "";
    for (var i = 0; i < s.length; i++) {
        if (okURIchars.indexOf(s.charAt(i)) == -1)
            enc += "%" + toHex(s.charCodeAt(i));
        else
            enc += s.charAt(i);
    }
    return enc;
}

function toHex(n) {
    return hexchars.charAt(n >> 4) + hexchars.charAt(n & 0xF);
}

function utf8(wide) {
    var c, s;
    var enc = "";
    var i = 0;
    while (i < wide.length) {
        c = wide.charCodeAt(i++);
        // handle UTF-16 surrogates
        if (c >= 0xDC00 && c < 0xE000) continue;
        if (c >= 0xD800 && c < 0xDC00) {
            if (i >= wide.length) continue;
            s = wide.charCodeAt(i++);
            if (s < 0xDC00 || c >= 0xDE00) continue;
            c = ((c - 0xD800) << 10) + (s - 0xDC00) + 0x10000;
        }
        // output value
        if (c < 0x80) enc += String.fromCharCode(c);
        else if (c < 0x800) enc += String.fromCharCode(0xC0 + (c >> 6), 0x80 + (c & 0x3F));
        else if (c < 0x10000) enc += String.fromCharCode(0xE0 + (c >> 12), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
        else enc += String.fromCharCode(0xF0 + (c >> 18), 0x80 + (c >> 12 & 0x3F), 0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
    }
    return enc;
}

/**
 * starts pushbox
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @since 1.0, 14 aug, 2009
 * @return void
 */

function startPushbox() {
	if (!$('pushbox')) return;
	var pbox = new Pushbox({
		'viewport': $('pushbox').getElement('div.viewport'),
		'slides': $('pushbox').getElement('ul.slides').getElements('li'),
		'navigation': $('pushbox').getElement('ul.pushbox_nav').getElements('li'),
		'transition': 'fade',
		'delay': 5
	});
}

/**
* starts carrousel
*
* @author Rocco Janse <rocco@efocus.nl>
* @since 1.1, 27 aug, 2009
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @return void
*/

function startCarrousel() {
	if (!$('projectscarrousel')) return;
	
	makeEqualHeight($('projectscarrousel').getElement('ul.slides').getChildren('li'));
	$('projectscarrousel').getElement('div.viewport').setStyle('height', makeEqualHeight($('projectscarrousel').getElement('ul.slides').getChildren('li')));

	var csel = new Carrousel({
		'viewport': $('projectscarrousel').getElement('div.viewport'),
		'slidesContainer': $('projectscarrousel').getElement('ul.slides'),
		'linkNext': $('projectscarrousel').getElement('div.nav').getElement('a.next'),
		'linkPrevious': $('projectscarrousel').getElement('div.nav').getElement('a.prev'),
		'slidesToShift': 1,
		'slidesToShow': 3
	});
}

/**
* initRating
* Makes sure the rating can be set.
* 
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @author Rocco Janse <rocco@efocus.nl>
* @return void
*/
function initRating() {
	if (!document.getElement('.appreciation')) return;

	$$('ul.appreciation').each(function(elAppreciation) {
		arrAppreciationLinks = elAppreciation.getElements('a');
		arrAppreciationLinks.each(function(elAppreciationLink, n) {
			elAppreciationLink.addEvents({
				'mouseenter': function() {
					intAppreciationNumber = n * 5;
					if (intAppreciationNumber == 0 || intAppreciationNumber == 5) intAppreciationNumber = '0' + intAppreciationNumber;
					elAppreciation.className = 'appreciation appreciation' + intAppreciationNumber;
					elAppreciation.getParent().getElement('.appreciation_value').setProperty('value', intAppreciationNumber);
				},
				'click': function(e) {
					e.stop();
					elAppreciationLink.blur();
				}
			});
		});
	});
}

/**
* initContactTabs
* Adds tabbed navigation to the contactpage.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @since 1.1, 26 aug, 2009
* @return void
*/
function initContactTabs() {
	if (!document.getElement('.contact')) return;
	
	var contactTabs = new Tabs({
		tabs: document.getElement('.tabnav').getElements('a'),
		panels: document.getElement('.tabcontent').getElements('li')
	});
}

/**
* Tabs Class
* Creates a tabbed navigation from a list and links it to the appropriate content.
*
* @author Ralph Meeuws <ralph.meeuws{AT}efocus.nl>
* @since 1.0, 17 aug, 2009
*
* @params tabs: Array of anchors elements
* @params panel: Array of list items acting as content holders
* @return void
*/
var Tabs = new Class({
	Implements: [Options, Events],
	options: {
		tabs: document.getElements('.tab_nav a'),
		panels: $$('.tab_panel')
	},
	initialize: function(options) {
		this.setOptions(options);
		this.createTabEvents();
		this.detectDirectURI();
	},
	createTabEvents: function() {
		this.options.tabs.each(function(elTab, n) {
			elTab.addEvent('click', function(event) {
				event.stop();
				elTab.blur();
				this.setActiveStates(n);
			} .bindWithEvent(this));
		} .bind(this));
	},
	detectDirectURI: function() {
		if (location.href.contains('#')) {
			var arrURIParts = location.href.split('#');
			var strInternalLink = arrURIParts[arrURIParts.length - 1];

			$$('a').each(function(elLink) {
				if (elLink.getProperty('name') == strInternalLink) {
					this.detectActiveItems(elLink);
				}
			} .bind(this));
		}
	},
	detectActiveItems: function(elInternalLink) {
		this.options.panels.each(function(elPanel, n) {
			if (elPanel == elInternalLink.getParent()) {
				this.setActiveStates(n);
			}
		} .bind(this));
	},
	setActiveStates: function(intActiveItem) {
		this.options.panels.each(function(elPanel, n) {
			if (n == intActiveItem) {
				elPanel.addClass('active');
			} else {
				elPanel.removeClass('active');
			}
		});

		this.options.tabs.each(function(elTab, n) {
			if (n == intActiveItem) {
				elTab.getParent().addClass('active');
			} else {
				elTab.getParent().removeClass('active');
			}
		});
	}
});

/**
* inserts Google map and Google directions on contact page
*
* @author Ralph Meeuws <ralph.meeuws[AT]efocus.nl>
* @author Klaas Dieleman <klaas[AT]efocus.nl>
* @return void
*/

function insertGoogleMap() {
	if(!$('googlemap') || !$('googledirections')) return false
	
	var elRouteMap = $('googlemap');
	var elRouteZip = document.getElement('fieldset.planroute input.text');
	var elRouteBtn = document.getElement('fieldset.planroute input.button');
	var elRouteDir = $('googledirections');	
	
	var strBalloonContent = document.getElement('div.contact div.usercontent p.intro').clone();	
	var strBalloonContentImg = strBalloonContent.getElement('img.visual').dispose(); 
		
	if (GBrowserIsCompatible()) {
		var map = new GMap2(elRouteMap);
		var geocoder = new GClientGeocoder();
		var gdir = new GDirections(map, elRouteDir);
		
		function showAddress(address) {
			geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
						alert(address + " not found");
					} else {
						map.setCenter(point, 15);
						var marker = new GMarker(point);
						
						map.addOverlay(marker);
						map.addControl(new GLargeMapControl());
						map.addControl(new GMapTypeControl());						
						marker.openInfoWindowHtml(strBalloonContent);
						
						GEvent.addListener(marker, 'click', function() {
//							marker.openInfoWindowHtml(document.getElement('div.contact div.usercontent p.intro').clone());
							marker.openInfoWindowHtml(strBalloonContent);
						});
					}
				}
			);
		}	
		showAddress(gmapAddress);

	}
	
	elRouteBtn.addEvent('click', function(){
	  	strRouteZip = elRouteZip.value;
		gdir.load('from: ' + strRouteZip + ' to: ' + gmapAddress, { 'locale': 'nl_NL' });
	});
	
	elRouteZip.addEvent('keypress', function(event){
		if (event.key == 'enter') {
	  		strRouteZip = elRouteZip.value;
			gdir.load('from: ' + strRouteZip + ' to: ' + gmapAddress, { 'locale': 'nl_NL' });
		}
	});
}

/**
 * inserts NS widget on contact page
 *
 * @author Klaas Dieleman <klaas[AT]efocus.nl>
 * @return void
 */

function insertNSwidget() {
	if(!$('nswidget')) return false
	
	var widgetFrame = "<iframe frameborder=0 src='http://www.ns.nl/webwidgets/widget.jsp?width=470&amp;height=320&amp;data=eNpjaE3Os1VLTkpPtjU0Mzc3NzI0VStH4WWg8JKLElNsDdSSym0N1ZKA4sYmRoZAGbW0ZFtjY1NT%0AExNjtbRiW0OgQGaFrbtaSpltcIh/mFpKIoROKyu2TUvMKU5VSykGWltsGxSgauQc4AQAxGkl7g%3D%3D%0A&amp;ref="+escape(location.href)+"' width='470' height='320'></iframe>";
	$('nswidget').set('html', widgetFrame);
}

/**
 * inserts JW wmv videoplayer on contentpages where a video is added
 * client requires Silverlight plugin
 *
 * @author Klaas Dieleman <klaas[AT]efocus.nl>
 * @return void
 */

function insertWMVplayer() {
	if(!$('introvideo')) return false
	
	var cnt = $('introvideo');
	var src = '/js/wmvplayer/wmvplayer.xaml';
	
	var ply = new jeroenwijering.Player(cnt,src,cfg);
	
}

/**
 * initializes search form; handles enter keyup event and click events
 *
 * @author Rocco Janse <rocco@efocus.nl>
 * @since 1.0, 10 sept, 2009
 * @return void(0)
 */
function initSearchForm() {
	var forms = $$('fieldset.findproject').combine($$('fieldset.search')).combine($$('fieldset.search_form')).combine($$('div.header_webshop'));
	if (forms.length == 0) return;

	var buildUrl = function(form) {
		var input = form.getElement('input.text');
		
		var url = form.getElement('input.searchUrl').get('value');
		url += encodeURIComponent(input.get('value'));
		if(document.getElement('select.searchdomain')) {
			url += '&domein=' + encodeURIComponent(document.getElement('select.searchdomain').getSelected().get('value'));
		}
		return(url);
	};
	
	forms.each(function(form) {
	
		var input = form.getElement('input.text');
		var button = form.getElement('.button');

		input.addEvents({
			'keyup': function(e) {
				if (e.key == 'enter' && input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}
			}
		});
		button.addEvents({
			'click': function(e) {
				if (input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}			
			},
			'keyup': function(e) {
				if (e.key == 'enter' && input.get('value') != '') {
					e.stop();
					window.location = buildUrl(form);
				}			
			}
		});
	});
}

/**
 * puts FAQ categories in an accordion and enables toggling of answers
 *
 * @author Klaas Dieleman <klaas[AT]efocus.nl>
 * @return void
 */

function initFAQtoggling() {

	var list = $(document.body).getElement('ul.faq');
	if (!list) return;

	var items = list.getChildren('li');
	
	if (items.length > 0) {

		var handles = [];
		var questions = [];

		items.each(function(item) {
			if (item.getElement('div.questions')) {
				handles.include(item.getElement('h3'));
				questions.include(item.getElement('div.questions'));
			}
		});

		var faqAccordion = new Fx.Accordion(handles, questions, {
			'onActive': function(toggler){
				toggler.getParent().addClass('open');
			},
			'onBackground': function(toggler){
				toggler.getParent().removeClass('open');
			},
			'alwaysHide': true,
			'show': 0
		});
		$$('div.questions')[0].setStyle('height', $$('div.questions')[0].getSize().y);
	}

	if ($$('ul.faq dd').length > 0) {
		if ($$('ul.faq dt').length == $$('ul.faq dd').length) {
			$$('ul.faq dt').each(function(item, index) {
				item.addEvent('click', function() {
					var oldHeight = item.getParent().getSize().y;

					$$('ul.faq dt').removeClass('open');
					$$('ul.faq dd').removeClass('open');

					$$('ul.faq dt')[index].addClass('open');
					$$('ul.faq dd')[index].addClass('open');

					var newHeight = item.getParent().getSize().y;

					item.getParent('div.questions').setStyle('height', (item.getParent('div.questions').getSize().y + (newHeight - oldHeight)));
				});
			});
		}
	}
}


function addListToBasket() {
	var products = $$('ul.products_list>li div.product_order').filter(function(el){
		if(el.getElement('input.text')) return el;
	});
	
	if(products.length < 1) return false
	
	products.each(function(item) {
		var productcode = item.getElement('a.addToBasketLink').getProperty('productcode');
		var amount = item.getElement('input.text').get('value');
		
		AddToBasket(productcode, amount, "1");
	});
}


/**
* function makePreview
* makes preview of current form / email
*
* @author Mirjam <mirjam[AT]efocus.nl>
* @return void
*/

function makePreview() {

    ///&subject=Test%20onderwerp&message=Test%20bericht
    //shadowbox;height=500;width=500
     
    var previewLink = $$('a.open_lightbox');
    if (previewLink.length == 0) return false;

    previewLink.each(function(item) {
        item.addEvent('click', function(event) {

            event.stop();

            var thisForm = previewLink.getParent('div.form');

            var lightboxUrl = "tell-a-friend/email-voorbeeld.aspx?";
            lightboxUrl += "fromname=" + thisForm.getElement('input.name_from').get('value');
            lightboxUrl += "&fromemail=" + thisForm.getElement('input.email_from').get('value');
            lightboxUrl += "&toname=" + thisForm.getElement('input.name_to').get('value');
            lightboxUrl += "&toemail=" + thisForm.getElement('input.email_to').get('value');
            lightboxUrl += "&subject=" + thisForm.getElement('input.subject').get('value');
            lightboxUrl += "&message=" + thisForm.getElement('textarea.message').get('value');
            lightboxUrl += "&item=" + getQueryVariable('item');
            
            Shadowbox.open({
                content: lightboxUrl,
                player: "iframe",
                height: 500,
                width: 500
            });

        });
    });
    
}

function F67postcodecheck(prefix) {
    var postcodeveld = $(eval(prefix + 'postcodeveld'));
    var huisnummerveld = $(eval(prefix + 'huisnummerveld'));
    var updatepanel = $(eval(prefix + 'updatepanel'));
    var checkenabled = $(eval(prefix + 'postcodecheckenabled'));

    // checkenabled.checked is false als 'handmatig' of 'buitenland' is gekozen
    if (checkenabled.checked) {
        if (postcodeveld.value != '' && huisnummerveld.value != '') {
            __doPostBack(eval(prefix + 'postcodeveld'), '');
        }
    }
}

function F67checkVolledigeAanmelding(validator) {
    // validatie gebeurt alleen op server; deze clientfunctie dient alleen om de meldingen na wijzigen te verbergen
    validator.valid = true;
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	} 
}
