function popUp(URL)
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=630,height=310,left = 322.5,top = 387');");
} 

	
// vs new loops trough elements and if a tag is found will open the a tag
function loadHrefOfAtag(allContainedElements){
	for (var i = 0; i < allContainedElements.length; i++) {
		var elem = allContainedElements[i];
		if(elem.target == "_blank") {
			day = new Date();
			id = day.getTime();
			//alert(id);
			window.open(elem.href, id);
		}
		else {
			document.location = elem.href;
		}
		return true;
	}
	return false;
}
	
	
// vs new loads the href of the first a tag in a teaser div or table
function clickTeaser(teaser, e){

	var elem, allContainedElements;
	var contentDiv = document.getElementById(teaser.id);
	var siteEditActive = false;
	if(undefined===window._SE_BoolPaneShown){
		siteEditActive = false;
	}
	else {
		siteEditActive = window._SE_BoolPaneShown;
	}
		
	if (!siteEditActive){ //if siteedit button is not active
		//special case for tables
		if (teaser.nodeName == 'TABLE'){
			var trElements = contentDiv.getElementsByTagName("TR");
			for (var i = 0; i < trElements.length; i++) {
				elem = trElements[i];
				tdElements = elem.getElementsByTagName("TD");
				for (var j = 0; j < tdElements.length; j++) {
					elem = tdElements[i];
					allContainedElements = contentDiv.getElementsByTagName("A");
					if (loadHrefOfAtag(allContainedElements)) break;
				}
			}	
		}
		else {
			allContainedElements = contentDiv.getElementsByTagName("A");
			loadHrefOfAtag(allContainedElements);
		}
	}

	//stop default click event on a tag
	if (arguments.length == 2){
		var evt = e || window.event;
		if (evt.preventDefault) {
			evt.preventDefault( );
		} else{
			evt.returnValue = false;
		}
	}
}	
	
/* vs new function to change location according to dropdown */
function dropdownChange(strLocation){
	if (strLocation != "") window.location = strLocation;
}

/* vs used to be inline javascript function */
function SiteSelectBox(SelectedElement)
{
	if(SelectedElement.value != "") {
		if (SelectedElement.className == 'pop')
		{
			window.open(SelectedElement.value);
		}
		else
		{
			document.location = SelectedElement.value;
	
		}
	}
}


function sendAFried(frm){
	$("#safContainer").load(frm.attr("action"), {
		u: $("#saf_u").val(),						
		saf_to_email: $("#saf_to_email").val(),
		saf_from_email: $("#saf_from_email").val(),
		formSubmitted: 1
		},
		function(){
			$("#safForm").submit(function() {
				return sendAFried($(this));
			});
			bindShowEmailExample();
	});
	sendTrackPageview ("sendafriend/" + relPageLocation() + "/submit");
	return(false);	
}

function bindShowEmailExample(){
	$("#showEmailExample").click(function () { 
		$("#exampleMail").slideToggle("slow");
		return false;
	});
}

function printPage(){
	sendTrackPageview ("print/" + relPageLocation());
	window.print();	
}



/* calendar http://marcgrabanski.com/code/ui-datepicker/ */
var eventDateFormat = 'dd-mm-yy';


$(document).ready(function() {

	
	/* temp function, can be deleted when template change has been published */
	$("body.detail li.print a").bind("click", function(e){
		sendTrackPageview ("print/" + relPageLocation());
	});
	
	/* vs new tooltip function
	http://jquery.com/plugins/project/cluetip
	titleAttribute is set on donotuse so no header will show up if title attribute is filled in
	ajaxsettings type=tooltip is added after the url that is used for ajax call	
	*/
	$('a.tooltip').cluetip({
		dropShadowSteps: 2, showTitle: false, titleAttribute:'donotuse',
		onShow: function(c,ct) {
			sendTrackPageview ("help/" + ct.children("div").attr("class"));
		},
		ajaxSettings: {
			data: "type=tooltip"
		}
	});

	/* sticky tooltip, will close with close button or on mouse-out */
	$('a.tooltipsticky').cluetip({
		dropShadowSteps: 2, showTitle: false, titleAttribute:'donotuse',
		onShow: function(c,ct) {
			sendTrackPageview ("help/" + ct.children("div").attr("class"));
		},		
		ajaxSettings: {
			data: 'type=tooltip'
		},
		cluetipClass: 'default cluetip-sticky',
		width:450,
		height:350,
		sticky: true,
		mouseOutClose: true,
		closePosition: 'top',
		closeText: '<img src="' + binaryUrl + 'maplarge_close.gif" alt="" />'
	});
	

	/* send a friend popup. will only close on close button */
	$('li.sendafriend a').cluetip({
		dropShadowSteps: 4, showTitle: true, titleAttribute:'title',
		height: 200,
		width: 350,
		positionBy: 'mouse',
		sticky: true,
		closePosition: 'title',
		cursor: 'pointer',
		cluetipClass: 'default cluetip-sendafriend',
		closeText: '<img src="' + binaryUrl + 'maplarge_close.gif" alt="" />',
		onShow: function(ct, c){
			$("#showEmailExample").show();
			$("#exampleMail").hide();			
			c.find("form").submit(function() {
				return sendAFried($(this));
			});
			bindShowEmailExample();
			sendTrackPageview ("sendafriend/" + relPageLocation() + "/show");
		},
		ajaxSettings: {
			data: 'type=tooltip'
		}
	});

	$("a.openButton").bind("click", function(e){
		//next() = searchFormWrapperClosed or searchFormWrapper
		$(this).next().slideToggle("fast", function(){
			$(this).contents(".closeButton").fadeIn();
		});
		sendTrackPageview ("box/open");
		$(this).hide();
		return false;
	});

	$("a.closeButton").bind("click", function(e){	
		$(this).parent().slideToggle("fast", function(){
			//searchFormWrapperClosed or searchFormWrapper										
			$(this).prev(".openButton").fadeIn();
		});
		sendTrackPageview ("box/close");
		$(this).hide();
		return false;
	});
	
	
	$("a.openFilter").bind("click", function(e){	
		$(this).siblings().slideToggle("fast", function(){									
			//possibility to set logic after opening
		});
		if ($("body.poi_result").length){
			category = $(".ctselect").val();	
		} else {
			category = "catselect";
		}
		
		trackLink = "box/verfijning/" + category + "/" + analyticsSafe($(this).text());
		if ($(this).attr("class").indexOf("openFilterDyn") > 0) {
			trackLink += "/open";
			checkFilterInputs($(this), "open");
		} else {
			trackLink += "/close";
			checkFilterInputs($(this), "close");
		}
		sendTrackPageview (trackLink);
		$(this).toggleClass("openFilterDyn");
		$(this).blur();
		return false;
	});

	$("a.closeFilter").bind("click", function(e){	
		$(this).siblings().slideToggle("fast", function(){									
			//possibility to set logic after closing
		});
		if ($("body.poi_result").length){
			category = $(".ctselect").val();	
		} else {
			category = "catselect";
		}
		trackLink = "box/verfijning/" + category + "/" + analyticsSafe($(this).text());
		if ($(this).attr("class").indexOf("openFilterDyn") > 0) {
			trackLink += "/open";
			checkFilterInputs($(this), "open");
		} else {
			trackLink += "/close";
			checkFilterInputs($(this), "close");
		}
		sendTrackPageview (trackLink);
		$(this).toggleClass("openFilterDyn");
		$(this).blur();
		return false;
	});
	
	$("a.openAll").bind("click", function(e){							  
		$(this).parent().siblings(".filtercontainer").children(".openFilterDyn").trigger("click"); 
		$(this).parent().toggleClass("closeAll");
		sendTrackPageview("box/verfijning/open_all");
		return false;
	});
		
	$("a.closeAll").bind("click", function(e){							  
		$(this).parent().siblings(".filtercontainer").children(".closeFilter").trigger("click"); 
		$(this).parent().toggleClass("closeAll");
		sendTrackPageview("box/verfijning/close_all");
		return false;
	});
	
	
	$("a.openFilter").addClass("closeFilter openFilterDyn");
	$("a.openFilter").removeClass("openFilter");
	

	$(".poisearch .submitinput").bind("click", function(e){
		$(this).parents("form").find(".error").remove();														
		//object type could be selectlist selector														
		var objectType = $(this).parents("form").find("select[name=ct]").val();
		//if undefined, but radio buttons exists
		if (objectType == undefined && $(this).parents("form").find(":radio[name=ct]").length > 0 ) {
			objectType = $(this).parents("form").find(":radio[name=ct]:checked").val();
			//if objecttype is undefined, nothing is checked, set objecttype to ""
			if (objectType == undefined) objectType = "";
		}
		if ( objectType == ""){
			var ajaxUrl = rootUrl + "system/search/tooltip.jsp";
			var submitButton = $(this);
			$.get(ajaxUrl, { label: "error.geenctgeselecteerd", type: "tooltip" },
			  function(data){
				data = '<div class="error">'+ data + "</div>";
				submitButton.parents("form").prepend(data);
				submitButton.before(data);
			});
			return false;
		} else {
			
			$(this).parents("form").attr("action", $(this).parents("form").attr("action").replace("/lister.jsp", "/" + objectType + ".jsp")); //set action to ct value
			trackBoxSearch(objectType, $(this));
		}
	});
	

	/* search input box on global navigation */
 	if($("#q_globalSearch").val() == "") 
		$("#q_globalSearch").val($("#q_globalSearch").attr("title"));
	
	$("#q_globalSearch").focus(function() {
		if($(this).val() == $("#q_globalSearch").attr("title")) $(this).val("");
	});
	$("#q_globalSearch").blur(function() {
		if($(this).val() == "") $(this).val($(this).attr("title"));
	});
	$("#globalSearch").submit(function() {
		var qValue = $("#q_globalSearch").val();							   
		if(qValue == $("#q_globalSearch").attr("title")|| qValue == "") return(false);
	});
	
	// autocomplete for city's remote cities.jsp?q=inputfieldvalue&limit=10
	$("form.poisearch input.city").autocomplete( geoUrl, {
		matchSubset: false,
		minChars: 1,	
		highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "i"), "<strong>$1</strong>");
		}
	});
	$("form.poisearch input.city").result(function(event, data, formatted) {
		if (data){
			$(this).next("input").val(data[0]); /* set hidden input to value selected */
			if ($("body.poi_result").length) { //on poi result pages, track input 
				inputTrackUrl($(this));
				clearTimeout(cityTimer); //by default input is tracked onchange after few millisecond, cancel this
			}
		}
	});
						
	/*convert input to chain selector */
	$("form.poisearch input.ti_pr_chain").each(function(){
        $(this).replaceWith('<select name="pr_chain" disabled="disabled" class="chain_select" id="' + $(this).attr("id") + '"><option>' + SEARCH_BOX_CHAIN_SELECT + '</option></select>');
    });
	
	/* bind to click of ct, populate chains to chainselector */
	$("form.poisearch input.radioinput[name='ct']").bind("click", function(e){
		populateChains($(this));																		   
	});
	
	/* bind to change of ct, populate chains to chainselector */
	$("form.poisearch select.ctselect").change(function () {
		populateChains($(this));																		   
	});
	

	/* category selection, populates ctselect with values */
	$("form.poisearch select.category").change(function () {													 
		var ctId = "#" + $(this).attr("id").replace("category","ct");
		var oldValue = 	$(ctId).val();
		var opts = $(this).val().split("~");
		var options = '';
		if(opts.length > 1){
			for (var i = 0; i < opts.length; i = i + 2) {
				options += '<option value="' + opts[i] + '">' + opts[i+1] + '</option>';
			 }
			options += '<option selected="selected" value=""></option>';
			$(ctId).html(options);
			// try to select old value
			$(ctId).selectOptions(oldValue);
		}
	});

	/* region selector, clear cache from autocompete city and delete city input */
	$("form.poisearch select.region").change(function () {
	    var elem = $(this).parent().next().children("input");
   		elem.val(""); // clear input
		elem.flushCache();
		elem.setOptions({
			extraParams: {
				region: $(this).val()
			}
		 })
     });

	/* date selectors */
	var maxEventDate = new Date();
	var minEventDate = new Date();
	maxEventDate.setDate(maxEventDate.getDate() + 2 * 356); // two years ahead
	minEventDate.setDate(minEventDate.getDate()); // today
	$(".dateinput").datepicker({beforeShow: setEndRange, onSelect: selectStartDate, showOn: 'both', buttonText: '&nbsp;', buttonImage: '', buttonImageOnly: false, dateFormat: eventDateFormat, closeAtTop: false, minDate: minEventDate, maxDate: maxEventDate, hideIfNoPrevNext: true, speed: '' }); 
	
	
});
	


function selectStartDate(strDate, inst){
	var input = inst; //inst._input[0];
	if (strDate != "") {
		if(input.id.substring(0,5) == "start"){
			var startDate = $.datepicker.parseDate(eventDateFormat, strDate);
			var otherInput = $("#"+input.id.replace("start","end"));
			var endDate = $.datepicker.parseDate(eventDateFormat, $("#"+input.id.replace("start","end")).val());
			//change enddate if enddate is before startdate
			if (endDate < startDate) $("#"+input.id.replace("start","end")).val(strDate);
		}
		else { // if enddate is before startdate, set startdate = enddate
			var endDate = $.datepicker.parseDate(eventDateFormat, strDate);
			var otherInput = $("#"+input.id.replace("end","start"));
			var startDate = $.datepicker.parseDate(eventDateFormat, $("#"+input.id.replace("end","start")).val());
			if (endDate < startDate) $("#"+input.id.replace("end","start")).val(strDate);
		}
	}
	$("#" + input.id).trigger('change');
	otherInput.trigger('change');
}
 
function setEndRange(input) {
	//posible to set a range to the end in combination with the start
	//don't use this function at this moment
	//if(input.id.substring(0,3) == "end"){
	//	var endDate = $.datepicker.parseDate(eventDateFormat, $("#"+input.id.replace("end","start")).val());
	//	endDate.setDate(endDate.getDate() + 31);
	//	return {maxDate: (endDate)}; 
	//}
} 


function populateChains(control){
	control.parents("form").find(".error").remove();//remove error divs
	var strAction = control.parents("form").attr("action");
	strAction = strAction.substring(0,strAction.lastIndexOf("/")+1) + control.val() + ".jsp";
	//set action of form to ct page
	control.parents("form").attr("action", strAction);
	var chainSelect = control.parents(".poisearch").find(".chain_select");	
	var ajaxUrl = rootUrl + "system/search/AjaxGetChainsByType.jsp"
	if(document.location.protocol == "file:") ajaxUrl = "system/search/AjaxGetChainsByType.js";
	if (chainSelect.length){
		var oldValue = chainSelect.val();
		$.getJSON(ajaxUrl, {ct: control.val(), ajax: 'true'}, function(j){
			var options = '';
			if (j.length == 0) {
				options = '<option value="">' + SEARCH_BOX_CHAIN_NOTAVAILABLE + '</option>';
				chainSelect.attr("disabled","disabled");
			}
			else {
				chainSelect.removeAttr("disabled");
				for (var i = 0; i < j.length; i++) {
					options += '<option value="' + j[i] + '">' + j[i] + '</option>';
				}
				options += '<option selected="selected" value=""></option>';
			}
			chainSelect.html(options);
			// try to select old value
			chainSelect.selectOptions(oldValue);
			
		})
	}
}
	


function toggleSection(strMenu) {
	menuDiv = document.getElementById('menu');
	headings = menuDiv.getElementsByTagName('h2');
	for(var i =0 ; i< headings.length; i++) {
		sectionId = 'm_' + (i + 1) + '_s';
		sectionPart = document.getElementById(sectionId);
		bodyId = 'm_' + (i + 1) + '_b';
		bodyPart = document.getElementById(bodyId);
		if (strMenu == headings[i].id) {
			$("#"+sectionId).fadeIn("slow");
			sectionPart.className = "sectionClosed sectionOpen";			
			$("#"+bodyId).fadeIn("slow");
			bodyPart.className = "sectionBody sectionBodyOpen";
		}
		else {
			sectionPart.className = "sectionClosed";
			if (bodyPart.className == "sectionBody sectionBodyOpen") {
				$("#"+bodyId).hide();
			}
			bodyPart.className = "sectionBody";
		}
	}
}


jQuery.fn.selectOptions = function(value) {
	this.each(
		function()	{
			if(this.nodeName.toLowerCase() != "select") return;
			
			// get number of options
			var optionsLength = this.options.length;
			
			
			for(var i = 0; i<optionsLength; i++) {
				if (this.options[i].value == value) {
					this.options[i].selected = true;
				};
			}
		}
	)
	return this;
}


function trackBoxSearch(objectType, input){
			//only log entries on boxes that are not on poi result pages
			if ($("body.poi_result").length == 0){
				//loop trough all input elements 
				input.parent("form").find(":input").each(function(){
					if($(this).val() != "" && $(this).attr("name") != "category"  && $(this).attr("name") != "ct" && $(this).attr("type") != "hidden" && $(this).attr("type") != "submit"){
						label = "label[for='" + $(this).attr("id") + "']";
						strUrl = "box/search/" + objectType + "/" + analyticsSafe($(label).text().replace(":","")) + "/" + analyticsSafe($(this).val());
						sendTrackPageview(strUrl);
					}
				});
			}

			strUrl = "&" + input.parent("form").serialize();
			strUrl = strUrl.replace(/\&ct=/,"&cat="); //replace &ct= with &cat= (full text site search uses ct)
			strUrl =  "box/searchquery/" + relPageLocation() + "?" + strUrl.substr(1); // strip first ampersand from query string
			sendTrackPageview(strUrl);	
}


var showConsoleLog = false;
function consoleLog(message){
	//only show console errors on .nbtc domains and with firebug installed
	if (showConsoleLog || ((location.hostname.indexOf(".nbtc") > 0 || location.hostname.indexOf("stagingprod.") >= 0) && window.console && window.console.firebug)){
		console.log(message);
	}
}

function consoleLogKeyValue(key,value){
	consoleLog(key + " = " + value);
}

function relPageLocation(){
	url = location.pathname;
	//remove rootUrl from url
	url = url.substr(rootUrl.length);
	return 	url;
}

function sendTrackPageview(url){
	url = rootUrl + "functions/" + url;
	consoleLog(url);
	pageTracker._trackPageview(url);
}

function analyticsSafe(value){
	return value.replace(/\//g, "-");
}

function getQuerystring(key, qstring, default_)
{
  if (default_==null) default_="";
  if (qstring==null) qstring=window.location.href;
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(qstring);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function checkFilterInputs(divLink, state ){
	if (state == "close") {
		var checkboxes = divLink.parent().find("input:checked").length;
		var selectlists = 0;
		divLink.parent().find("select option:selected").each(function () {
		   if ($(this).val() != "") selectlists++;
		});
		if ($("#pricetype").val() == "") selectlists= 0;
		if (checkboxes + selectlists > 0) {
			divLink.css("color","red");
		}
		else{
			divLink.css("color","#003399");
		}
	} else {
		divLink.css("color","#ff6600");
	}
}
	
$(function() {
	//add hover class for msie 6 and lower
	if ($.browser.msie && parseInt($.browser.version)< 7) {
		$("#language_selector li, #main_nav li").hover(
			function() {
				$(this).addClass("over");
			},
			function() {
				$(this).removeClass("over");
			}
		);	
	}
	
	
	$(".list_link_box").hover(
		function() {
			$(this).addClass("over");
		},
		function() {
			$(this).removeClass("over");
		}
	);	
	

	positionSubMenu();
	// set active main menu
	//$("#main_nav ul li li a.active").parents("ul").parents("li").find("a:first").addClass("active");


});

function positionSubMenu(){
	if ($("#subMenu ul").length) {
		var act = $("#mainMenu a.active");
		//left position of active menu item
		var xpos = (act.offset().left - $("#mainMenu").offset().left);
		//add half of active menu item
		xpos += parseInt((act.width() +  parseInt(act.css("padding-left")) +parseInt(act.css("padding-right")))/2);
		//substract half the with of submenu
		xpos -= parseInt($("#subMenu ul").width() /2);
		//if the new pos plus with of the submenu is bigger then the total available with, substract overflow width
		if (xpos + $("#subMenu ul").width() > 970){
			xpos -= xpos + $("#subMenu ul").width() - 963;
		}
		if (xpos > 0){
			$("#subMenu ul").css("margin-left", xpos);
		}
	}
}