

function load(){
}

function unload(){
}


/*
=====================================================
Wahanda.com
Global JavaScript functions library
=====================================================
*/

// Function to open links to external sites in a new browser window (target attribute not allowed by XHTML 1.0 Strict)
// (c) SitePoint.com 2003 (http://www.sitepoint.com/article/standards-compliant-world/)
function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
       anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
 }
}


// Function to clear a text input field on click (eg search box)
function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

// Function to write default text to a text input field (eg search box)
function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}

function searchClickClear (thisfield, defaulttext) {
	if (thisfield.value == "") {
	}
}

// Function to toggle visibility of a block-level element
<!--
function hidetoggleb (idtogg)
{
	document.getElementById(idtogg).style.display = (document.getElementById(idtogg).style.display == 'block') ? 'none' : 'block';
}

/*
Trigger code:

onClick="hidetoggleb('ID'); return false;"
*/

// Function to toggle visibility of an inline element
<!--
function hidetogglei (idtogg)
{
	document.getElementById(idtogg).style.display = (document.getElementById(idtogg).style.display == 'inline') ? 'none' : 'inline';
}

/*
Trigger code:

onClick="hidetogglei('ID'); return false;"
*/

function submitForm(el)
{
	document.forms[el].submit()
}

function loadAGalleryImage(el, titleSelector, imageDivSelector) {
	var alt = $(el).children('img:first').attr("alt");
	$(titleSelector).html(alt);
	$(imageDivSelector).html("<img src='" + $(el).attr("href") + "' alt='" + alt + "' />");
}
  
function attachIndexImages(resultIndex,pageIndex) {
	var url;
	var url_over;
	
	if ( resultIndex > 99 ) {
		url = iconUrlBlank;
		url_over = iconUrlOverBlank;
	} else {
		url = iconUrls[resultIndex-1];
		url_over = iconUrlsOver[resultIndex-1];
	}
	
	var numberEl = $('.result-number').eq(pageIndex); 
	var resultEl = $('.search-result').eq(pageIndex);
		
	$(numberEl).css("background-image", "url(" + url + ")");

	//console.log($('.result-number').length );
	
	$(resultEl).hover(function () { 
		$(numberEl).css("background-image", "url(" + url_over + ")");
	}, function (){
		$(numberEl).css("background-image", "url(" + url + ")");	
	});
}	



function getViewportScrollY() {
  var scrollY = 0;
  if( document.documentElement && document.documentElement.scrollTop ) {
    scrollY = document.documentElement.scrollTop;
  }
  else if( document.body && document.body.scrollTop ) {
    scrollY = document.body.scrollTop;
  }
  else if( window.pageYOffset ) {
    scrollY = window.pageYOffset;
  }
  else if( window.scrollY ) {
    scrollY = window.scrollY;
  }
  return scrollY;
};

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
	return curtop;
	}
}
var maptop;
var wrapped = false;
$(window).scroll(function(){
	if(theMap = document.getElementById("module-google-maps")) {
		if(!wrapped) {
			var wrapper = document.createElement("div");
			wrapper.style.position= "relative";
			wrapper.style.top = "";
			wrapper.style.width = theMap.offsetWidth+"px";
			wrapper.style.height = theMap.offsetHeight+"px";
			wrapper.style.marginBottom = "15px";
			
			$("#module-google-maps").wrapAll(wrapper);
			wrapped = true;
		}
		if(!maptop) {
			maptop = findPos(theMap);
		}
		if((getViewportScrollY() >= maptop) && ((window.innerHeight >= (theMap.offsetHeight*2)) || (document.body.clientHeight >= (theMap.offsetHeight*2)))) {
			theMap.style.position = "fixed";
			theMap.style.top="0px";
		} else {
			theMap.style.position= "relative";
			theMap.style.top= "";
		}
	}
});

function setViewportScrollY(scrollY) {
  if( document.documentElement && document.documentElement.scrollTop ) {
    document.documentElement.scrollTop = scrollY;
  }
  else if( document.body && document.body.scrollTop ) {
    document.body.scrollTop = scrollY;
  }
  else if( window.pageYOffset ) {
    window.pageYOffset = scrollY;
  }
  else if( window.scrollY ) {
    window.scrollY = scrollY;
  }
};

$(document).ready(function(){

	// clear password field if username not populated (to stop Salim moaning all the time!)
	if( $("#loginBoxPasswordField").val() != "" ) {
		if ( $("#loginBoxEmailField").val() == "" ) {
			$("#loginBoxPasswordField").val("");
		}
	}
	if( $("#passwordId").val() != "" ) {
		if ( $("#emailId").val() == "" ) {
			$("#passwordId").val("");
		}
	}
	
	// set tab-indexes of all form items to force them into tab-navigation
	$("input[type!=hidden], button, textarea, select, label.radioLabel").tabindex(0);
	
	// remove tab index from links and images - these are making it difficult to tab-navigate forms. Will impair usability for some users however.
	$("a, img").tabindex(-1);
	
	// set target of all external links (starting with http://) to _blank
	externalLinks();
	
	// check whether user is logged in
	determineLoginState();
	
	// instantiate promo carousel
	$("#module-carousel > ul").tabs({ fx: { opacity: 'toggle' } }).tabs('rotate', 4000);
	
	// instantiate booking box tabs
    $("#module-section-search > ul").tabs({ fx: { opacity: 'toggle' } });
  
// ----------------------------------------------------------------------
// SEARCH BOX FUNCTIONS
// ----------------------------------------------------------------------
 	$("#search-for, #search-in-or-near").focus(function () { 
		if ($("#search-for").attr("value")=="e.g. spa name, treatment, keyword") {
			$("#search-for").attr("value","");
		}
		if ($("#search-in-or-near").attr("value")=="i.e. location, postcode") {
			$("#search-in-or-near").attr("value","");
		}	
 	});
	/*
	$("#search-for").tabindex(1);
	$("#search-in-or-near").tabindex(2);
	$("#submit-quick-search").tabindex(3);
	*/
	$("#quick-search").submit(function(){
		
		if ( (($("#search-for").attr("value")=="") || 
					($("#search-for").attr("value")== "e.g. spa name, treatment, keyword"))
			  && (($("#search-in-or-near").attr("value")=="") || 
			  		($("#search-in-or-near").attr("value")== "i.e. location, postcode")) ){ 
			$("#search-for").addClass("error");
			$("#search-in-or-near").addClass("error");
			return false;
		}
		$("#quick-search").submit();
	});
	 	
 	$("#search-for, #search-in-or-near").blur(function () { 
		if (($("#search-for").attr("value")=="") && ($("#search-in-or-near").attr("value")=="")) {			
			$("#search-for").attr("value","e.g. spa name, treatment, keyword");
			$("#search-in-or-near").attr("value","i.e. location, postcode");
		}
	});
	
	$("#search-for, #search-in-or-near").keyup(function(){
		if ( (($("#search-for").attr("value")!="") && 
					($("#search-for").attr("value")!= "e.g. spa name, treatment, keyword") )
			 || (($("#search-in-or-near").attr("value")!="") && 
			 		($("#search-in-or-near").attr("value")!= "i.e. location, postcode")) ){ 
			$("#search-for").removeClass("error");
			$("#search-in-or-near").removeClass("error");
		}
	});
	
	
	
	$("fieldset.voucher-module").click(function(){
		$(this).find(".voucher-input").click();
	})

	$("#search-for").autocomplete(
		"/ajax/type-ahead/keyword",
		{
			width:300,
			delay:10,
			cacheLength:0,
			minChars:2,
			matchContains:1,
			matchSubset:0,
			maxItemsToShow:10,
			selectFirst:false
		}
	).result(function(event, data, formatted) {
		$("#search-in-or-near").focus();
	});
	
	$("#search-for").result(function(event, data, formatted) {
		$("#entityId").val(data[1]);
		$("#entityType").val(data[2]);
	});
	
	$("#search-for").keyup(
		function(){
			$("#entityId").val("");
			$("#entityType").val("");
		}
	);
	
	$(".in-or-near").autocomplete(
		"/ajax/type-ahead/locations",
		{
			width:175,
			delay:10,
			cacheLength:0,
			minChars:2,
			matchContains:1,
			matchSubset:0,
			maxItemsToShow:10,
			selectFirst:false		}
	);

	$(".for-treatment").autocomplete(
		"/ajax/type-ahead/treatments",
		{
			width:200,
			delay:10,
			cacheLength:0,
			minChars:2,
			matchContains:1,
			matchSubset:0,
			maxItemsToShow:10,
			selectFirst:false
		}
	);

// brown search
	$("#searchSpaEntity, #spa-in-or-near").keyup(function(){
		if ( ($("#searchSpaEntity").val()!="") ||
				( ($("#spa-in-or-near").val()!="") && ($("#spa-in-or-near").val()!="Town or postcode") ) ){ 
			$("#searchSpaEntity").removeClass("error");
			$("#spa-in-or-near").removeClass("error");
		}
	});
	
	$("#searchTreatmentEntity, #treatment-in-or-near").keyup(function(){
		if ( ($("#searchTreatmentEntity").val()!="") ||
				( ($("#treatment-in-or-near").val()!="") && ($("#treatment-in-or-near").val()!="Town or postcode") ) ){ 
			$("#searchTreatmentEntity").removeClass("error");
			$("#treatment-in-or-near").removeClass("error");
		}
	});
	
// -------- END SEARCH FUNCTIONS ------------------

// Newsletter Signup Form Checker
	
	$("#fmNewsletterSignup").ajaxForm(function() {
	// Callback function
		var email = document.getElementById("newsletterEmailField").value;
		window.location = "/thankyou/newsletter?redirectTo=" + urlEncode(location.href) + "&email=" + email;
	});
	
	$("#fmNewsletterSignup").validate({
		errorClass: "newsletter-error",
		errorElement: "span",
		errorPlacement: function(error, element) {
			
			error.appendTo( $("#newsletter-message") );
		},
		rules: {
			newsletterEmailField: {
				required: true,
				email: true
			},
			newsletterPostcodeField: {
				required: false,
				minlength: 2
			}
			
		}
	});
	
	$("#newslettersubmit").click(function() {
		if($("#fmNewsletterSignup").valid()) {
			if(document.getElementById("newsletterPostcodeField").value == "Postcode here") {
				document.getElementById("newsletterPostcodeField").value = "";
			}
			$("#fmNewsletterSignup").submit();
		}
		return false;
	});
	
	$("#login-form").submit(function(){
		var emailValue = $('#loginBoxEmailField').val()
		var passValue = $('#loginBoxPasswordField').val()
		var query = { email: emailValue, password: passValue };
		
		jQuery.post("/ajax/profile/login",  query, function(data){
			
			var success = data.getElementsByTagName("success")[0].firstChild.nodeValue;
			if(success == 'true'){
				var signInDiv = document.getElementById("signInPrompt");
				signInDiv.style.display = "none";
				
				var name = data.getElementsByTagName("greeting-name")[0].firstChild.nodeValue;
				var greetingDiv = document.getElementById("greeting");
				greetingDiv.style.display = "inline";
				
				var nameSpan = document.getElementById("greetingName");
				nameSpan.innerHTML = name;
				
				closeLoginBox();
			}
			else{
				var errorMessage = document.getElementById("login-message");
				errorMessage.style.visibility = "visible";
			}
		});
		
		return false;
	});
	
		
	$(".search-result").hover(function() {
		$(this).addClass("search-result-hover");
		$(this).find(".action-link a").css("background-color", "#FEE580");
		$(this).find(".overall-rating-0").css("background-position", "0 -220px");
		$(this).find(".overall-rating-1").css("background-position", "0 -120px");
		$(this).find(".overall-rating-2").css("background-position", "0 -140px");
		$(this).find(".overall-rating-3").css("background-position", "0 -160px");
		$(this).find(".overall-rating-4").css("background-position", "0 -180px");
		$(this).find(".overall-rating-5").css("background-position", "0 -200px");
	
	}, function() {
		$(this).removeClass("search-result-hover");
		$(this).find(".action-link a").css("background-color", "#F3F3F3");
		$(this).find(".overall-rating-0").css("background-position", "0 -100px");
		$(this).find(".overall-rating-1").css("background-position", "0 0px");
		$(this).find(".overall-rating-2").css("background-position", "0 -20px");
		$(this).find(".overall-rating-3").css("background-position", "0 -40px");
		$(this).find(".overall-rating-4").css("background-position", "0 -60px");
		$(this).find(".overall-rating-5").css("background-position", "0 -80px");
	});

	$(".search-result").click(function() {
		window.location = $(this).find(".action-link a").attr("href");
	});
	
	$(".stream-event-content").click(function() {
		window.location = $(this).find(".stream-event-link a").attr("href");
	});
	$(".stream-event-content").hover(function() {
		$(this).addClass("stream-event-content-hover");
		$(this).find(".overall-rating-0").css("background-position", "0 -220px");
		$(this).find(".overall-rating-1").css("background-position", "0 -120px");
		$(this).find(".overall-rating-2").css("background-position", "0 -140px");
		$(this).find(".overall-rating-3").css("background-position", "0 -160px");
		$(this).find(".overall-rating-4").css("background-position", "0 -180px");
		$(this).find(".overall-rating-5").css("background-position", "0 -200px");
	
	}, function() {
		$(this).removeClass("stream-event-content-hover");
		$(this).find(".overall-rating-0").css("background-position", "0 -100px");
		$(this).find(".overall-rating-1").css("background-position", "0 0px");
		$(this).find(".overall-rating-2").css("background-position", "0 -20px");
		$(this).find(".overall-rating-3").css("background-position", "0 -40px");
		$(this).find(".overall-rating-4").css("background-position", "0 -60px");
		$(this).find(".overall-rating-5").css("background-position", "0 -80px");
	});
	
	$("#standalone-login-form").submit(function() {
		return standAloneLogin();
	});
});// END OF $(document).ready(function()


function atozClick(url) {
	document.location=url;
}

function submitSearchForSpa(el){
	if ( ($("#searchSpaEntity").val()=="") &&
				( ($("#spa-in-or-near").val()=="") || ($("#spa-in-or-near").val()=="Town or postcode") ) ){ 
		$("#searchSpaEntity").addClass("error");
		$("#spa-in-or-near").addClass("error");
		return false;
	}
	else{
		if ( $("#spa-in-or-near").attr("value")== "Town or postcode" ){
			$("#spa-in-or-near").attr("value","");
		}
		document.forms[el].submit();
	}
	return false;
}

function submitSearchForTreatment(el){
	if ( ($("#searchTreatmentEntity").val()=="") &&
				( ($("#treatment-in-or-near").val()=="") || ($("#treatment-in-or-near").val()=="Town or postcode") ) ){ 
		$("#searchTreatmentEntity").addClass("error");
		$("#treatment-in-or-near").addClass("error");
		return false;
	}
	else{
		if ( $("#treatment-in-or-near").attr("value")== "Town or postcode" ){
			$("#treatment-in-or-near").attr("value","");
		}
		document.forms[el].submit();
	}
	return false;
}

function submitSearchBox(el) {
	if( document.getElementById("spa-in-or-near").value == "Town or postcode") 
		document.getElementById("spa-in-or-near").value = "";
	if( document.getElementById("treatment-in-or-near").value == "Town or postcode") 
		document.getElementById("treatment-in-or-near").value = "";
	document.forms[el].submit();
}

function determineLoginState(){
	jQuery.post("/ajax/profile/check-recognised", function(data){
		var recognised = data.getElementsByTagName("recognised")[0].firstChild.nodeValue;
		if(recognised == 'true'){
			var name = data.getElementsByTagName("greeting-name")[0].firstChild.nodeValue;
			$("#greeting").css("display", "inline");
			
			$("#greetingName").html(name);
			
			$("#module-register").css("display", "none");
			
		}
		else{
			$("#signInPrompt").css("display", "inline");
		}
	});
}

function login(){
	$("#login-form").submit();	
	return false;
}

function standAloneLogin(){
	
	var emailValue = $('#emaiId').val();
	var passValue = $('#passwordId').val();
	var targetPage = $('#targetPageId').val();
	var query = { email: emailValue, password: passValue };
	
	jQuery.post("/ajax/profile/login",  query, function(data){
		
		var success = data.getElementsByTagName("success")[0].firstChild.nodeValue;
		
		if(success == 'true'){
			window.location=targetPage;	
		}
		else{
			var errorMessage = document.getElementById("login-message-standalone");
			errorMessage.style.visibility = "visible";
		}
	});
	
	return false;
}

function logout(){
	jQuery.get("/ajax/profile/logout", function(data){
		
		var greetingDiv = document.getElementById("greeting");
		greetingDiv.style.display = "none";
		
		var signInDiv = document.getElementById("signInPrompt");
		signInDiv.style.display = "inline";	
		window.location="/";
	
	});
	
	return false;
}

function urlEncode(inVar)
{
	var inString = new String(inVar);
	var outString = new String("");
  	for(i = 0; i < inString.length; i++) 
  	{
  		tempChar = inString.substring(i, i + 1);
 		if		(tempChar == " ") { outString += "+"; continue; }
		else if (tempChar == "!") { outString += "%21"; continue; }
		else if (tempChar == "#") { outString += "%23"; continue; }
		else if (tempChar == "$") { outString += "%24"; continue; }
		else if (tempChar == "%") { outString += "%25"; continue; }
		else if (tempChar == "&") { outString += "%26"; continue; }
		else if (tempChar == "'") { outString += "%27"; continue; }
		else if (tempChar == "(") { outString += "%28"; continue; }
		else if (tempChar == ")") { outString += "%29"; continue; }
		else if (tempChar == "*") { outString += "%2A"; continue; }
		else if (tempChar == "+") { outString += "%2B"; continue; }
		else if (tempChar == ",") { outString += "%2C"; continue; }
		else if (tempChar == "-") { outString += "%2D"; continue; }
		else if (tempChar == ".") { outString += "%2E"; continue; }
		else if (tempChar == "/") { outString += "%2F"; continue; }
		else if (tempChar == ":") { outString += "%3A"; continue; }
		else if (tempChar == ";") { outString += "%3B"; continue; }
		else if (tempChar == "<") { outString += "%3C"; continue; }
		else if (tempChar == "=") { outString += "%3D"; continue; }
		else if (tempChar == ">") { outString += "%3E"; continue; }
		else if (tempChar == "?") { outString += "%3F"; continue; }
		else if (tempChar == "@") { outString += "%40"; continue; }
		else if (tempChar == "[") { outString += "%5B"; continue; }
		else if (tempChar == "\\"){ outString += "%5C"; continue; }
		else if (tempChar == "]") { outString += "%5D"; continue; }
		else if (tempChar == "^") { outString += "%5E"; continue; }
		else if (tempChar == "_") { outString += "%5F"; continue; }
		else if (tempChar == "|") { outString += "%7C"; continue; }
		else if (tempChar == "{") { outString += "%7B"; continue; }
		else if (tempChar == "}") { outString += "%7D"; continue; }
		else if (tempChar == "~") { outString += "%7E"; continue; }
		else if (tempChar == "£") { outString += "%A3"; continue; }
		else if (tempChar == "¬") { outString += "%AC"; continue; }
		else if (tempChar == "`") { outString += "%60"; continue; }
		else { outString += tempChar; }
	}
	return outString;
}

/**
 * replaces a query string parameter (or adds if not present)
 * - does not support multiple params with the same name.
 * - url encodes values but not param names
 */
function setQueryStringParam(uri, param, value) {
	var loc = new String(uri);
	var paramReplaced = false;
	//if we have a hash at the end without an internal link needs to be stripped
	if (loc.charAt(loc.length - 1) == '#') {
		loc = loc.substr(0, loc.length - 1);
	}
	//see if we have a ?
	if (loc.indexOf('?') >= 0) {
		//split location
		newloc = new String(loc.split('?')[0]+'?');
		qs = new String(loc.split('?')[1]);
		//split qs into constituent parts
		qsList = qs.split('&');
		//loop over looking for param
		for (i = 0; i < qsList.length; i++) {
			qsParam = qsList[i].split('=')[0];
			qsValue = qsList[i].split('=')[1];
			//append replacement
			if (qsParam == param) {
				if (!paramReplaced) { 
					if (i > 0) {
						newloc += '&';
					}
					//TODO: figure out why encoding values is causing this function to loop indefintely
					//newloc += qsParam+'='+urlEncode(value);
					newloc += qsParam+'='+value;
					paramReplaced = true;
				}
			}
			else {
				if (i > 0) {
					newloc += '&';
				}
				//TODO: figure out why encoding values is causing this function to loop indefintely
				//newloc += qsParam+'='+urlEncode(qsValue);
				newloc += qsParam+'='+qsValue;
			}
		}
		//if we didn't find it append 
		if (!paramReplaced) {
			newloc += '&'+param+'='+urlEncode(value);
		}
	}
	//otherwise simple - just append
	else {
		newloc = loc+'?'+param+'='+urlEncode(value);  
		//newloc = loc+'?'+param+'='+value;
	}
	return newloc;	
}

function rateReview(id, giveRating) {
	$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Processing");
	jQuery.get(
		'/ajax/site/rate-content',
		{
			contentId: id,
			rating: giveRating
		},
		function(data) {
			var response = data.getElementsByTagName("status")[0].firstChild.nodeValue;
			if ( response == "OKAY" ) {
				if (giveRating == "useful") {
					$(".user-actions[reviewId='"+id+"'] .thumbs-up").addClass("rated");
					$(".user-actions[reviewId='"+id+"'] .thumbs").removeClass("thumbs").removeAttr("onclick").unbind();
					var count = $(".user-actions[reviewId='"+id+"'] .thumbs-up-count").text();
					count++;
					$(".user-actions[reviewId='"+id+"'] .thumbs-up-count").text(count);
				} else {
					$(".user-actions[reviewId='"+id+"'] .thumbs-down").addClass("rated");
					$(".user-actions[reviewId='"+id+"'] .thumbs").removeClass("thumbs").removeAttr("onclick").unbind();
					var count = $(".user-actions[reviewId='"+id+"'] .thumbs-down-count").text();
					count++;
					$(".user-actions[reviewId='"+id+"'] .thumbs-down-count").text(count);
				}
				$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Thank you.");
			} else if ( response == "NOT_LOGGED_IN" ) {
				$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Redirecting to login page");
				//window.location = "/rate-content?contentId="+id+"&rating="+giveRating;
				//build redirect path from current
				path = document.location;
				path = setQueryStringParam(path, "jsAction", "rateReview(\""+id+"\", \""+giveRating+"\");");
				//alert(path);
				document.location = "/protected-action?route=" + urlEncode(path);
			} else if ( response == "OWN_CONTENT" ) {
				$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Sorry, you can't rate your own content");
				$(".user-actions[reviewId='"+id+"'] .thumbs").removeClass("thumbs").removeAttr("onclick").unbind();
			} else if ( response == "ALREADY_RATED" ) {
				$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Sorry, you've already rated this review");
				$(".user-actions[reviewId='"+id+"'] .thumbs").removeClass("thumbs").removeAttr("onclick").unbind();
			} else {
				$(".user-actions[reviewId='"+id+"'] .rating-ajax").text("Sorry, something went wrong");
			}
		}
	);
	return false;

}



