<!-- Start hiding script

/* Variables */

var win=null;
var new_window;
var selectedId;
var selectedTxt;
var selectedTip;
var selectedTipId;
var picDivisor = 10000;
/* Things to do with the search pages */
var calExists, cal, adate1 = 0, adate2, countriesShown = 0;

/*
 *  Helper Variables
 */
if (typeof(YAHOO) != "undefined") {
    var $D = YAHOO.util.Dom;
    var $E = YAHOO.util.Event;
    var $A = YAHOO.util.Anim;
    var $M = YAHOO.util.Motion;
    var $S = YAHOO.util.Scroll;
    var $ = $D.get;
}

/* Generic useful functions */

function rscopenwindow(file,width,height) {
	new_window=window.open(file,'change','toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+width+',height='+height);
	if (window.focus) { new_window.focus(); }
}

function ajfopenwindow(file,height,width)  {
	win=window.open(file,'Change','toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+width+',height='+height);
	win.focus();
}

function formatDateTime(date) {
	var output = date.getUTCFullYear() + "-" + 
		padLeft(date.getUTCMonth() + 1, 2, 0) + "-" +
		padLeft(date.getUTCDate(), 2, 0) + " " +
		padLeft(date.getUTCHours(), 2, 0) + ":" +
		padLeft(date.getUTCMinutes(), 2, 0) + ":" +
		padLeft(date.getUTCSeconds(), 2, 0);
	return output;
}

function padLeft(inputString, minLength, padValue) {
	inputString = new String(inputString);
	while (inputString.length < minLength) {
		inputString = padValue + inputString;
	}
	return inputString;
}

/* ?? */

function showImage(_id){
	var test;
	var hid;
	var rhid;
	test = _id.split(",");
	hid=test[1].split("_");
	rhid=hid[0].split("/");
	if (test[0]=="show"){		
		var mainImage = document.getElementById('bigPic_'+rhid[1]);
		mainImage.src = "/picsmall/"+test[1];	
	}
	if (test[0]=="hide"){
		var mainImage = document.getElementById('bigPic_'+rhid[1]);
		mainImage.src = "/picsmall/"+mainImage.name.replace(".:.", "/");
	}
	
}


function markResponded(_id){
    var image = document.getElementById('responded_'+_id);
    var reqs = document.getElementById('reqs');
    var imageSrc = image.src;
    if (imageSrc.match("/i/phone_go.png") != null)
    {
        var _str = reqs.innerHTML;
        var strArr;
        
        _strArr = _str.split(" ");
        _str = _strArr[0];
        _str = _str -1;
        _str = _str + " non-actioned requests";
        reqs.innerHTML = _str;
        var surl = 'tools_callback_ajax.aspx?action=markAsResponded&id='+_id+'&ms=' + new Date().getTime();
	    var request = YAHOO.util.Connect.asyncRequest('GET', surl, {success:handleRequestTool,failure:showError});
	}
}

function handleRequestTool(o){
    var image = document.getElementById('responded_'+ o.responseText);
    image.src = "/i/tick.png";
}

function addRequest(){
    var _name = document.getElementById('cust_support_name');
    var _number = document.getElementById('cust_support_telno');
    var _string = _number.value;
    
    YAHOO.util.Dom.setStyle(['cust_support_name','cust_support_telno','callback_button','callme'], 'visibility', 'hidden');    
    YAHOO.util.Dom.setStyle(['ajaxLoader','ajaxLoaderText'], 'display', 'inline');
    
    if (_name.value == "" || _name.value == "Enter name (optional)"){
        _name.value = "";
    }
    var surl = 'whychooseus_ajax.aspx?action=addRequest&num='+_string+'&name='+_name.value+'&ms=' + new Date().getTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', surl, {success:handleRequesta,failure:showErrora});
}

function handleRequesta(o) {
    var cbs = document.getElementById('callbackMessage');
    cbs.innerHTML = o.responseText;
    YAHOO.util.Dom.setStyle('cs_middle', 'width', '192px');
    YAHOO.util.Dom.setStyle('callbackMessage', 'display', 'inline');
    YAHOO.util.Dom.setStyle('callback_button', 'visibility', 'hidden');
    YAHOO.util.Dom.setStyle(['ajaxLoader','ajaxLoaderText','cust_support_name','cust_support_telno','callme','form1'], 'display', 'none');
}

function showErrora(o){
    var cbs = document.getElementById('callbackMessage');
    cbs.innerHTML = "<br>We're sorry, there has been an error. <br><br> Please contact our support team on +44 (0)1865 312 000";
    YAHOO.util.Dom.setStyle('callbackMessage', 'display', 'inline');    
    YAHOO.util.Dom.setStyle(['ajaxLoader','ajaxLoaderText','cust_support_name','cust_support_telno','callback_button','callme'], 'display', 'none');
}

function handleCountry(o) {
	var result = o.responseText.split('|||');
	document.getElementById('filter_country').innerHTML = result[1];
}

function showError() {
}

function searchCountry() {
	if (countriesShown == 0) {
		var temp = document.createElement('div');
		temp.setAttribute('id', 'filter_country');
		temp.innerHTML = "<img src='/images/ajax_busy.gif'>"
		document.getElementById('filter_toploc').appendChild(temp);

		var surl = 'sr_ajax.asp?action=countrybox&ms=' + new Date().getTime();
		var request = YAHOO.util.Connect.asyncRequest('GET', surl, {success:handleCountry,failure:showError});
		countriesShown = 1
	} else if (countriesShown == 1) {
		YAHOO.util.Dom.setStyle('filter_country', 'display', 'none');
		countriesShown = -1;
	} else {
		YAHOO.util.Dom.setStyle('filter_country', 'display', 'block');
		countriesShown = 1;
	}

}

function changeURL(lsNew) {
	var aUrl = window.location.href.split("/");
	
	var lsTemp = aUrl[aUrl.length - 2];
	lsTemp = lsTemp.substring(0, 6);
	if (lsTemp == "pageid") {
		aUrl[aUrl.length - 2] = "";
	}
	aUrl[aUrl.length] = lsNew;
	lsNew = aUrl.join("/");
	
	if (lsNew.indexOf("homesearch.asp")!=-1){
		//if the URL has homesearch in it then strip it out as handled elsewhere. Leave in anything else to catch date search etc. (Strip to slash url)
		var keyStart = lsNew.indexOf("keywords=");
		lsNew=lsNew.substring(keyStart+9);
	}

	timer = setTimeout("window.location.href = '" + lsNew + "'", 5);
}

function show_roll(ident) {
	YAHOO.util.Dom.removeClass('roll_' + ident, 'filter_roll');
	YAHOO.util.Dom.setStyle('show_roll_' + ident, 'display', 'none');
	return false;
}

/* Things to do with budget on search pages */
function changeBudget() {
	/* budget_max first because it's first alphabetically */
	var budget_min = document.getElementById('budget_min').value;
	var budget_max = document.getElementById('budget_max').value;
	
	budget_min = parseInt(budget_min, 10);
	budget_max = parseInt(budget_max, 10);
	
	var lsParams = "budget_max./budget_min./";
	if (isNaN(budget_max) == false) { lsParams = lsParams + "budget_max." + budget_max + "/"; }
	if (isNaN(budget_min) == false) { lsParams = lsParams + "budget_min." + budget_min + "/"; }
	changeURL(lsParams);
}

/* Search pages calendar things */
var searchSelected = function( type, args, obj ) {
	var dates = args[0];
	var date = dates[0];
	
	if (adate1 == 0) {
		adate1 = getAdate(date);
		document.getElementById('search_instr').innerHTML = 'Now please select a departure date:';
	} else {
		adate2 = getAdate(date);
		if (adate1!=adate2){ 
			document.getElementById('add_dates').innerHTML = 'Please wait...';
			YAHOO.util.Dom.setStyle('add_dates', 'display', 'block');
			YAHOO.util.Dom.setStyle('search_cal_outer', 'display', 'none');
			//IE doesn't like setting the window.location before returning false to a link. It seems to cancel the navigation 80% of the time. So, let's do it in 5ms
			changeURL('adate1.' + adate1 + '/adate2.' + adate2 + '/');
		}
	}
}

function cancelCal() {
	adate1 = 0;
	adate2 = 0;
	cal.deselectAll();
	cal.render();
	YAHOO.util.Dom.setStyle('search_cal_outer', 'display', 'none');
	YAHOO.util.Dom.setStyle('add_dates', 'display', 'block');
}

function showCal() {
	//calHide();
	YAHOO.util.Dom.setStyle('search_cal_outer', 'display', 'block');
	YAHOO.util.Dom.setStyle('add_dates', 'display', 'none');
	if (calExists) {
		//setCalDate("arrive", cal1);
	} else {
		var dt = new Date();
		var cur_year = dt.getYear();
		if (cur_year < 1000) { cur_year = cur_year + 1900; }
		cal = new YAHOO.widget.Calendar('cal','calContainer', { 
			mindate:(dt.getMonth() + 1) + '/' + (dt.getDate() + 1) + '/' + cur_year,
			maxdate:(dt.getMonth() + 1) + '/' + (dt.getDate() + 1) + '/' + (cur_year + 2)
			} );
		cal.selectEvent.subscribe( searchSelected );
		cal.render();
		calExists = true;
	}
}

function getAdate(date) {
	//Get 1 day in milliseconds
	var one_day=1000*60*60*24;
	
	//Set starting point
	var millennium = new Date(2000, 0, 1); //Month is 0-11 in JavaScript
	
	// What is today's adate?
	var today = new Date(date[0], date[1] - 1, date[2]);

	//Calculate difference btw the two dates, and convert to days
	var adate = Math.ceil((today.getTime()-millennium.getTime())/(one_day));
	return adate;
}

/* Stop search calendar */

function roundprice(rprice, rbpence) { 
	//rprice [the full price to be rounded]
	//rbpence flag to specify to round to pence(3.99) or to pound(3)[  1=pence 0=pounds ]
	//rprice=222.5; rbpence=1;
	
	//alert('roundpence() rprice='+rprice + ' rbpence='+rbpence);
	var mystr = rprice.toString();
	var mypos=mystr.indexOf(".");
	//alert('roundpence() mypos='+mypos);
	if (mypos==-1)  {
		retval=mystr;
		//Put comma in to represent thousand separator - what a pain!!
		//alert('leaving here');
		
		
		if (rbpence==1)   {
			//No decimal place, so add the .00
			retval=mystr+'.00'
		}
	}
	else  {	
	
		if (rbpence==1)  {
			//Add a ZERO if only one number after the decimal place
			//Get the bit before the decimal place
			var after = mystr.slice(mypos+1);
			//alert('a) after='+after);
			if (after.length==1)  {  //dp+1digit==2
				after=after+'0';
				//alert('b) after='+after);
			}
			else  {
				//Get 3 digits (if they exist) so we can round properly
				//alert('after=' + after);
				
				if (after.length > 2 )  {
					after=after.slice(0,2) + '.' + after.slice(2,3);
					//Rounds to 2 dp
					after=Math.round(after);
				}
				//alert('after slice=' + after);
			}
			retval=mystr.slice(0,mypos) + '.' + after;
		}
		else  {
			//Just return the bit before the decimal place
			//retval=mystr.slice(0,mypos);
			retval=Math.round(mystr)
		}
		
		
	}
	//alert('roundpence() retval='+retval);
	return addCommas(retval);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//Function to get around the javascript division/multiplying with fractions bug.
//For example, 85*0.175 should be 14.875, but comes out as 14.874999999999998
function roundNumber(number, decimals) {
	//Round up the extra buggy decimal
	number = Math.round(number * Math.pow(10, decimals + 1));
	//Get the correct last decimal
	number = Math.round(number / 10);
	//Move the floating point to the correct number of decimals
	number = number / Math.pow(10, decimals);
    return number.toFixed(decimals);
}

function findobject(n, d) { 
  var x,i,p;

	if(!d) d=document; 
	//alert ('fine');
	if((p=n.indexOf("?"))>0&&parent.frames.length) {
    	d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
  	if(!(x=d[n])&&d.all) x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findobject(n,d.layers[i].document);
	if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function NewWindow(mypage,myname,w,h,pos,infocus){
	if(pos=="random"){myleft=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;mytop=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
	if(pos=="center"){myleft=(screen.width)?(screen.width-w)/2:100;mytop=(screen.height)?(screen.height-h)/2:100;}
	else if((pos!='center' && pos!="random") || pos==null){myleft=0;mytop=20}
	
	settings="width=" + w + ",height=" + h + ",top=" + mytop + ",left=" + myleft + ",scrollbars=no,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no";
	win=window.open(mypage,myname,settings);
	win.focus();
	
}

function showHideElement(id){
	//check for certain elements and disable
	if(document.getElementById(id)){
		if(document.getElementById(id).id==id){
			var el = document.getElementById(id).style;			
			if (showRogueFields != ""){
			    if (showRogueFields) {
			        el.visibility="";
			    } else {
			        el.visibility="hidden";
			    }
			} else {			
			    if (el.visibility=="hidden"){
				    el.visibility="";
			    }else{
				    el.visibility="hidden";
			    }
			}
		}
	}
}

/* Functions relating to ajax captcha registration and check */
function registerCaptcha(callbackFunction, callbackArgument) {
    var url = "ajax/CaptchaRegister_Ajax.aspx?ts=" + getEpochTime();
    var request = YAHOO.util.Connect.asyncRequest('GET', url, { success: registerCaptchaSuccess, failure: registerCaptchaFailure, argument: {callback: callbackFunction, argument: callbackArgument} });
}

function registerCaptchaSuccess(response) {
    var callbackFunction = response.argument.callback
    var callbackArgument = response.argument.argument
    
    // Expected response text is 'Ok||{image}|{public key}'
    var responseArray = response.responseText.split("|", 4);
    if (responseArray[0] == "Ok") {
        var captchaImage = responseArray[2];
        var captchaPublicKey = responseArray[3];
        callbackFunction(captchaImage, captchaPublicKey, callbackArgument);
    } else {
        registerCaptchaFailure(response);
    }
}

function registerCaptchaFailure(response) {
    alert('error');
}

/* Functions relating to ajax enquiry survey response comment update */
function registerEnquirySurveyResponse() {
	var url = "ajax/EnquirySurveyResponse_Ajax.aspx?ts=" + getEpochTime();
	YAHOO.util.Connect.setForm('commentForm');
	var request = YAHOO.util.Connect.asyncRequest('POST', url, { success: registerEnquirySurveyResponseSuccess, failure: registerEnquirySurveyResponseFailure });
}

function registerEnquirySurveyResponseSuccess(response) {
	// Expected response text is 'True||'
	var responseArray = response.responseText.split("|", 3);
	if (responseArray[0] == "True") {
		if (document.getElementById('comment_div')) {
			document.getElementById('comment_div').style.display = 'none';
		}
		if (document.getElementById('response_div')) {
			document.getElementById('response_div').style.display = 'none';
		}
		if (document.getElementById('response_comment_div')) {
			document.getElementById('response_comment_div').style.display = 'block';
		}
		if (document.getElementById('enquiry_response_share')) {
			document.getElementById('enquiry_response_share').style.marginTop = '-100px';
		}	
		if (document.getElementById('car_hire_widget_for_survey')) {
			document.getElementById('car_hire_widget_for_survey').style.display = 'none';
			if (document.getElementById('hidden_reponse_share')) {
				document.getElementById('hidden_reponse_share').style.display = 'block';
				document.getElementById('enquiry_response_share').style.marginTop = '0px';
			}
		}
	} else {
		registerEnquirySurveyResponseFailure(response);
	}
}

function registerEnquirySurveyResponseFailure(response) {
	//do nothing
}

/* Functions relating to the share popup on enquiry response landing page */
function enquiryResponsePopupShow(url, parent, child) {    
    var contentHtml = createShareThisTable(url);
    createTrianglePopup(parent, child, 17, 16, 310, 10, contentHtml);
}

/* Functions relating to the video share popup on premium advert page - called from hd_functions */
function videoSharePopupShow() {    
    var contentHtml = createShareThisTable(document.location.href);
    createTrianglePopup('parent_link', 'video_share_popup', 317, 12, 310, 10, contentHtml);
}

/* Functions relating to the video takedown popup on premium advert page - called from hd_functions */
function videoTakedownClick(message) {
    registerCaptcha(videoTakedownPopup, message);
}

function videoTakedownPopup(captchaImage, captchaPublicKey, message) {
    var popup = document.getElementById("video_takedown_popup");
    var contentHtml = "";
    
    // The class to display any error message and user entry prompts in.
    var pClass = (message == "") ? "" : "error";    
    
	if (!popup ) {
	    // Build the content from scratch the first time.
        contentHtml = 
                "<div id='vtd_thanks' style='display:none;'><br/><h2>Thank you for reporting this video.</h2>" +
                "<p>We will review the video and take necessary action as soon as possible (our working hours are Monday &ndash; Friday, 9am &ndash; 5.30pm).</p>" + 
                "<p>We will only contact you if we require further clarification of your complaint.</p><br/>" +
                "</div>" +
                "<div id='vtd_container' style='display:block;'><form name='vtd_form'>" + 
                "<h2>Report this video</h2>" +
                "<p id='vtd_message' class='error'>" + message + "</p>" +
                "<p>If you wish to report this video, please select a category that best suits your complaint:</p>" +
                "<select id='vtd_reason_select' name='vtd_reason_select'><option>Please select</option><option>Inappropriate content</option><option>Copyrighted content</option><option>Misleading</option><option>Other</option></select><br/><br/>" +
                "<p id='vtd_question1' class='" + pClass + "'>In the box below, please provide further details of your compaint.</p>" +
                "<p>If your complaint is copyright related, please include details of the original content and your contact details.</p>" +
                "<textarea id='vtd_reason_text' name='vtd_reason_text' style='width:390px;height:70px;'></textarea><br/><br/>" +
                "<img id='vtd_captcha_img' name='vtd_captcha_img' src='" + captchaImage + "' width='200' height='55' /><br/><br/>" +
                "<p id='vtd_question2' class='" + pClass + "'>Please type the characters you see in the pattern above.</p>" + 
                "<input type='text' id='vtd_user_answer' name='vtd_user_answer' style='width:100px;'/>" + 
                "<input type='hidden' id='vtd_captcha_key' name='vtd_captcha_key' value='" + captchaPublicKey + "'/>" +
                "<input type='hidden' id='vtd_video_id' name='vtd_video_id' value='" + document.getElementById("video_id").value + "'/>" +
                "<div style='text-align:right;'>" +
                "<a id='vtd_report_link' href='javascript:videoTakedownAction();'>" + 
                "<img class='button' alt='Report this video' title='Report this video' src='/images/buttons09/o-report-white.gif'/>" +
                "</a></div></form></div>";
                
        videoTakedownPopupShow(contentHtml);
        
    } else {
        // The popup already exists, so just change the captcha, message, and styles.
        document.getElementById("vtd_thanks").style.display = "none";
        document.getElementById("vtd_container").style.display = "block";
        document.getElementById("vtd_captcha_img").src = captchaImage;
        document.getElementById("vtd_captcha_key").value = captchaPublicKey;
        document.getElementById("vtd_user_answer").value = "";
        document.getElementById("vtd_message").innerHTML = message;
        document.getElementById("vtd_question1").className = pClass;        
        document.getElementById("vtd_question2").className = pClass;
        
        videoTakedownPopupShow(undefined);
    }
}

function videoTakedownPopupShow(contentHtml) {
    // Generate or redisplay the popup.
    createTrianglePopup('parent_link', 'video_takedown_popup', 232, 12, 400, 377, contentHtml);
}

function videoTakedownAction(captchaPublicKey) {
    // The user must supply something in the reason text and captcha answer boxes. If they don't then automatically fail.
    if (document.getElementById("vtd_reason_select").value == "Please select" || document.getElementById("vtd_user_answer").value == "" || document.getElementById("vtd_reason_text").value == "") {
        videoTakedownFailure(undefined);
    } else {        
        // Otherwise, make the ajax call to validate the captcha answer and takedown the video.
        var url = "ajax/VideoTakedown_Ajax.aspx?ts=" + getEpochTime();
        // Prepare the form for posting.
        YAHOO.util.Connect.setForm('vtd_form');
        var request = YAHOO.util.Connect.asyncRequest('POST', url, { success: videoTakedownSuccess, failure: videoTakedownFailure });
    }
}

function videoTakedownSuccess(response) {
    // Expected response text is 'True||' If the first value isn't true then the captcha hasn't been validated.
    var responseArray = response.responseText.split("|", 3);
    if (responseArray[0] == "True") {
        videoTakedownPopupThanks();
    } else {
        videoTakedownFailure(response)
    }
}

function videoTakedownFailure(response) {
    // Remove and regenerate the video takedown popup.
    closeTriangleTopBox('video_takedown_popup');
    videoTakedownClick('Please complete all parts of this form.');
}

function videoTakedownPopupThanks() {
    closeTriangleTopBox('video_takedown_popup');

    // The popup already exists, so just change the content.
    document.getElementById("vtd_thanks").style.display = "block";
    document.getElementById("vtd_container").style.display = "none";

    videoTakedownPopupShow(undefined);
}

//Holder for the list of fields that need hiding per page in a CSV
var rogueFields="";
var showRogueFields="";     //Empty by default. 'True' to show all rogue fields. 'False' to hide all. Used to handle two popup's in the video section.

/*Misbehaving elements with regard to the Share box*/
function rogueElements(){
	var browser = navigator.appName;
	if(rogueFields){
		//Split out a list of fields to hide
		var aList=rogueFields.split(",");
		
		//Now work through the list
		for (var i=0;i<aList.length;i++){
			showHideElement(aList[i]);
		}
	    showRogueFields = "";
	}
}

function createTrianglePopup(parentId, childId, offsetX, offsetY, widthPx, triangleOffset, contentHtml) {
	//Creates a floating blue bordered box with a link triangle
	//To align right use a negative offsetX    remember to also use a negative triangleOffset
	var cElement=document.getElementById(childId);
	if(!cElement){
	    //First allow for any elements that wont go behind the box
	    showRogueFields = false;
	    rogueElements();

		//Find the point on the page to add the code
		var pElement=document.getElementById(parentId);
		//Create a positioning holding div
		var newHolder=document.createElement("div");
		newHolder.className="triTop_pos_holder";
		newHolder.style.zIndex="1000";
		
		//Create the floating holder
		var newTBox=document.createElement("div");
		newTBox.style.position="absolute";
		newTBox.style.left=offsetX + "px";
		newTBox.style.top=offsetY + "px";
		newTBox.style.zIndex="1010";
		newTBox.id=childId;
		
		//Create the triangle and add it to the floating holder
		var triangle=document.createElement("div");
		triangle.className="triTop_triangle";
		triangle.style.left=triangleOffset + "px";
		triangle.style.zIndex="1015";
		newTBox.appendChild(triangle);
		
		//Create the content holder and add it to the floating holder
		var contentHolder=document.createElement("div");
		contentHolder.id="triTop_content";
		contentHolder.style.width=widthPx + "px";
		contentHolder.style.zIndex="1011";
		contentHolder.innerHTML= contentHtml;
		
		//Create the close link holder
		var closeLinkHolder=document.createElement("div");
		closeLinkHolder.className="triTop_close";
		closeLinkHolder.style.zIndex="1012";

		//Create the close link and add it to the close link holder
		var closeLink=document.createElement("a");
		closeLink.href="javascript:closeTriangleTopBox('" + childId + "');"
		var closeLinkInner=document.createElement("b");
		closeLinkInner.appendChild(document.createTextNode("close x"));
		closeLink.appendChild(closeLinkInner);
		closeLinkHolder.appendChild(closeLink);
		
		//Add the close link holder to the content holder
		contentHolder.appendChild(closeLinkHolder);

		//Add the content holder to the floating holder
		newTBox.appendChild(contentHolder);
		
		//Add the floating holder to the positioning holding div
		newHolder.appendChild(newTBox);

		//Add the positioning holding div to the point on the poge
		pElement.appendChild(newHolder);

	}else{
		//Already exists so just toggle visibilty
		if(cElement.style.display=="none"){
			cElement.style.display="block";
	        showRogueFields = false;
		}else{
			cElement.style.display="none";
	        showRogueFields = true;
		}

	    rogueElements();
	}
} 

/* Floating share/post this popup box */
function createTriangleTopBox(parentId, childId, offsetX, offsetY, widthPx, triangleOffset){
    var contentHtml = createShareThisTable(document.location.href)
    createTrianglePopup(parentId, childId, offsetX, offsetY, widthPx, triangleOffset, contentHtml)
}

function closeTriangleTopBox(id){
    //Re-show any elements that wouldnt go behind the box
    showRogueFields = true;
    rogueElements();

    var bt=document.getElementById(id);
    if (bt != null) {
        //Close the floating blue box
        bt.style.display="none";
    }
}

function createShareThisTable(urlToShare){
	var linkArray = new Array();
	//Set up the link (and icon) array
	linkArray[0]="<a href='http://www.facebook.com/share.php?u=" + urlToShare + "' target='_blank'><img src='/images/shareicons/facebook.gif' alt='Facebook' class='share_icon'> <b>Facebook</b></a>";

	linkArray[1]="<a href='http://www.myspace.com/Modules/PostTo/Pages/?l=2&u=" + urlToShare + "&t=Holiday Lettings' target='_blank'><img src='/images/shareicons/myspace.gif' alt='MySpace' class='share_icon'> <b>MySpace</b></a>";

	linkArray[2]="<a href='http://del.icio.us/post?url=" + urlToShare + "&title=" + urlToShare + "' target='_blank'><img src='/images/shareicons/deli.gif' alt='del.icio.us' class='share_icon'> <b>del.icio.us</b></a>";

	linkArray[3]="<a href='http://www.stumbleupon.com/submit?url=" + urlToShare + "&title=" + urlToShare + "' target='_blank'><img src='/images/shareicons/stubleupon.gif' alt='StumbleUpon' class='share_icon'> <b>StumbleUpon</b></a>";

	linkArray[4]="<a href='http://bookmarks.yahoo.com/toolbar/savebm?opener=tb&u=" + urlToShare + "&t=" + urlToShare + "&d=www.holidaylettings.co.uk' target='_blank'><img src='/images/shareicons/yahoo_bookmarks.gif' alt='Yahoo Bookmarks' class='share_icon'> <b>Yahoo Bookmarks</b></a>";

	linkArray[5]="<a href='http://www.google.com/bookmarks/mark?op=edit&bkmk=" + urlToShare + "&title=" + urlToShare + "' target='_blank'><img src='/images/shareicons/google.gif' alt='Google Bookmarks' class='share_icon'> <b>Google Bookmarks</b></a>";

	linkArray[6]="<a href='https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url=" + urlToShare + "&title=www.holidaylettings.co.uk&top=1' target='_blank'><img src='/images/shareicons/windows_live.gif' alt='Windows Live' class='share_icon'> <b>Windows Live</b></a>";

	linkArray[7]="<a href='http://myweb2.search.yahoo.com/myresults/bookmarklet?u=" + urlToShare + "&t=" + urlToShare + "' target='_blank'><img src='/images/shareicons/yahoo_myweb.gif' alt='Yahoo My Web' class='share_icon'> <b>Yahoo! My Web</b></a>";

	linkArray[8]="<a href='http://friendfeed.com/share?url=" + urlToShare + "&title=" + urlToShare + "' target='_blank'><img src='/images/shareicons/friendfeed.gif' alt='FriendFeed' class='share_icon'> <b>FriendFeed</b></a>"

	linkArray[9]="<a href='http://twitter.com/home/?status=ShareThis+" + urlToShare + "' target='_blank'><img src='/images/shareicons/twitter.gif' alt='twitter' class='share_icon'> <b>Twitter</a>"

	linkArray[10]="<a href='http://favorites.my.aol.com/ffclient/webroot/0.4.3/src/html/addBookmarkDialog.html?url=" + urlToShare + "&title=" + urlToShare + "&favelet=true&description=" + urlToShare + "' target='_blank'><img src='/images/shareicons/myaol.gif' alt='myAOL' class='share_icon'> <b>myAOL</b></a>"
	
	linkArray[11]="<a href='http://www.mister-wong.com/index.php?action=addurl&amp;bm_url=" + urlToShare + " &amp;bm_description=" + urlToShare + "' title='Add this page to Mister Wong' target='_blank'><img src='/images/shareicons/misterwong.gif' alt='Add this page to Mister Wong' border='0' class='share_icon'> <b>Mister Wong</b></a>"
	
	linkArray[12]="<a href='http://digg.com/submit?phase=2&url=" + urlToShare + "&amp;title=www.holidaylettings.co.uk' title='Add this page to Digg' target='_blank'><img src='/images/shareicons/digg.gif' alt='Add this page to Digg' border='0' class='share_icon'> <b>Digg</b></a>"
	
	var temp_text;
	//Setup the return text from the above array in formatted HTML
	tempText="<table>";
	for(var i=0;i<linkArray.length;i++){
		if (i % 2 == 0){
			tempText=tempText+"<tr>";
		} else {
			tempText=tempText+"<td class='space'>&nbsp;</td>";
		}
		tempText=tempText+"<td>" + linkArray[i] + "</td>";
		if (i % 2 != 0){
			tempText=tempText+"</tr>";
		}
	}
	if (i % 2 != 0){
		tempText=tempText+"<td>&nbsp;</td></tr>";
	}
	tempText=tempText+"</table>";
	return tempText;
}


	
function getCurrName(lscurr)  {
	var lsOut;
	switch(lscurr)  {
		case "aud": lsOut = "Australian $"; break;
		case "usd": lsOut = "American $"; break;
		case "eur": lsOut = "Euros &euro;"; break;
		case "gbp": lsOut = "British &pound;"; break;
		case "zar": lsOut = "S. African R";break;
		case "cad": lsOut = "Canadian $";break;
		case "chf": lsOut = "Swiss CHF";break;
	}
	return lsOut;
}

function getCurrName_short(lscurr)  {
	var lsOut;
	switch(lscurr)  {
		case "aud": lsOut = "AUS$"; break;
		case "usd": lsOut = "US$"; break;
		case "eur": lsOut = "EUR&euro;"; break;
		case "gbp": lsOut = "GB&pound;"; break;
		case "zar": lsout = "ZAR"; break;
		case "cad": lsOut = "CA$"; break;
		case "chf": lsOut = "CHF"; break;
	}
	return lsOut;
}


function getCurrSymbol(lscurr)  {
	var lsOut;
	//alert('getCurrSymbol()');
	switch(lscurr)  {
		case "aud": lsOut = "AU$"; break;
		case "usd": lsOut = "$"; break;
		case "eur": lsOut = "&euro;"; break;
		case "gbp": lsOut = "&pound;"; break;
		case "zar": lsOut = "R";break;
		case "cad": lsOut = "CA$";break;
		case "chf": lsOut = "CHF";break;
	}
	return lsOut;
}

function update_ccy(from_ccy, to_ccy){
	//alert('update_ccy');
	//gh_rates["usd"]
	//document.getElementById('new_rate').innerHTML = this_ccy;
	
	//Change the calculated amounts 
	for (var thisgroup = 1; thisgroup <= document.getElementById('num_groups').innerHTML; thisgroup++)  {
		//alert ('getting - group :'+thisgroup);
		for (var i = 0; i <= document.getElementById('num_curr_elements_'+thisgroup).innerHTML; i++)  {
			//Get Amounts
			var myCalc =	document.getElementById('currcalc_'+thisgroup+'_'+i);
			var myCalc_desc = document.getElementById('currcalc_desc_'+thisgroup+'_'+i);
			var mywkend = document.getElementById('c_wkend_'+thisgroup+'_'+i);
			var mywkday = document.getElementById('c_wkday_'+thisgroup+'_'+i);
			
			//alert ('getting - group :'+thisgroup+ '_' + i);
			var myQuoted =	document.getElementById('quoted_'+thisgroup+'_'+i).innerHTML;
			var q_wkend =	document.getElementById('q_wkend_'+thisgroup+'_'+i).innerHTML;
			var q_wkday =	document.getElementById('q_wkday_'+thisgroup+'_'+i).innerHTML;
			
			//alert('MyQuoted=' + myQuoted);
			
			var divisor_rate = gh_rates[from_ccy];
			
			//alert('myquoted=' + myQuoted + ' gh_rates='+gh_rates[to_ccy]);
			myCalc.innerHTML=roundprice(myQuoted/divisor_rate*gh_rates[to_ccy],0);
			
			mywkend.innerHTML=roundprice(q_wkend/divisor_rate*gh_rates[to_ccy],0);
			mywkday.innerHTML=roundprice(q_wkday/divisor_rate*gh_rates[to_ccy],0);
			
			//alert('=='+mywkend.innerHTML);
			//Fix to make pretty and agree with the ASP-generated format
			if (mywkend.innerHTML=='0')  { 	mywkend.innerHTML='-';  }
			if (mywkday.innerHTML=='0')  { 	mywkday.innerHTML='-';  }
			
			myCalc_desc.innerHTML=getCurrSymbol(to_ccy) ;
		}
	}
	
	//Save their currency preference
	save_preferred_ccy(to_ccy);
	return true;
	
}

function save_preferred_ccy(saveccy)  {
	var sURL = 'ajax_functions.asp?action=save_preferred_ccy&save_ccy=' + saveccy + '&ms=' + new Date().getTime()
	var request = YAHOO.util.Connect.asyncRequest('GET', sURL, {success:handleSuccess,failure:handleFailure});
}

function handleFailure(o){ if(o.responseText !== undefined){ alert(o.responseText); } }
function handleSuccess(o) { 
	var response = o.responseText; 
	var update = new Array(); 
	if(response.indexOf('|') != -1) {
		update = response.split('|'); 
		for (i in update)  { 
			if ( (i%3==0) )  { 
				var j=parseInt(i)+1; 
				var k=parseInt(i)+2; 
				if (update[i] == "imgsrc") { 
					document.getElementById(update[j]).src = update[k]; 
				} 
				else if (update[i] == "value") { 
					document.getElementById(update[j]).value = update[k]; 
				} 
				else { 
					document.getElementById(update[j]).innerHTML = update[k];
				}
			}
		}
	} 
}

// Stuff for the co-lo tabs is below here.  This would be better denoted as an object in object literal notation so that it was all
// clearly grouped together.

// A dictionary of the most recently clicked-on tabs for each colo advert on the page. The key is "parent_" + parent home id, 
// and the value is the home_id of the home clicked on (which may be the parent).
var coloTabsLastClicks = {};

// A dictionary of colo homes' display data, i.e. the html to use in a call to updateSRPTableRowContent for a particular home. 
// The key is "home_" + home id.
// The cache is filled for each home via a call to cacheColoTab, which uses srp_colo_ajax.asp to attempt to get the content.
// If an srp_colo_ajax.asp call is in progress to fill the cache but has not yet returned then the dictionary value will be null.
var coloTabsAjaxCache = {};

// This function is called whenever the user clicks on one of the tabs of a colo advert. 
function selectTab(parentId, selectedTab, numberTabs, homeId, tabMode, homeType, childCost, orderBy){
	var bSelected = false;
	var tabEdgeClass;
	var tabContentClass;
	
	//Work through the number of tabs
	for(var i=1;i<=numberTabs;i++){
		//Set the defaults
		bSelected = (i==selectedTab);
		tabEdgeClass = "srp_colo_tab_edge";
		tabContentClass = "srp_colo_tab_content";
		
		if(bSelected){ 
			if(i==1){
				//First tab
				tabEdgeClass += "_first_selected";
			}else{
				//All other tabs
				tabEdgeClass += "_selected";
			}
			// The content background
			tabContentClass += "_selected";
			
			// Change the tab content
			changeSRPTab(parentId, homeId, childCost, orderBy);
			
		} else {
			//Not selected
			if((i-1)==selectedTab){
				//If the previous tab was selected then we need to add
				tabEdgeClass += "_after_selected";
			} else if(i==1){
				//If it is the first tab
				tabEdgeClass += "_first";
			}
		}
		
		//Update the current tab
		document.getElementById("tab_" + parentId + "_" + i).className = tabEdgeClass;
		document.getElementById("content_" + parentId + "_" + i).className = tabContentClass + " " + tabMode;
	}
	
	// Update the Home Type and Home ID in the advert's title row
	document.getElementById("spn_colo_details_" + parentId).innerHTML = homeType + " " + homeId;
	
	//Update the tab line end
	if(bSelected){
		document.getElementById("tab_end_" + parentId).className = "srp_colo_tab_end_after_selected";
	}else{
		document.getElementById("tab_end_" + parentId).className = "srp_colo_tab_end";
	}
}

// This function rebuilds the html for a colo advert. The content is displayed within a table cell of id "tr_colo_advert_" + parentId.
// The function is called from selectTab above.
function changeSRPTab(parentId, homeId, childCost, orderBy) {
    // Store the home as the advert's most recently displayed tab.
    coloTabsLastClicks["parent_" + parentId] = homeId;
    
    var homeKey = "home_" + homeId;
    if (homeKey in coloTabsAjaxCache) {
        if (coloTabsAjaxCache[homeKey] != null) {
            // There is already a cached value for the home so display it immediately.
            updateSRPTableRowContent(parentId, coloTabsAjaxCache[homeKey]);
        } else {
            // The data is currently being loaded so display the loading image and wait.
            updateSRPTableRowLoadingImage(parentId)
        }
    } else {
        // We need to get the data, so display the loading image and make the ajax call.
        updateSRPTableRowLoadingImage(parentId)
        cacheColoTab(parentId, homeId, childCost, orderBy);
    }    
}

// This function fills the entry in coloTabsAjaxCache for the given home id. It will *not* overwrite any value there already.
function cacheColoTab(parentId, homeId, childCost, orderBy) {
    
    var homeKey = "home_" + homeId;
    // Make a final check that the cache is empty in case two asynchronous process try at the same time.
    if (!(homeKey in coloTabsAjaxCache)) {
        // Set a null value first to show that the ajax call is in progress.
        coloTabsAjaxCache[homeKey] = null;
        
        // Make the ajax call to fill the cache with the correct html.
        var url = "/srp_colo_ajax.asp?home_id=" + homeId + "&parent_id=" + parentId + "&child_cost=" + childCost + "&order_by=" + orderBy;
        var request = YAHOO.util.Connect.asyncRequest('GET', url, { 
            success : handleColoTabAjaxResponse, 
            failure : handleColoTabAjaxError,
            argument : { HomeId : homeId, ParentId : parentId }
        });
    }
}

function handleColoTabAjaxResponse(o) {

	// Split the AJAX response into two parts on the delimiter
	var delimiter = "|>delimiter<|";
	var responseParts = o.responseText.split(delimiter, 2);
	var parentId, tableCellHTML;

    var homeKey = "home_" + o.argument.HomeId;
	if (responseParts[0] == "ERROR") {
		coloTabsAjaxCache[homeKey] = "<td>&nbsp; Sorry, there was a problem retrieving the data for that Home.</td>";
	} else {
		coloTabsAjaxCache[homeKey] = responseParts[1];
	}
	
	// If the tab for this home is the most recently clicked-on tab for the advert, display it immediately.
	var parentKey = "parent_" + o.argument.ParentId;
	if (parentKey in coloTabsLastClicks) {
        if (coloTabsLastClicks[parentKey] == o.argument.HomeId) { 
            // Make sure the tab's holding element is visible.
            var trCellElement = document.getElementById("tr_colo_advert_" + o.argument.ParentId);
            trCellElement.style.visibility = "";

            // Remove the advert's loading element.
            var loadingElement = document.getElementById("loading_element_" + o.argument.ParentId);
            loadingElement.parentNode.removeChild(loadingElement);

            updateSRPTableRowContent(o.argument.ParentId, coloTabsAjaxCache[homeKey]);
        }
    }
}

function handleColoTabAjaxError(o) {
	o.responseText = "ERROR";
	handleColoTabAjaxResponse(o);
}

// Displays the given html in the table cell of the given advert.
function updateSRPTableRowContent(parentId, tableCellHTML) {
	// Detect browser type
	if (navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
		
		// It's IE hack time. To be fair, this one comes courtesy of the bloke who
		// invented innerHTML: Eric Vasilik. http://www.ericvasilik.com/2006/07/code-karma.html
		var tableBodyElement = document.getElementById("tr_colo_advert_" + parentId).parentNode;
		var id = tableBodyElement.id.replace('tb', '');
		var tableElement = tableBodyElement.parentNode;
		var tableBodyHTML = tableElement.innerHTML;
		
		// "Replace" the third row of the SRP table with the AJAX response text by grabbing
		// the first two rows and appending the response text onto them.
		var tableBodyNewHTML = tableBodyHTML.substr(0, tableBodyHTML.toLowerCase().lastIndexOf("<tr")) + "<tr id='tr_colo_advert_" + parentId + "'>" + tableCellHTML + "</tr>";
		
		// Use the hidden <span> tag that sits under the SRP table to "hold" our HTML
		var span = document.getElementById("spn_" + id);
		span.innerHTML = "<table border='0' cellspacing='0' cellpadding='0' class='srp3' id='tbl" + id + "'>" + tableBodyNewHTML + "</table>";
		
		// Update the SRP table body HTML using the hidden <span>
		tableElement.replaceChild(span.firstChild.firstChild, tableBodyElement);
		
	} else {
		document.getElementById('tr_colo_advert_' + parentId).innerHTML = tableCellHTML;
	}
}

function updateSRPTableRowLoadingImage(parentId) {	
	var trCell = document.getElementById("tr_colo_advert_" + parentId);
	var trCellPosition = YAHOO.util.Dom.getXY("tr_colo_advert_" + parentId);
	trCell.style.visibility = "hidden";

	var loadingElement = document.getElementById("loading_element_" + parentId);
	if (loadingElement == null) {
	    loadingElement = document.createElement("div");
	    loadingElement.id = "loading_element_" + parentId;
	    loadingElement.style.position = "absolute";
	    loadingElement.innerHTML = "<img src='/images/ajax_busy.gif' alt='Loading...'>";
	    
        var loadingPos = [ trCellPosition[0] + (trCell.clientWidth / 2) - (90 / 2),
                           trCellPosition[1] + (trCell.clientHeight / 2) - (22 / 2) ];
                       
        loadingElement.style.left = loadingPos[0] + 'px';
        loadingElement.style.top = loadingPos[1] + 'px';
        	    
    	trCell.parentNode.appendChild(loadingElement);
	}
}

function preFetchImages(homeIdCsv) {
	// Pre-fetch co-lo images by instantiating a new image object and setting
	// its path for each of the IDs in the given comma-delimited list, thus
	// preloading the image into the cache.
	var image;
	
	// Generate array of co-located Home IDs from given string
	var homeIds = homeIdCsv.split(",");
	
	// Iterate through Home IDs, setting the image object's path
	for (var i = 0; i < homeIds.length; i++) {
		image = new Image();
		image.src = "/picsmall/" + genPicPath(homeIds[i], "1");
	}
}

function genPicPath(homeId, picId) {
	// Generate a path to a Home's picsmall image. Note that the path is a
	// function of the Home's ID, since picsmall subfolders contain images
	// for a maximum of 10,000 homes.
	var path = ( parseInt(homeId / picDivisor) ).toString();
	path += "/" + genPicFile(homeId, picId);
	return path;
}

function genPicFile(homeId, picId) {
	// Generate a picsmall image filename in the format homeId_picId.jpg
	return homeId + "_" + picId + ".jpg";
}


//--------------------------------------------------------------------------------
// Google Maps functions
//--------------------------------------------------------------------------------

var map;

function initialiseGMap() {
	// Initialise and configure the Google Map
	if (GBrowserIsCompatible()) { configureGoogleMap(); }
}

function resetGMap(lat, lng, zoom) {
	// Resets the Google Map's lat, lng and zoom settings and reverts the map
	// type back to the default street map type.
	map.setCenter(new GLatLng(lat, lng), zoom);
	map.setMapType(G_NORMAL_MAP);
}

//--------------------------------------------------------------------------------
// End Google Maps functions
//--------------------------------------------------------------------------------

// generic time stamper method moved from tools_renewals.js as its useful elsewhere
function getEpochTime() {
    var now = new Date();
    return now.getTime();
}

// Read query string value for a given key. Set to default value if key not found
function getQuerystring(key, default_) {
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

// Set affiliate window cookie if the url contains the affiliate window query string parameters
function setAffiliateWindowCookie() {
  var expiry = new Date();  
  expiry.setDate(expiry.getDate() + 30);

  if (getQuerystring("awaid") != "") {

    // Remove Partner cookie if exists
    if (getCookie("aff%5Fid") != "") {
        document.cookie = 'aff%5Fid=;expires=Thu, 01-Jan-70 00:00:01 GMT;path=/';
	}
      
    // Add Affiliate Window Cookie
    document.cookie = 
        "hlaw=" + 
            "AffiliateId=" + getQuerystring("awaid") + 
            "&GroupId=" + getQuerystring("awgid") + 
            "&BannerId=" + getQuerystring("awbid") + 
            "&ProductId=" + getQuerystring("awpid") + 
            "&ClickRef=" + getQuerystring("awcr") +             
            "&ClickDate=" + formatDateTime(new Date()) +
        ";expires=" + expiry +
        ";path=/";
        
  }
}

// Get contents of a cookie by its name 
function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=")
    if (c_start!=-1) { 
        c_start=c_start + c_name.length+1 
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1) c_end=document.cookie.length
        return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
  return ""
}


// Home page search handler functions
function mysubmit() {
	var theform = document.search_form;
	var countryselect = theform.loc_country;
	
	try {
		pageTracker._trackEvent('homepage', 'country-dropdown', countryselect.value);
	} catch(err) {
	}
	
	if (countryselect.options[countryselect.selectedIndex].value != 0) {
		//The user has managed to use the dropdown and click the button, since we are hear js is not disabled therfore slow browser
		theform.method = 'GET';
		if (countryselect.options[countryselect.selectedIndex].getAttribute('hl_sz') == "s") {
			theform.action = "homesearch.asp";
		} else {
			theform.action = "search_easy.asp";
		}
	}
	protectSearchButton(true);
	theform.submit();
	return true;
}

function protectSearchButton(bDisable) {
	var el = document.getElementById("sautSubmit");
	if (el) { el.disabled = bDisable; }
}

// Stop Hiding script -->

	// Maintain a global list of Home IDs for use with AJAX handlers
	var homeIds;

	var carousel;
	var rightNavButton;
	

	
	// YUI Carousel deferred loading
	function getNextCarouselItems() {
		var url, postData, request;
		var homeIdsCsv = document.getElementById("hdn_home_ids").value;
		var nextBatch = homeIdsCsv.split(',', 4);
        
		// If we've found a batch then post a comma-delimited string of
		// home IDs using AJAX and get formatted HTML back in the response.
		if (nextBatch[0] != "") {
			
			// Disable the right-hand navigation button until has have an AJAX response
			rightNavButton.disabled = true;
			
			homeIds = nextBatch;
			url = 'ajax/carousel_ajax.aspx';
			postData = "home_ids=" + nextBatch.join(',') 
			request = YAHOO.util.Connect.asyncRequest('POST', url, {
				success: handleAjaxSuccess,
				failure: handleAjaxFailure
			}, postData);

			// Re-enable the right-hand navigation button
			rightNavButton.disabled = false;
			
		}
	}
	
	// AJAX success handler
	function handleAjaxSuccess(o) {
		var spotlightHtml, homeIdsCsv, hiddenHomeIds
		var html = o.responseText;

		if (html == "Error") {
			handleAjaxFailure();
		} else {
			// The response text is likely to contain HTML for more than one spotlight,
			// so we delimit with "|><|".
			spotlightHtml = html.split("|><|");

			// Iterate the array of HTML we've created and add new carousel items
			for (var i = 0; i < spotlightHtml.length; i++) { carousel.addItem(spotlightHtml[i]); }

			// Remove the Home IDs of newly-added carousel items from the comma-delimited
			// list in the hidden input field.
			homeIdsCsv = homeIds.join(',');
			hiddenHomeIds = document.getElementById("hdn_home_ids").value.replace(homeIdsCsv, "");
			
			// Remove leading comma from hidden field value if necessary
			if (hiddenHomeIds.charAt(0) == ",") { hiddenHomeIds = hiddenHomeIds.substr(1); }
			
			document.getElementById("hdn_home_ids").value = hiddenHomeIds;
		}
	}
	
	// AJAX failure handler
	function handleAjaxFailure() {
		for (var i = 0; i < homeIds.length; i++) {
			var itemHTML = "<div style='width:140px; margin-top:50px;'><a href='/" + homeIds[i] + "'>Spotlight on<br>Home " + homeIds[i] + "</a></div>";
			carousel.addItem(itemHTML);
		}
	}
	
	//
	// expand or collapse the top destinations box 
	var toggleTopDestinations = function() {
	    var module = document.getElementById('top_destinations');
		var image = document.getElementById('show_top_destinations');
		var hidden = (module.style.display == 'none' ? true : false); 
	    if(hidden) {
			module.style.display = 'block';
			image.src = '/images/dk2010/collapse.png'
			image.alt = 'Collapse section'
		} else {
			module.style.display = 'none';
			image.src = '/images/dk2010/expand.png'
			image.alt = 'Expand section'
		}
	}

    //
    // expand or collapse the holiday ideas box
	var toggleHolidayIdeas = function() { 
		var module = document.getElementById('holiday_ideas');
		var image = document.getElementById('show_holiday_ideas');
		var hidden = (module.style.display == 'none' ? true : false); 
	    if(hidden) {
			module.style.display = 'block';
			image.src = '/images/dk2010/collapse.png'
			image.alt = 'Collapse section'
		} else {
			module.style.display = 'none';
			image.src = '/images/dk2010/expand.png'
			image.alt = 'Expand section'
		}
	}

    //
    // expand or collapse the about holiday lettings box
	var toggleAboutHolidayLettings = function() { 
		var module = document.getElementById('about_holiday_lettings');
		var image = document.getElementById('show_about_holiday_lettings');
		var hidden = (module.style.display == 'none' ? true : false); 
	    if(hidden) {
			module.style.display = 'block';
			image.src = '/images/dk2010/collapse.png'
			image.alt = 'Collapse section'
		} else {
			module.style.display = 'none';
			image.src = '/images/dk2010/expand.png'
			image.alt = 'Expand section'
		}
	}

	
	