   // redirect to the content page
   function redirectToContent(linkElemenent, url) {
   	// if the call is made from the history page, toggle the tabs
   	if (IsRedirectFromContent(url)) {
   		var lSplits = url.split('#');
   		if (lSplits[1] != undefined) {
   			var el = $get(lSplits[1]);
   			// try getting the #termTab to be focused
   			if (focusTab && el != undefined) {
   				var tab = $get(el.id + '_data');
   				focusTab(tab);
   				focusTabItem(el, tab);
   			}
   			// if no tabs are available, redirect
   			else {
   				window.location = url;
   			}
   		}
   		// if the page does not contain any #term, redirect
   		else {
   			window.location = url;
   		}
   	}
   	// if the call is made from a page diferent than the content page, redirect
   	else {
   		window.location = url;
   	}
   }
   // check to see if the redirect call is made from the content page
   function IsRedirectFromContent(url) {
   	var lPath = 'content/index.aspx';
   	return (url.indexOf(lPath) > -1) && (window.location.href.indexOf(lPath) > -1);
   }

(function($) {

	$(document).ready(function() {
	
		if (!IsHistoryCookieAvailable()) {
			UpdateHistory();
		}
		else {
			DisplayHistoryFromCookie();
		}
	});

})(jQuery);



var panel = document.getElementById('pnlCompositionEditor');
if (panel != undefined && panel.parentNode) {
	panel.parentNode.removeChild(panel);
	document.forms[0].insertBefore(panel, document.forms[0].firstChild);
}
function ResizeFadeOutPanel() {
	var panel = document.getElementById('pnlCompositionEditor');
	panel.style.height = document.getElementsByTagName("body")[0].scrollHeight + "px";
	panel.style.width = document.getElementsByTagName("body")[0].scrollWidth + "px";
}
// redirect to the history page
function redirectToHistory(linkElemenent, url) {
	// if the call is made from the history page, toggle the tabs	
	if (IsRedirectFromHistory(url)) {		
			var lSplits = url.split('#');
			if (lSplits[1] != undefined) {
				var el = $get(lSplits[1]);
				var tab = $get(el.id + '_data');				
				focusTab(tab);
				focusTabItem(el, tab);
		}
	}
	// if the call is made from a page diferent than the history page, perform the redirect
	else {
		window.location = url;
	}
}
// check to see if the redirect call is made from the history page
function IsRedirectFromHistory(url) {
	var lPath = 'index.aspx#';
	return (url.indexOf(lPath) > -1) && (window.location.href.indexOf('history') > -1);
}
// updates the text on the user menu control with the number of viewed/stored accommodations.
function UpdateButtonTexts(savedText, viewedText) {
		//defer the update of the button texts until the page is fully loaded.
		$(document).ready(function() {
			SaveHistoryCountsInCookie(viewedText, savedText);
			DisplayHistory(viewedText, savedText);
		});
}

function updateUserMenu(id, message) {
	var lButton = $get(id);
	if (lButton) {
		lButton.innerHTML = message;
	}
}





function DisplayHistory(viewedCount, storedCount) {


	var viewedText = $('#HistoryLink_Viewed').html().replace(/\(\d*\)/, "(" + viewedCount + ")");
	var storedText = $('#HistoryLink_Stored').html().replace(/\(\d*\)/, "(" + storedCount + ")");
	var viewedLink = $('#HistoryLink_Viewed');
	var storedLink = $('#HistoryLink_Stored');
	viewedLink.html(viewedText);
	storedLink.html(storedText);
	viewedLink.attr("title", viewedText);
	storedLink.attr("title", storedText);
}

function UpdateHistory() {

	var lCode = $("input#code").val();

	$.ajax({

		type: "POST",
		url: "/accommodation/WebServices/CustomerHistoryService.svc/UpdateCustomerHistory",
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify({ "key": lCode }),
		dataType: "json",
		success: function(json) {

			SaveHistoryCountsInCookie(json.d.Viewed, json.d.Stored);
			DisplayHistory(json.d.Viewed, json.d.Stored);

		}
	});
}

function IsHistoryCookieAvailable() {
	var lCode = $("input#code").val();
	return $.cookie("HistoryItemsViewed" + lCode) != null;
}

function DisplayHistoryFromCookie() {
	var lCode = $("input#code").val();
	DisplayHistory($.cookie("HistoryItemsViewed" + lCode), $.cookie("HistoryItemsStored" + lCode));

}
function SaveHistoryCountsInCookie(viewedCount, storedCount) {
	var lCode = $("input#code").val();
	$.cookie("HistoryItemsViewed" + lCode, viewedCount, { path: "/", expires: 30 });
	$.cookie("HistoryItemsStored" + lCode, storedCount, { path: "/", expires: 30 });
}
function NewWindow(theURL,winName,features)
{
  newwindow = window.open(theURL,winName,features);
  if (newwindow) {
  	newwindow.focus();
  }
}

//Scalable Tabset script 
//TODO:
//check why sometimes the offsetwidth is smaller then the rendering width
//

/**************************
Restructure code
**************************/

var isFirstTab = true;

function buildTabs(){	
		
	// Create a container for the tab panel headings
	var tabContainer = $("<ul class='strip'></ul>").appendTo(this);
	var panelContainer = $("<div class='data'></div>").appendTo(this);
	
	$("> div[class!=data]", this)

	// Process the tabs and their panels
		.each(function() {
			var tabPanelId = $(this).attr("id").toLowerCase();
			// Give each tab panel a proper id and proper styling.
			// Add a clearing div to force floated content to clear properly.
			var tabPanel =
				$(this)
					.attr("id", tabPanelId + "_data")
					.addClass("tab")
					.append("<div class='clearing'></div>");

			// Add a tab heading for each panel
			$("<li></li>")
				.attr("id", tabPanelId)
				.text(tabPanel.attr("title"))
				.appendTo(tabContainer);

			// Move the tab using the direct DOM functions instead of jQuery.appendTo,
			// which re-runs scripts.
			panelContainer[0].appendChild(this);
		})
		.filter(":first")
			.each(function() {
				focusTab(this);
			});

	// Prevent margin spacing on the last tab heading
	tabContainer
		.find("li:last")
			.addClass("nomargin");

	// If the current tabset was hidden (while loading the page) make it visible now.
	$(this).removeClass("hidden");	
}

/**************************
runtime behavior code
**************************/

function tabclick(el, useFallback) {
	var tab = document.getElementById(el.id + '_data');
	// call google tracker to track the tab click
	// the call is in a try{}catch{} block because the method needs to 
	// be defined in the page before the call.

	// for the implicit tab that is loaded the tracking is bypassed
	if (!isFirstTab) {
		try { trackTabClick(el); } catch (err) { }

	}
	isFirstTab = false;
	focusTab(tab);
	focusTabItem(el, tab);
	GetOriginalStrips(tab);

	if (IsFallbackNeeded(el, 0) > 1) {
		if ((useFallback != null) && (useFallback)) {
			fallbackFocus(el);
		}
	}
	if (el.id == "pricetable" && typeof (InitPriceScrollbar) != "undefined") {
			InitPriceScrollbar();
	}
}

/*Recursively determines if a tab control nested inside another tab control 
tabs - number of tab controls in the nest
*/
function IsFallbackNeeded(tabItem, tabs) {
	if (tabItem.nodeType == 9) {
		//reached the end document node so there is no point in going further
		return tabs;
	}
	else {
		if (tabItem.className.indexOf('tabset') > -1 && tabItem.className.indexOf('set') > -1) {
			//found a tab control
			tabs++;
		}
		//go one step up in the DOM
		return IsFallbackNeeded(tabItem.parentNode, tabs);
	}
}

/*if the current tab control is nested inside another tab control focus the tabs as required*/
function fallbackFocus(tabItem) {

	//get the tab the current tab is nested in
	var tabs = new Array();

	tabs = getParentTabItem(tabItem.parentNode, tabs);

	if (tabs != null && tabs.length == 2) {
		//focus the tab and its content
		//		focusTab(tabs.pop());
		//		focusTabItem(tabs.pop());

		focusTab(tabs[1]);
		focusTabItem(tabs[0]);
		tabs[1].focus();
	}
}

function getParentTabItem(el, tabs) {
	if (el.nodeType == 9 || tabs.length > 0) {
		//no elements found ... if this point is reached then there is an error
		return null;
	}
	else {
		if (el.id.indexOf('_data') > -1) {
			// a (data) was found
			var tabItem = getTabItemFromTabData(el);
			// a tab was found (LI)
			if (tabItem != null) {
				tabs.push(tabItem);
				tabs.push(el);

				return tabs;
			}
		}
		else {
			//go one level up in the DOM
			return getParentTabItem(el.parentNode, tabs);
		}
	}
}

function getTabItemFromTabData(tabData) {
	var tabItemId = tabData.id.substring(0, tabData.id.length - 5);
	return document.getElementById(tabItemId);
}

/* tab strip items behavior */
function focusTabItem(tabItem, dataTab) {
	var tabStripList = tabItem.parentNode.parentNode.childNodes;
	var i;

	for (i = 0; i < tabStripList.length; i++) {
		if ((tabStripList[i].nodeType == 1) && (tabStripList[i].className.indexOf('strip') > -1)) {
			blurSiblingTabItems(tabStripList[i].firstChild)
		}
	}
	//		blurSiblingTabItems(tabItem.parentNode.firstChild);
	tabItem.className += " on";

	try {
		FindOverflowClass(dataTab.childNodes, 'fragment')
	}
	catch (err) {

	}
}

function blurSiblingTabItems(tabItem) {
	if (tabItem != null) {
		if (tabItem.nodeType == 1)// elements only
		{
			tabItem.className = tabItem.className.replace(/\s*on/, '');
			if (document.all) {
				tabItem.className = tabItem.className.replace(/\s*hover/, "");
			}
		}
		blurSiblingTabItems(tabItem.nextSibling);
	}
}

/* tab (data) behavior */
function focusTab(tabElement) {
	if (tabElement != null) {
		blurSiblingTabs(tabElement.parentNode.firstChild);
		tabElement.className += " on";
	}
}

function findActiveTab(tabSet) {
	// find the first div in a div (first tab in data div)
	var CurTab = tabSet.getElementsByTagName('DIV')[1];
	while (CurTab != null) {
		if (CurTab.className.indexOf('on') > -1) {
			return CurTab;
		}
		else {
			CurTab = CurTab.nextSibling;
		}
	}
	return null;
}

function resizeParent(tabElement) {
	var maincont = tabElement.parentNode.parentNode;
}

function blurSiblingTabs(tabElement) {
	if (tabElement != null) {
		if (tabElement.nodeType == 1)// elements only
		{
			tabElement.className = tabElement.className.replace(/\s*on/, '');
		}
		blurSiblingTabs(tabElement.nextSibling);
	}
}

/* behavior init methods */
function setTabsBehavior(tabdiv) {
	var TabItem = tabdiv.getElementsByTagName('LI')[0];
	while (TabItem != null) {
		SetTabItemBehavior(TabItem);
		TabItem = TabItem.nextSibling;
	}
}

function SetTabItemBehavior(node) {
	node.onmouseover = function() { node.className += ' hover' }
	node.onmouseout = function() { node.className = node.className.replace(/\s*hover/, '') }
	node.onclick = function() { tabclick(node); }
}

function openTabFromUrl() {
	var locSplit = window.location.href.split('#');
	var result = '';

	if (locSplit.length > 1)
		result = locSplit[locSplit.length - 1].toLowerCase();

	return result;
}

function openFirstTabs() {
	var nodeId = openTabFromUrl();
	var tabNode = $(nodeId.length > 0) ? document.getElementById(nodeId) : null;
	if (tabNode) {
		tabclick(tabNode, true);
	}
	else {
		var tabs = $("> ul > li", this);
		if (tabs.length > 0) tabclick(tabs[0]);		
	}
}

function applyTabBehaviors() {
		setTabsBehavior(this);
}

/* like click on tab */
function openTab(tabId) {
	var tab = document.getElementById(tabId);
	if (tab) {
		// open the tab
		tabclick(tab);
		// open parent
		var parent = tab.parentElement;
		while (parent != null && parent.id.indexOf('_data') < 0) {
			parent = parent.parentElement;
		}
		if (parent != null) {
			openTab(parent.id.replace('_data', ''));

		}
	}
}

/* click from an external link and lunck the click on tab */
function remoteOpenTab(link) {
	var locSplit = link.split('#');
	var result = '';

	if (locSplit.length > 1)
		result = locSplit[locSplit.length - 1].toLowerCase();
	openTab(result);
}

function openLocationHashTab() {
	var hash = location.hash;
	var tabId;

	if (hash != '') {
		tabId = hash.replace('#', '');
		var element = document.getElementById(tabId);
		if (element != null) {
			/* Check if the provided hash is not real anchor */
			if (element.tagName != 'A') {
				openTab(tabId);
			}
			else {  //ie bugfix
				var parent = element.parentNode;
				while (parent != null && parent.id.indexOf('_data') < 0) {
					parent = parent.parentNode;
				}
				if (parent != null) {
					openTab(parent.id.replace('_data', ''));
				}
			}
		}
		else {
			var anchorCol = document.getElementsByTagName('A');
			var i = 0;
			var foundElement;
			for (i; i < anchorCol.length; i++) {
				if (anchorCol[i].name == tabId) {
					foundElement = anchorCol[i];
					i = anchorCol.length;
				}
			}
			if (foundElement != null) {
				var parent = foundElement.parentNode;
				while (parent != null && parent.id && parent.id.indexOf('_data') < 0) {
					parent = parent.parentNode;
				}
				if (parent != null) {
					openTab(parent.id.replace('_data', ''));
				}
			}
		}
	}
}

// New Scale specific script

function setNoMarginLastChild(List) {
	if ((List != null) && (List.lastChild != null)) {
		List.lastChild.className += " nomargin"
	}
} 

//search strip elements
//if a strip element is found
//look is there are sibling strip elements
function GetOriginalStrips(node) {
	var count = 0;
	var list;
	list = node.getElementsByTagName('UL');
	//loop through all ul items
	for (count; count < list.length; count++) {
		//if it is a strip element
		if (list[count].className.indexOf("strip") > -1) {
			var placeholder;
			var placeholderSet = false;
			var parent;
			var originalStrip;
			//get sibling ul set for a complete list item set. This is done in case a tabstrip is already split across several strips. 
			var siblingSet = list[count].parentNode.childNodes
			var y;

			//create a dummy placeholder for the future tabstrips
			placeholder = document.createElement('DIV');
			placeholder.className = 'placeholder';
			placeholder.id = 'dummy';

			originalStrip = document.createElement('UL');
			originalStrip.className = 'strip';

			placeholder.appendChild(originalStrip);

			//reverse order. Original tabstrip is split across several ul's with the last ul containing the first li's
			for (y = siblingSet.length - 1; y >= 0; y--) {
				if (siblingSet[y].nodeType == 1 && siblingSet[y].className.indexOf("strip") > -1) {
					parent = siblingSet[y].parentNode;
					if (!placeholderSet) {
						// place a placeholder and remove the split strip
						parent.insertBefore(placeholder, siblingSet[y]);
						y = y + 1;
						AppendListItems(originalStrip, parent.removeChild(siblingSet[y]));
						placeholderSet = true;
					}
					else {
						//remove the split strip
						AppendListItems(originalStrip, parent.removeChild(siblingSet[y]));
					}
				}

			}
			//original strip is restored. and placed in the placeholder in a strip element. It is placed in a strip element
			// for the width calculation of the elements. If this is not done the style on the listitems are lost.

			//create new tabstrips next
			count += CreateNewTabStrips(originalStrip, placeholder) - 1;
		}
	}
}

//create new tabstrips at the place of the placeholder
function CreateNewTabStrips(originalStrip, placeholder) {
	var currentInsertPoint;
	var totalWidth;
	var elementWidth;
	var elementCount;
	var stripCount = 0;

	var widthLimit = GetWidthLimit(document.getElementById(originalStrip.childNodes[0].id + '_data'));
	var i = 0;
	//set current insertion point
	currentInsertPoint = placeholder;
	//get list item count
	elementCount = originalStrip.childNodes.length;

	//get a new tab strip with the correct css classes
	var newStrip = GetNewStrip(stripCount++)
	//strip paddings
	var totalWidth = 5 * stripCount;
	//add the strip to the dom and set is as the current insert point for listitems/strips
	currentInsertPoint.parentNode.insertBefore(newStrip, currentInsertPoint)
	currentInsertPoint = newStrip;
	//loop through all the list items
	for (i = 0; i < elementCount; i++) {
		//get elementwidth(offsetwidth(contentwidth + paddingwidth's + borderWidth's) + marginWidth's
		elementWidth = GetElementWidth(originalStrip.childNodes[0]);

		//check if new width exceeds the limit
		if ((totalWidth + elementWidth) > widthLimit) {
			//limit exceded
			//create a new tabstrip set.
			//insert it in the DOM
			//Set it as the current insertion point.
			//reset the width counter
			setNoMarginLastChild(currentInsertPoint);
			newStrip = GetNewStrip(stripCount++);
			currentInsertPoint.parentNode.insertBefore(newStrip, currentInsertPoint)
			currentInsertPoint = newStrip;
			totalWidth = 5 * stripCount;
		}
		//add the list item to the strip
		currentInsertPoint.appendChild(originalStrip.childNodes[0]);
		//count the width
		totalWidth += elementWidth;
	}

	//when done remove the obsolete placeholder container
	placeholder.parentNode.removeChild(placeholder);
	return stripCount;
}

//gather all the list items of the strips in a set.
function AppendListItems(targetElement, listItemContainer) {
	var itemList = listItemContainer.getElementsByTagName('LI');
	var count = itemList.length;
	var i = 0;
	for (i = 0; i < count; i++) {
		//IE FIX
		//fixes stuck hover effect.
		// TODO check why hover is stuck and check strange behavior when 2 tabsets are involved
		// guessing hover style gets stuck at a resize event cycle when the li's are split across different strips.
		while (itemList[0].className.indexOf('hover') > 1) {
			itemList[0].className = itemList[0].className.replace(/\s*hover/, "");
		}

		targetElement.appendChild(itemList[0]);
	}
}

//calculate the element currentwidth of the provided element
function GetElementWidth(el) {
	var totalElementWidth = 0;
	if (document.all) {
		//IE
		totalElementWidth = el.offsetWidth + parseInt(el.currentStyle.marginLeft.replace('px', '')) + parseInt(el.currentStyle.marginRight.replace('px', ''));
	}
	else {
		//Firefox opera does not work in safari
		totalElementWidth = el.offsetWidth + parseInt(window.getComputedStyle(el, null).marginLeft.replace('px', '')) + parseInt(window.getComputedStyle(el, null).marginRight.replace('px', ''));
	}
	return totalElementWidth;
}

//create a strip with the correct css classes
function GetNewStrip(count) {
	var newStrip = document.createElement('UL');
	if (count == 0) {
		newStrip.className = 'strip';
	}
	else {
		newStrip.className = 'strip strip' + count;
	}
	return newStrip
}

//get the width limit of the strips
//gets the tab_data segment and searches the displayed tab
//and returns it's offsetWidth
function GetWidthLimit(el) {
	var list = el.parentNode.childNodes;
	var counter = 0;
	while (list[counter] != null) {
		if (list[counter].nodeType == 1 && list[counter].offsetWidth > 0) {
			return list[counter].offsetWidth - 5;
		}
		counter++
	}
	return 300; //in the event that no width is found return a standard value
}

// checks if tabElement.id is in the array tracking list and if it is track the tab on google analytics.
function trackOnGoogleTabClick(tabElement, googlePageTracker) {
	var lTabText, lTabsToTrack, lIndex, lPath, lCurrentPageAddress;

	// an array to keep all the tab id's we want to track on Google Analytics
	lTabsToTrack = new Array('pricetable', 'info', 'testimonial', 'excursions', 'flights', 'dive',
		'weather', 'map', 'carrent', 'accommodations', 'bookoptions', 'skiarea', 'destinations');

	// web address to track
	// use regular expression to replace the space intead of simple replace
	lTabText = tabElement.innerHTML.replace(/ /g, '_').replace(/&amp;/g, '&');
	lIndex = document.location.toString().indexOf(document.location.pathname.toString())
	lPath = document.location.toString().substring(lIndex);
	lCurrentPageAddress = lPath + '~' + lTabText;

	// loop and see if the tabElement.id belongs to the array list; if it belongs then track the event if not continue 
	// to the next iteration 
	for (i = 0; i < lTabsToTrack.length; i++) {
		if (lTabsToTrack[i] != tabElement.id)
			continue;

		if (googlePageTracker != null) {
			googlePageTracker._trackPageview(lCurrentPageAddress);
		}
	}
}

/*
	Since the redrawing of the HTML for the tabs can have iframes to become empty,
	reload the iframes
*/
function reloadFrames() {
	$("div.tabset iframe[src]:visible", document).each(function() {
		try {
			var iFrameCopy = $(this).clone();
			$(this).replaceWith($(iFrameCopy));
		}
		catch (e) { }
	});
}

function InitTabs() {

	$("div.tabset", document).each(function() {

		// Check for presence of an initialization marker, so that
		// the tabset isn't initialized twice.
		if ($(this).data("tabset-initialized"))
			return true; /* continue */

		// Store a marker indicating the tabset as initialized.		
		$(this).data("tabset-initialized", true);

		buildTabs.apply(this, []);
		applyTabBehaviors.apply(this, []);
		openFirstTabs.apply(this, []);
		reloadFrames.apply(this, []);

		openLocationHashTab();

		GetOriginalStrips(this);
	});

	// Work around issues with the Google visualization API rendering the column chart for
	// climate information into a dynamic iframe. The iframe's contents end up wiped when
	// the DOM containing the iframe is manipulated by the tab-generating script.

	// Wrap everything in a try-catch as the drawChart variable may be undeclared.
	try {
		// Assume this is the drawChart function we got from thirdparty code.
		if (drawChart) {
			function fixChart() {
				if (climateBarDrawn === true) // Is only set after the graph has been generated.
				{
					$("#show-weather-bar-chart iframe", document).remove();
					drawChart();
				}
				else {
					setTimeout(fixChart, 250);
				}
			}
			setTimeout(fixChart, 250);
		}
	}
	catch (e) {
	} 
}
function submitInfoUsefulFeedback(answer, ansnwerDetails, pageUrl, feedbackControlID) {


	var feedbackUrl = "https://nieuwsbrief.sunweb.nl/SSL/renderer/messagentHTTPS2.aspx?ID=eOgbwKneCAueeeW&FID=aanmelden&NUTTIG=" + answer +
		  "&MERK=" + siteVariationBrandCode + "&URL=" + escape(pageUrl) + "&OPMERKING=" + escape(ansnwerDetails);


	document.getElementById(feedbackControlID +"_frmInfoUsefulFeedback").src = feedbackUrl;


	var wizardStep1 = document.getElementById(feedbackControlID + "_infoUsefulFeedBackWizardStep1");
	var wizardStep2 = document.getElementById(feedbackControlID + "_infoUsefulFeedBackWizardStep2");

	closeInfoUsefulFeedbackDetails(feedbackControlID);
	
	wizardStep1.style.display = "none";
	wizardStep2.style.display = "inline";

}
function openInfoUsefulFeedbackDetails(feedbackControlID) {
	document.getElementById(feedbackControlID + "_infoUsefulFeedBackAnswerDetails").style.display = "inline";
	document.getElementById(feedbackControlID + "_infoUsefulFeedBackAnswerDetails").focus();
}

function closeInfoUsefulFeedbackDetails(feedbackControlID) {
	document.getElementById(feedbackControlID + "_infoUsefulFeedBackAnswerDetails").style.display = "none";
}
/**
 * ELabel.js 
 * This Javascript is provided by Mike Williams
 * Blackpool Community Church Javascript Team
 * http://www.commchurch.freeserve.co.uk/   
 * http://econym.googlepages.com/index.htm
 * This work is licenced under a Creative Commons Licence http://creativecommons.org/licenses/by/2.0/uk/
*/
/**
* @author Marco Alionso Ramirez, marco@onemarco.com
* @version 1.0
* The Tooltip class is an addon designed for the Google
* Maps GMraker class.
*/

function Tooltip(marker, content, padding) {
  this.marker = marker;
  this.content = content;
  this.padding = padding;
  this.div = null;
  this.map = null;
}

function InitializeTooltip() {
  Tooltip.prototype = new GOverlay();

  Tooltip.prototype.initialize = function(map) {

    this.div = document.createElement("div");
    var innerContainer = this.div.cloneNode(false);
    this.div.appendChild(innerContainer);
    this.div.style.position = 'absolute';
    this.div.style.visibility = 'hidden';
    innerContainer.className = 'googleTooltip';

    var child = typeof this.content == 'string' ?
		document.createTextNode(this.content) :
		this.content;
    innerContainer.appendChild(child);
    map.getPane(G_MAP_FLOAT_PANE).appendChild(this.div);
    //map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(this.shadow);
    this.map = map;
  }

  Tooltip.prototype.remove = function() {
    this.div.parentNode.removeChild(this.div);
  }

  Tooltip.prototype.copy = function() {
    var content = typeof this.content == 'string' ? this.content : this.content.cloneNode(true);
    return new Tooltip(this.marker, content, this.padding);
  }

  Tooltip.prototype.redraw = function(force) {
    if (!force) return;

    //draw tooltip
    var markerPos = this.map.fromLatLngToDivPixel(this.marker.getPoint());
    var iconAnchor = this.marker.getIcon().iconAnchor;
    var xPos = Math.round(markerPos.x - this.div.clientWidth / 2);
    var yPos = markerPos.y - iconAnchor.y - this.div.clientHeight - this.padding;
    this.div.style.top = yPos + 'px';
    this.div.style.left = xPos + 'px';
  }

  Tooltip.prototype.show = function() {
    this.div.style.visibility = 'visible';
  }

  Tooltip.prototype.hide = function() {
    this.div.style.visibility = 'hidden';
  }
}

function ELabel(point, html, classname, pixelOffset, percentOpacity, overlap)
{
  // Mandatory parameters
  this.point = point;
  this.html = html;

  // Optional parameters
  this.classname = classname || "";
  this.pixelOffset = pixelOffset || new GSize(0, 0);
  if (percentOpacity)
  {
    if (percentOpacity < 0) { percentOpacity = 0; }
    if (percentOpacity > 100) { percentOpacity = 100; }
  }
  this.percentOpacity = percentOpacity;
  this.overlap = overlap || false;
  this.hidden = false;
}

function InitializeELabel()
{
  ELabel.prototype = new GOverlay();

  ELabel.prototype.initialize = function(map)
  {
    var div = document.createElement("div");
    div.style.position = "absolute";
    div.innerHTML = '<div class="' + this.classname + '">' + this.html + '</div>';
    map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(div);
    this.map_ = map;
    this.div_ = div;
    if (this.percentOpacity)
    {
      if (typeof (div.style.filter) == 'string') { div.style.filter = 'alpha(opacity:' + this.percentOpacity + ')'; }
      if (typeof (div.style.KHTMLOpacity) == 'string') { div.style.KHTMLOpacity = this.percentOpacity / 100; }
      if (typeof (div.style.MozOpacity) == 'string') { div.style.MozOpacity = this.percentOpacity / 100; }
      if (typeof (div.style.opacity) == 'string') { div.style.opacity = this.percentOpacity / 100; }
    }
    if (this.overlap)
    {
      var z = GOverlay.getZIndex(this.point.lat());
      this.div_.style.zIndex = z;
    }
    if (this.hidden)
    {
      this.hide();
    }
  };

  ELabel.prototype.getContentDiv = function()
  {
    return this.div_;
  };

  ELabel.prototype.remove = function()
  {
    this.div_.parentNode.removeChild(this.div_);
  };

  ELabel.prototype.copy = function()
  {
    return new ELabel(this.point, this.html, this.classname, this.pixelOffset, this.percentOpacity, this.overlap);
  };

  ELabel.prototype.redraw = function(force)
  {
    var p = this.map_.fromLatLngToDivPixel(this.point);
    var h = parseInt(this.div_.clientHeight, 10);
    this.div_.style.left = (p.x + this.pixelOffset.width) + "px";
    this.div_.style.top = (p.y + this.pixelOffset.height - h) + "px";
  };

  ELabel.prototype.show = function()
  {
    if (this.div_)
    {
      this.div_.style.display = "";
      this.redraw();
    }
    this.hidden = false;
  };

  ELabel.prototype.hide = function()
  {
    if (this.div_)
    {
      this.div_.style.display = "none";
    }
    this.hidden = true;
  };

  ELabel.prototype.isHidden = function()
  {
    return this.hidden;
  };

  ELabel.prototype.supportsHide = function()
  {
    return true;
  };

  ELabel.prototype.setContents = function(html)
  {
    this.html = html;
    this.div_.innerHTML = '<div class="' + this.classname + '">' + this.html + '</div>';
    this.redraw(true);
  };

  ELabel.prototype.setPoint = function(point)
  {
    this.point = point;
    if (this.overlap)
    {
      var z = GOverlay.getZIndex(this.point.lat());
      this.div_.style.zIndex = z;
    }
    this.redraw(true);
  };

  ELabel.prototype.setOpacity = function(percentOpacity)
  {
    if (percentOpacity)
    {
      if (percentOpacity < 0) { percentOpacity = 0; }
      if (percentOpacity > 100) { percentOpacity = 100; }
    }
    this.percentOpacity = percentOpacity;
    if (this.percentOpacity)
    {
      if (typeof (this.div_.style.filter) == 'string') { this.div_.style.filter = 'alpha(opacity:' + this.percentOpacity + ')'; }
      if (typeof (this.div_.style.KHTMLOpacity) == 'string') { this.div_.style.KHTMLOpacity = this.percentOpacity / 100; }
      if (typeof (this.div_.style.MozOpacity) == 'string') { this.div_.style.MozOpacity = this.percentOpacity / 100; }
      if (typeof (this.div_.style.opacity) == 'string') { this.div_.style.opacity = this.percentOpacity / 100; }
    }
  };

  ELabel.prototype.getPoint = function()
  {
    return this.point;
  };
  ELabel.prototype.U = function()
  {
    return this.point;
  };
  ELabel.prototype.V = function()
  {
    return this.point;
  };
  ELabel.prototype.W = function()
  {
    return this.point;
  };
  ELabel.prototype.X = function()
  {
    return this.point;
  };
  ELabel.prototype.Y = function()
  {
    return this.point;
  };
  ELabel.prototype.Z = function()
  {
    return this.point;
  };
}

//Exception handling
function NetMatchGoogleException(name, message)
{
  this.name = name;
  this.message = message;
}
NetMatchGoogleException.prototype.toString = function()
{
  return this.name + " : " + this.value;
};
function ManageException(e)
{
  var settings = read_settings();

  if (settings['targetControlId'] != '' && (settings['errorMessage'] != '' || e.name == 'BrowserException'))
  {
    var mapDiv = document.getElementById(settings['targetControlId']);
    //clear any child the target control might have
    var parent = mapDiv.parentNode;
    var i = 0;
    for (i = 0; i < parent.childNodes.length; i++)
    {
      if (parent.childNodes[i].id == settings['targetControlId']) 
	  {
		ApplyWidthAndHeight(parent.childNodes[i].style, 0, 0);
	  }
      else
      {
        parent.removeChild(parent.childNodes[i]);
      }
    }
    //add the error paragraph
    var errorParagraph = document.createElement('p');
    parent.appendChild(errorParagraph);

    //mapDiv.style.display = 'none';
    ApplyWidthAndHeight(mapDiv.style, 0, 0);
    
    document.getElementById('errorField').value = e.name + '<br />' + e.value;

    if (e.name != 'BrowserException')
      errorParagraph.innerHTML = settings['errorMessage'];
    else
      errorParagraph.innerHTML = e.message;
  }
}
function read_secondaryMarkers(markersValue)
{
  var aResult;
  if (markersValue !== '')
  {
    //the input is formated like : (23,12 ^ 31,49) (51,01 ^ 14,37) 
    var i = 0;
    var matches = 0;
    //find out if there are more than 1 pairs of (latitude, longitude) coordinates
    for (i = 0; i < markersValue.length; i++)
    {
      if (markersValue.charAt(i) == '(')
      {
        matches++;
        //more than 1 pair found so we can break
        if (matches > 1)
        {
          break;
        }
      }
    }

    var latitude, longitude, id;

    // an array result having as key an index and the value a (latitude, longitude) pair.
    // eg. aResult[1,0] = latitude0;
    //     aResult[1,1] = longitude0;
    var mSplit

    //if there is exactly 1 pair
    if (matches == 1)
    {
      aResult = new Array(1);
      aResult[0] = new Array(4);

      mSplit = markersValue.split('^');

      //the latitude will look something like (23,12^34,19^name^id) so we have to remove the '(' and the ')'
      latitude = mSplit[0];
      latitude = parseFloat(latitude.substring(1, latitude.length).replace(',', '.'));
      aResult[0][0] = latitude;

      longitude = mSplit[1];
      longitude = parseFloat(longitude.replace(',', '.'));
      aResult[0][1] = longitude;

      aResult[0][2] = mSplit[2];

      id = mSplit[3];
      id = parseInt(id.substring(0, id.length - 1, 10));
      aResult[0][3] = id;
    }
    else		//there are at least 2 coordinates pairs :   (11,32 : 14:56)(19,76 : 41,59)(23,14 : 19:51)
    {
      var markers = markersValue.split(')(');
      aResult = new Array(markers.length);

      mSplit = markers[0].split('^');
      aResult[0] = new Array(4);
      //clean the first result as above : (11,32 ^ 145,6 ^ 12
      latitude = mSplit[0];
      latitude = parseFloat(latitude.substring(1, latitude.length).replace(',', '.'), 10);
      aResult[0][0] = latitude;
      aResult[0][1] = parseFloat(mSplit[1]); 		//the longitude
      aResult[0][2] = mSplit[2];                      //the name
      aResult[0][3] = parseInt(mSplit[3]); 		//the id of the acco/dest/region

      //clean the last result as above : 11,32 ^ 145,6 ^ 12)
      aResult[1] = new Array(4);
      mSplit = markers[markers.length - 1].split('^');
      aResult[1][0] = parseFloat(mSplit[0]); 	//latitude
      longitude = mSplit[1]; 					//longitude
      longitude = parseFloat(longitude.replace(',', '.'));
      aResult[1][1] = longitude;
      aResult[1][2] = mSplit[2];
      aResult[1][3] = parseInt(mSplit[3], 10); 	//the id of the acco/dest/region

      //create the other coordinate pairs, from the second to the last but one coordinate pairs
      i = parseInt(i);
      for (i = 1; i < markers.length - 1; i++)
      {
        mSplit = markers[i].split('^');
        aResult[i + 1] = new Array(4);
        //the latitude
        aResult[i + 1][0] = parseFloat(mSplit[0]);
        //the longitude
        aResult[i + 1][1] = parseFloat(mSplit[1]);
        //the name 
        aResult[i + 1][2] = mSplit[2];
        //the id
        aResult[i + 1][3] = parseInt(mSplit[3]);
      }
    }
  }

  return aResult;
}

function read_settings()
{
  var settings = document.getElementById('settingsDiv');

  //get the value of the settings hidden field 
  if (settings !== undefined)
  {
    //for IE
    var sttngs = settings.childNodes[0].value;
    if (sttngs == undefined)
    {
      //for non-IE
      settings = settings.childNodes[1].value;
    }
    else
    {
      settings = sttngs;
    }
  }
  //the settings
  var geoSettings;

  if (settings != undefined)
  {
    geoSettings = settings.split(';');
  }

  //create a dictionary like structure for the settings
  //dSettings["latitude"] = 91,1231
  //the incrementation goes till length - 1 because the split creates an extra null element at the end of the array
  var i = 0;
  var dSettings = new Array(geoSettings.length);
  for (i = 0; i < geoSettings.length; i++)
  {
    var key = geoSettings[i].split(':')[0];
    var value = geoSettings[i].split(':')[1];

    if (key != 'secondaryMarkers')
    {
      dSettings[key] = value;
    }
    else
    {
      dSettings[key] = read_secondaryMarkers(value);
    }

    if (key == 'latitude' || key == 'longitude')
    {
      dSettings[key] = parseFloat(value.replace(',', '.'), 10);
    }
    if (key == 'level' || key == 'entityId')
    {
      dSettings[key] = parseInt(value, 10);
    }
    if (key == 'OneEntityOnGoogleMapZoomLevel') {
		dSettings[key] = parseInt(value, 10);
    }
  }
    return dSettings;
  }
  
function failedCallback(e)
{
  ManageException(e);
}

function CreateTabs(marker, id, level) {
	$.ajax({
		type: "POST",
		url: "/googleMaps/Service/GoogleMapHelperService.asmx/GetTabInfo",
		contentType: "application/json; charset=utf-8",
		data: JSON.stringify({ id: id, level: level }),
		dataType: "json",
		success: function(json) {
			var info = json.d.split("/**/");

			if (info[0].length + info[1].length > 0) {





				var detailsDiv = ['<div id="detailsDivTab" class="googleDetailsDiv">', info[0], '</div>'].join('');
				var photosDiv = ['<div id="pictureDivTab" class="googlePictureDiv">', info[1], '</div>'].join('');

				var tabs = [
					new GInfoWindowTab('Details', detailsDiv),
					new GInfoWindowTab('Fotos', photosDiv)
				];

				marker.openInfoWindowTabsHtml(tabs);
			}
		},
		error: function(xhr, status, error) {
			// Pull the JSON-serialized exception from the responseText manually.
			var err = JSON.parse(xhr.responseText);
			err && failedCallback(err);

			throw new NetMatchGoogleException('Service exception', '');
		}
	});     

}

function CreateSimpleMarker(latitude, longitude, id, level, map, name)
{
  //single click -> display	additional information
  var marker = new GMarker(new GLatLng(latitude, longitude));
  GEvent.addListener(marker, 'click', function() { CreateTabs(marker, id, level); }, failedCallback);
  
  var tooltip = new Tooltip(marker, name, 4);
  marker.tooltip = tooltip;  
  map.addOverlay(tooltip);
  GEvent.addListener(marker, 'mouseover', function() {    
    this.tooltip.show();
  });
  GEvent.addListener(marker, 'mouseout', function() {
    this.tooltip.hide();
  });
  
  map.addOverlay(marker);

  return marker;
}

function GetPath(markerData, level)
{
  var path = window.location.pathname;

  if (level == 3)
      path = path.replace('/region/', '/destination/');

  return window.location.protocol + '//' + window.location.host + path + '?id=' + markerData[3] + '#map';
}
function CreateRegionMarkers(map, settings)
{
  var i = 0;
  var secMarkers = settings['secondaryMarkers'];

  if (secMarkers != undefined)
  {
    for (i = 0; i < secMarkers.length; i++)
    {
      var content = '<nobr><a href="' + GetPath(secMarkers[i], settings['level']) + '">' + secMarkers[i][2] + '</a></nobr>';

      var marker = new ELabel(new GLatLng(secMarkers[i][0], secMarkers[i][1]), content, 'contentMarker');
      map.addOverlay(marker);
    }
  }
}

function CreateAccommodationMarker(map, settings) {
  var marker = CreateSimpleMarker(settings['latitude'], settings['longitude'], settings['entityId'], 1, map, settings['entityName']);
  CreateTabs(marker, settings['entityId'], settings['level']);
}

function CreateDestinationMarkers(map, settings)
{
  var i = 0;

  var secMarkers = settings['secondaryMarkers'];
  if (secMarkers != undefined)
  {
		// bounds used to determine the best zoom level and map center
		var bounds = new GLatLngBounds();
		
    for (i = 0; i < secMarkers.length; i++) {
      var marker = CreateSimpleMarker(secMarkers[i][0], secMarkers[i][1], secMarkers[i][3], 2, map, secMarkers[i][2]);
      bounds.extend(marker.getPoint());
    }
    // best fit the zoom level so that all accommodations to be visible on the map.
    bestFit(map, bounds);
  }
}

// this function adds markers to the provided coordinates              
// map - is a reference to a GoogleMap object
// coordinates - is an Array with elements like : (coordinates[1][0], coordinates[1][1]) corresponding to the latitude & longitude        
function add_markers(map, settings)
{
  switch (settings['level'])
  {
    case 1: CreateAccommodationMarker(map, settings); break;
    case 2: CreateDestinationMarkers(map, settings); break;
    case 3: CreateRegionMarkers(map, settings); break;
  }
}
//this function is used to open a link to accommodation-page, from the infotabs's links to accommodations
//in case that we are on the accommodation page (level 1), just the tab is changed to 'pricetable'
function openLinkToPricetableOrPhotos(href, showPhotos, photoUrl)
{
  var settings = read_settings();
  switch (settings['level'])
  {
    case 1: 
       if (showPhotos)
       {
         NewWindow(photoUrl, null , 'toolbar=no,menubar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width=756,height=485'); 
         return false;
         break;
       }
       else
       {
        openTab('pricetable'); return false; break;
       }
       break;
    case 2: location.href = href; break;
  }  
}

function ApplyWidthAndHeight(divStyle, width, height)
{
  //IE
  divStyle.width = width;
  //non-IE
  if (divStyle.width == '')
  {
    divStyle.width = width + 'px';
  }
  //IE
  divStyle.height = height;
  //non-IE
  if (divStyle.height == '')
  {
    divStyle.height = height + 'px';
  }
}
function setTitle(settings) {  
  var title = document.getElementById('googleMapTitle');
  var map = document.getElementById(settings['targetControlId']);
  title.parentNode.removeChild(title);
  map.parentNode.insertBefore(title, map);
}
// Call this function when the page has been loaded  
function initialize() {
	InitializeELabel();
  InitializeTooltip();  
  var settings = null;
  try {
  	settings = read_settings();  	
    var d1 = undefined;
    var d2 = '';

    if (settings.length > 0 && GBrowserIsCompatible()) {
      ApplyWidthAndHeight(document.getElementById(settings['targetControlId']).style, parseInt(settings['width']), parseInt(settings['height']));

      //get the latitude and the longitude 
      var latitude = settings['latitude'];
      var longitude = settings['longitude'];

      if (latitude < -90 || longitude < -180 || latitude > 90 || longitude > 180)
      {
        throw new NetMatchGoogleException('CoordinatesException', 'The latitude and/or the longitude are empty.');
      }

      var target = document.getElementById(settings["targetControlId"]);
      target.tip = '';
      target.parentNode.parentNode.title = '';
      var map = new GMap2(target);

      setZoomLevel(map, settings); 
      
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      if (settings['showOvervieMap'] == 'True')
        map.addControl(new GOverviewMapControl(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0)));

      map.disableContinuousZoom();
      map.disableDoubleClickZoom();

      //add markers
      add_markers(map, settings);
			
      ShowTitle();

      setTitle(settings);

      //if the destination has coordinates, but its accommodation don't, set the zoom level to the standard zoom level
      if (map.getZoom() == 0)
      	setZoomLevel(map, settings);
    }
    else
    {
      //if your browser is not capable of handling the google framework
      throw new NetMatchGoogleException('BrowserException', 'Your browser is not able to render the content of this page.');
    }

    //clear any memory leaks
    $(window).unload(function() { GUnload() }); ;
  }
  catch (e)
  {
    ManageException(e);
  }
}

// best fit the zoom level and the center for the bounds
function bestFit(map, bounds) {
	// maximum zoom level accepted
	var maxZoomLevel = 13; 
	
	// get calculated zoom.
	var zoom = map.getBoundsZoomLevel(bounds);
	
	// if calculated zoom is greater than maximum zoom level accepted reset the zoom
	// to maximum level accepted
	//zoom = zoom > maxZoomLevel ? maxZoomLevel : zoom;
   map.setZoom(zoom);
   map.setCenter(bounds.getCenter());
}

//Set a zoom level to the map.
function setZoomLevel(map, settings) {
	// The accommodation level (1) should have a higher zoom level
	// If there is only one marker to be displayed, also increase the zoom level.
	if (settings['level'] == 1 ||
 			(settings['secondaryMarkers'] != undefined && settings['secondaryMarkers'].length == 1))
		standardHighZoom(map, settings);
	else
		map.setCenter(new GLatLng(settings['latitude'], settings['longitude']), parseInt(settings['zoom'], 10));
}

// If there is a single marker on the map, the ZoomLevel will be taken from a config value.
 function standardHighZoom(map, settings) {
 	map.setCenter(new GLatLng(settings['latitude'], settings['longitude']), settings['OneEntityOnGoogleMapZoomLevel']);
 }
function addEvent(obj, evType, fn) {
  if (obj.addEventListener) {
    obj.addEventListener(evType, fn, false);
    return true;
  }
  else if (obj.attachEvent) {
    return obj.attachEvent("on" + evType, fn);
  } else {
    return false;
  }
}
function ShowTitle() {
  var div = document.getElementById('googleMapTitle');
  div.style.visibility = 'visible';
  div.style.display = 'block';
}
function LoadGoogleMapScript() {
  
  var key = document.getElementById('key').value;
  var script = document.createElement('script');
  var path = "http://maps.google.com/maps?file=api&v=2.x&key=" + key + "&c&async=2&callback=initialize&hl=nl";
  script.setAttribute('src', path);
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
  script = document.createElement('script');
}
function GetSourceControlId() {
	return "map";
}
function AttachToControl() {
  var sourceControlId = GetSourceControlId();
  if (window.location.href.indexOf('#map') > -1) {
    LoadGoogleMapScript();
  }
  else {
    var obj = document.getElementById(sourceControlId);
    if (obj != undefined)
      addEvent(obj, 'click', LoadGoogleMapScript);
  }
}
// Handles the keypress in the textbox.
function KeyHandler(e) 
{
    if (navigator.appName == 'Netscape')
    {
        if (e.which == 13)
        {
            e.cancelBubble = true;
            e.returnValue = false;
            RedirectToSearch();
            if (e.stopPropagation)
            { e.stopPropagation();}
            if (e.cancelable)
            {
            e.preventDefault();
            }
      }
    }
    else
    {
        if (window.event.keyCode == 13)
        {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
            RedirectToSearch();
        }
    }
}


function RedirectToSearch()
{
	var searchPage;
	var relPath = _DimSearchPage;
	var lSearchTerm = document.getElementById('SearchTerm').value;
	
	// Variables for use when search term == default search term
	var lDefaultSearchTerm = _DefaultTextSearchTerm;
	var lDimSearchPageDefaultSearched = _DimSearchPageDefaultSearched;
	var lSearchPageDefaultSearched;

  //if a page has a relative path to itself
  if (relPath == "")
  {
    var location = window.location.href;
    location = location.substring(location.lastIndexOf('/')+1);
    if(location.indexOf('?') >=0)
    {
      location = location.substring(0,location.indexOf('?'));
    }
    
    relPath = location; 
  }
  
  // if a page has a relative path to itself (DefaultString used)
  if (lDimSearchPageDefaultSearched == "" && lSearchTerm == lDefaultSearchTerm)
  {
    var location2 = window.location.href;
    location2 = location2.substring(location2.lastIndexOf('/')+1);
    if(location2.indexOf('?') >=0)
    {
      location2 = location2.substring(0,location2.indexOf('?'));
    }
    
    lDimSearchPageDefaultSearched = location2;
  }
  
  if (document.getElementById('baseUrl'))
  {
    searchPage = document.getElementById('baseUrl').href;
  }
  else
  {
    searchPage = window.location.href;
  }

	searchPage = searchPage.substring(0, searchPage.lastIndexOf('/'));
	while (relPath.indexOf('../') >= 0)
	{
	searchPage = searchPage.substring(0, searchPage.lastIndexOf('/'));
	relPath = relPath.substring(relPath.indexOf('../') + 3);
	}
	
	// The url contains an ../. Check if this has to be deleted.
	while (lDimSearchPageDefaultSearched.indexOf('../') >= 0)
	{	
		lDimSearchPageDefaultSearched = lDimSearchPageDefaultSearched.substring(lDimSearchPageDefaultSearched.indexOf('../') + 3);
	}
	
	// Copy the searchpage variable
	lSearchPageDefaultSearched = searchPage;
	
	searchPage = searchPage + '/' + relPath;

	if(lSearchTerm != null && lSearchTerm != '' && lSearchTerm != lDefaultSearchTerm)
    window.location.href = searchPage + '?N=0&search=' + lSearchTerm;
  
  // When default search term, redirect to another page.
  if (lSearchTerm == lDefaultSearchTerm)
  {
		window.location.href = lSearchPageDefaultSearched + '/' + lDimSearchPageDefaultSearched + '?search=' + lSearchTerm;
  }
}
(function($) {

	// uncomment to disable search merchanding
	// return;

	$(document).ready(function() {
		var lSiteVariationCode = $("#searchMerchandisingSiteVariationCode", document).val();

		$.ajax({
			type: "POST",
			url: "/Shared/Services/SearchMerchandisingService.svc/GetSearchMerchandising",
			contentType: "application/json; charset=utf-8",
			data: JSON.stringify({ siteVariationCode: lSiteVariationCode }),
			dataType: "json",
			success: function(json) {
				$("#SearchMerchandisingContainer", document).html(json.d);
			}
		});
	});

	// Utility function that constructs the search query string from the dropdown boxes
	function GetSearchQuery() {
		var lSearchQuerystring = "";

		$("#SearchMerchandisingContainer select", document).each(function() {
			if (this.selectedIndex > 0) {
				if (lSearchQuerystring == "")
					lSearchQuerystring += this.options[this.selectedIndex].value;
				else
					lSearchQuerystring += "+" + this.options[this.selectedIndex].value;
			}
		});

		return (lSearchQuerystring == "") ? "0" : "N=" + lSearchQuerystring;
	}

	// Called through an onchange= on a tag. Should be defined on the window so is 'global'.	
	window.RefreshResultCount = function() {
		var lSiteVariationCode = $("#searchMerchandisingSiteVariationCode", document).val();
		$("#searchMerchandisingAccoCount", document).html('<img src="/shared/img/ajax-loader.gif" width="16px" height="16px;" />');

		$.ajax({
			type: "POST",
			url: "/Shared/Services/SearchMerchandisingService.svc/GetSearchMerchandisingUpdate",
			contentType: "application/json; charset=utf-8",
			data: JSON.stringify({ endecaQuery: GetSearchQuery(), siteVariationCode: lSiteVariationCode }),
			dataType: "json",
			success: function(json) {

				$("#searchMerchandisingAccoCount", document).html(json.d.NumberOfResults);

				if (json.d.CountryOptionList != null) {
					var lCountrySelect = $("#sm_COUNTRY", document).empty();
					$.each(json.d.CountryOptionList, function() {
						$("<option></option>")
							.text(this.Key)
							.attr("value", this.Value)
							.appendTo(lCountrySelect);
					});
				}
			}
		});
	}

	// Called through an onclick= on a tag. Should be defined on the window so is 'global'.	
	window.RedirectToSearchPage = function(searchPageUrl) {
		window.location.href = searchPageUrl + '?' + GetSearchQuery();
	}

})(jQuery);
