function NewsletterPopupShouldBeShown(cookieName) {
	var lCookieValues = document.cookie.split(';');
	var lShowRGPopup = false;
	var lShowNewsletterPopup = true;;

	for (var i = 0; i < lCookieValues.length; i++) {
		var lCookieValue = lCookieValues[i].split('=');

		// determine if the reisgigant popup will be shown
		if (lCookieValue.length > 1 && lCookieValue[0].replace(' ', '') == 'reisgigant.showmessage' && lCookieValue[1].length > 0) {
			lShowRGPopup = true;
		}

		// determine if the reisgigant popup will be shown
		if (lCookieValue.length > 1 && lCookieValue[0].replace(' ', '') == cookieName && lCookieValue[1].length > 0) {
			lShowNewsletterPopup = false;
		}
	}
	return !lShowRGPopup && lShowNewsletterPopup;
}
function HideNewsletterPopup() {
	var lFloatContainer = document.getElementById('newsletter_float_container');
	if (lFloatContainer != null) {
		lFloatContainer.style.display = 'none';
	}

	var lFloatMessage = document.getElementById('newsletter_float_message');
	if (lFloatMessage != null) {
		lFloatMessage.style.display = 'none';
	}
		
	return false;
}
function AddNewsletterPopup(popupUrl) {
	var lBody = document.getElementsByTagName('body')[0];
	if (lBody == null) {
		return;
	}
	
	// the cookie value for reisgigant is found. A floating div should be added to the page now.
	var lHtml = '<div class="newsletter"><div class="title">';
	lHtml += '<span class="closeButton"><a href="#" onclick="return HideNewsletterPopup();"><img src="/party/imgparty/iconCloseOut.gif" alt="sluiten" /></a></span>';
	lHtml += 'Nieuwsbrief</div><div class="message">';
	lHtml += '<iframe src="'+ popupUrl +'" width="100%" height="100%" frameBorder="no" scrolling="no"></iframe>';
	lHtml += '<a class="button" href="#" onclick="return HideNewsletterPopup();">Sluiten</a>';
	lHtml += '</div></div>';

	var lFloatMessage = document.createElement('div');
	lFloatMessage.id = 'newsletter_float_message';
	lFloatMessage.innerHTML = lHtml;
	lBody.appendChild(lFloatMessage);

	var lFloatContainer = document.createElement('div');
	lFloatContainer.id = 'newsletter_float_container';
	lFloatContainer.onclick = function() { return HideNewsletterPopup(); };
	lBody.appendChild(lFloatContainer);

	lFloatContainer.style.height = lBody.scrollHeight + "px";
	lFloatContainer.style.width = lBody.scrollWidth + "px";	
}
function SetCookieValue(cookieName) {
	var d = new Date();
	d.setDate(d.getDate() + 30);
	document.cookie = cookieName + "='shown';expires=" + d.toGMTString() + ";path=/";
}
function ShowNewsletterPopup(isWinter, popupUrl) {
	var cookieName;

	if (isWinter) {
		cookieName = 'jiba.newsletter.winter';
	} else {
		cookieName = 'jiba.newsletter.summer';
	}
	
	if (NewsletterPopupShouldBeShown(cookieName)) {
		AddNewsletterPopup(popupUrl);
		SetCookieValue(cookieName);
	}
}
   // 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 });
}
// 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);
