   // 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);
		}
	}
}


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, []);

		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";
}
// 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);
