﻿<!-- Start hiding script
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PLEASE NOTE:
// $(function(){ }); is a jQuery shorthand for document ready. Place all such generic scripts at the top of this file

if (typeof jQuery != 'undefined') { 
	// advertdisplay.aspx
	$(function() {
		if($("#sideTabs").length!=0){
			// Add the link to the whole of the tab. (Can't put a div inside an <a> and <span> doesn't hold its height for background)
			$(".tab").bind("click", function(){
			    var pageLink = $(this).children(".tab_back").children("a").attr("href");
				if(pageLink!=undefined){ document.location.href= pageLink; }
			});
			
			// IE before 9 then sort the background by using an image
			if ($.browser.msie && parseInt($.browser.version)<9) {
				$(".tab").css("background","url(/images/tab-back-nonselected.jpg) repeat-y top right");
				$(".tab.selected").css("background","url(/images/tab-back-selected.jpg) repeat-y top right");
			}
		}
		
		// Add the ribbon functionality
		$(".scrolling-link").bind("click", function(e) {
			e.preventDefault();
			var hrefArray = $(this).attr("href").split("#");
			if(hrefArray.length>0){
				var el = "#" + hrefArray[1];
				$('html,body').animate({scrollTop: $(el).offset().top},'slow', function(){
					if(el == "#Contact" && $("#fname").length>0){
						$("#fname").focus();
					}
				});
			}
		});
		
		// Create the top id to scroll to the very top of the page if the ribbon scrolling link is present
		if($(".scrolling-link").length>0){
			$("<div id='Top'></div>").prependTo("body");
		}
		
		function goToByScroll(id){
			$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
			$('html,body').animate({scrollLeft: $("#"+id).offset().left},'slow');
		}
		
		
		// All pages
		setSeeds();
		
		// Hide the html button border in IE to prevent the nasty black selected indicator
		if($.browser.msie) {
			$(".hl_button").css("border-width", "0px");
		}
	});

	//JQuery light box functionality
	$(function() {
	 
        function centre(element) {
            
                var winH = $(top.window).height();
                var winW = $(top.window).width();
                var contentH = $(element, top.document).height();
                var contentW = $(element, top.document).width();
                var verticalTopPosition = $(top.document).scrollTop() + winH / 2 - contentH / 2;

                //Make sure the top of the box is on the screen
                if (verticalTopPosition < ($(top.document).scrollTop() + 20)) {
                    verticalTopPosition = ($(top.document).scrollTop() + 30);
                }

                //Set the popup window to center
                $(element, top.document).css('top', verticalTopPosition);
                $(element, top.document).css('left', winW / 2 - contentW / 2);
        }

	    $(window).bind('resize', function() {

            var lightbox = $('div.modalWindow');
            if (lightbox != null) {
                centre(lightbox);
			    var maskHeight = $(top.document).height();
			    var maskWidth = $(top.window).width();
		
			    // Set heigth and width to mask to fill up the whole screen
			    $(".modalMask", top.document).css({'width':maskWidth,'height':maskHeight});            }
	    });
	    
        //Select all the 'a' tags with name='modal'
		$('a[name=modal]').click(function(e) {
			//Cancel the link behavior
			e.preventDefault();
			
			//Set up the element ids
            var url = $(this).attr('data-url');
		    if (url == null || url == "") {
		        url = $(this).attr('href');
		    }
		    var baseId = $(this).attr('id');
			var allowMulti = $(this).attr('multi') == 'true';
			var contentId = "content_" + baseId;
			var contentEl = "#" + contentId;
			
			//See if the content box has been provided
			if($(contentEl).length==0){
				var toAdd = "<div id='" + contentId + "' class='modalWindow'></div>";
				//See if the mask is needed
				if($("#modalBoxes").length==0){
					$("body",top.document).append("<div id='modalBoxes'>" + toAdd + "<iframe class='modalMask' style='background-color:transparent;border:0px;'></iframe><div class='modalMask' id='modalMask'></div></div>");
				}else {
					$("#modalBoxes",top.document).append(toAdd);
				}
			}
			
			//Fetch the content
			$.ajax({
				url: url,
				data: "display=modal",
				async: false,
				cache: false,
				success: function(data){ $(contentEl, top.document).html(data); },
				error: function() {
						$(contentEl).append("<div class='modalError'>Sorry, we've had a problem! Please contact us with details of when you saw this message.</div>");
					}
			});
			
			//Add the form post binding
			handleFormPost(contentEl,contentId);
			
			//Get the screen height and width
			var maskHeight = $(top.document).height();
			var maskWidth = $(top.window).width();
		
			if (!allowMulti) {
				//Set heigth and width to mask to fill up the whole screen
				$(".modalMask", top.document).css({'width':maskWidth,'height':maskHeight});
			
				//transition effect	
				$(".modalMask", top.document).fadeTo('fast',0.7);			
				$(".modalMask", top.document).fadeIn('fast');				
			}

			//Centre the modal window and mask
		    centre(contentEl);
			
			//transition effect
			$(contentEl, top.document).fadeIn('fast'); 

			//if mask is clicked or close button clicked
			$(".modalMask", top.document).click(function () {	closeModal(allowMulti); });
			
			//Add the close button
			closeButton(contentEl,contentId);
			
			//Add the resize functionality
			if($(this).attr("resize")=="true"){
				$(contentEl, top.document).resizable();
			}
			
			//Add the move button
			if(allowMulti){
				moveButton(contentEl,contentId);
				$(contentEl, top.document).draggable({ addClasses: false, cursor: 'move', handle: '#move_' + contentId, scrollSensitivity: 100 });				
			}			

			function handleFormPost(contentEl,contentId){
				$(contentEl + " form", top.document).bind('submit',function(e){
						e.preventDefault();
						var actionUrl = $(this).attr("action");
						if (actionUrl == null || actionUrl.length == 0) { actionUrl=url; }
						actionUrl += ((actionUrl.indexOf("?")==-1) ? "?":"&") + "display=modal";
						$.ajax({
							type: "POST",
							url: actionUrl,
							data: $(this).serialize(),
							async: false,
							success: function(data){ 
									$(contentEl, top.document).html(data);
									closeButton(contentEl,contentId);
									handleFormPost(contentEl,contentId);
								},
							error: function(){ $(contentEl, top.document).append("<div class='modalError'>Sorry there has been a problem loading content</div>"); }
						});					
				});			
			}
			
			function closeButton(contentEl,contentId){
				if($("#close_" + contentId, top.document).length==0){
					$(contentEl, top.document).append("<a href='#' class='closemodal closebutton' id='close_" + contentId + "'><img src='/images/tripadvisor/blue-cross.png'></a>");
				}
				$(".closebutton", top.document).click(function(e) { e.preventDefault(); closeModal(); });	
			}
			
			function moveButton(contentEl,contentId){
				if($("#move_" + contentId, top.document).length==0){
					$(contentEl, top.document).append("<div class='movemodal' id='move_" + contentId + "'></div>");
				}
			}
			
			function closeModal(){
				//Fade out and clear content
				if (!allowMulti) {
					$('.modalWindow', top.document).fadeOut('fast');
					$('.modalMask', top.document).fadeOut('fast', function(){ $(contentEl).remove();	});	
				} else { 
					$(contentEl, top.document).fadeOut('fast', function(){ $(contentEl).remove();	});	
				}
			}
		});
	});

};

// All $(function(){ ... } document ready functions above this point please
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Extend the jQuery library to have a scrollContent element.
// To use: 
//   create a div with a class of "scroll_holder"
//   put your content in div's with a class of "content" 
//   custom attribute of  data-auto="3000"   would set it to auto rotate moving slide every 3000 milliseconds
//   There is a onLoad function that will do the rest for you
if (typeof jQuery != 'undefined') { 
	$(function() {
		jQuery.fn.scrollContent = function () {
			var el = $(this);
			var autoMilliseconds = parseInt(el.attr("data-auto"));
			var autoPause = true;
			var elId = $(this).attr("id");
			var numContent = 0;
			var currentPos = 1;
			var moving = false;

			// Create all needed for scroller
			addControls();

			// Start the auto scrolling
			if (el.attr("data-auto") != null) {
				autoPause = false;
				var startTimer = setTimeout(function () {
					autoProgress();
				}, autoMilliseconds);
			}

			// Continuous loop
			function autoProgress() {
				if (!autoPause) {
					currentPos++;
					if (currentPos > numContent) { currentPos = 1; }
					moveScrollWindow();
					var timer = setTimeout(function () {
						autoProgress();
					}, autoMilliseconds);
				}
			}

			// Set up the controls and binding
			function addControls() {
				var titleBar = $("#" + el.parent().attr("id") + " .scroll_title");
				var navButtons = "<div class='scroll_navigation_holder' id='scroll_nav_" + elId + "'>";
				if(titleBar.attr("data-prev")){
					navButtons += "<span id='" + elId + "_previous'>" + titleBar.attr("data-prev") + "</span>";
				} else {
					navButtons += "<img src='/images/move_left_disabled.png' alt='Previous' id='" + elId + "_previous' />";
				}
				
				navButtons += "<span>|</span>";
				
				if(titleBar.attr("data-next")){
					navButtons += "<span id='" + elId + "_next' class='active'>" + titleBar.attr("data-next") + "</span>";
				} else {
					navButtons += "<img src='/images/move_right.png' alt='Next' id='" + elId + "_next' class='active' />";
				}		
				
				navButtons +=	 "</div>";
				$(navButtons).appendTo(titleBar);

				el.children(".content").each(function () {
					numContent++;
					$(this).attr("id", elId + "_content_" + numContent);
				});

				$("#" + elId + "_previous").bind("click", function () {
					_gaq.push(['_trackEvent','wcu',elId,'prev']);
					autoPause = true;
					currentPos--;
					moveScrollWindow();
				});
				$("#" + elId + "_next").bind("click", function () {
					_gaq.push(['_trackEvent','wcu',elId,'next']);
					autoPause = true;
					currentPos++;
					moveScrollWindow();
				});
			}

			// Work out the new content id and set the nav arrows state
			function moveScrollWindow() {
				if (!moving) {
					if (currentPos < 1) {
						currentPos = 1;
					}
					if (currentPos > numContent) {
						currentPos = numContent;
					}

					if (currentPos == 1) {
						$("#" + elId + "_previous").attr("src", "/images/move_left_disabled.png").removeClass("active");
					} else {
						$("#" + elId + "_previous").attr("src", "/images/move_left.png").addClass("active");
					}

					if (currentPos == numContent) {
						$("#" + elId + "_next").attr("src", "/images/move_right_disabled.png").removeClass("active");
					} else {
						$("#" + elId + "_next").attr("src", "/images/move_right.png").addClass("active");
					}

					scrollHorizTo("#" + elId + "_content_" + currentPos);
				}
			};

			// Move to the new id
			function scrollHorizTo(id) {
				moving = true;
				var parentId = $(id).parent();
				var newLeft = $(parentId).offset().left - $(id).offset().left + $(id).padding().left;
				$(parentId).animate({ left: newLeft }, 300, function () { moving = false; });
			}
		};
	});
	
	// Calculate the margin of an element
	jQuery.fn.margin = function () {
		var marginTop = this.outerHeight(true) - this.outerHeight();
		var marginLeft = this.outerWidth(true) - this.outerWidth();

		return {
			top: marginTop,
			left: marginLeft
		};
	};

	// Calculate the padding of an element
	jQuery.fn.padding = function () {
		var paddingTop = this.outerHeight(true) - this.innerHeight();
		var paddingLeft = this.outerWidth(true) - this.innerWidth();

		return {
			top: paddingTop,
			left: paddingLeft
		};
	};	
}





// Opens a normal browser window and brings it to the front.
function openWindowToFront(url, target) {
    var windowFeatures = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes";
    var newWindow = window.open(url, target, windowFeatures);
    newWindow.focus();
}

// Expand/collapsible accordion page functions. 
// These are not as generic as they might be. Really, this is all specific to the account details page, but there's definitely room for improvement.
function toggleCollapse(blockName) {
	var	block = document.getElementById(blockName);
	if (block) {
		if (block.style.display == 'none') {
			block.style.display = 'block';
		} else {
			block.style.display = 'none';
		}
	}
}


function changeCollapsedState(block, setExpanded) {
    var image = YAHOO.util.Dom.get('head_' + block.id).getElementsByTagName("img")[0]; 
	if (block) {
	    if (setExpanded) {
	        expandBlock(block, image);
	    } else {
	        collapseBlock(block, image);
	    }
	}
}

function expandBlock(content, image) {
        content.className = 'collapsible2010exp';
		image.src = '/images/dk2010/collapse.png'
		image.alt = 'Collapse section'
}

function collapseBlock(content, image) {

    //
    //  check to see if the content being passed in contains a form that needs checking to see if its dirty
    var element = YAHOO.util.Dom.get(content.id);	    	    
    
    // 
    //  get all the elements in the dom that have the special check_dirty class name so we know that we have to 
    //  check the dirty state of the form within the content being passed in
    var elements = YAHOO.util.Dom.getElementsByClassName( 'check_dirty', 'form' );
    
    //
    //  allow the form to collapse by default
    var hide = true;
    if(elements !== null && elements !== undefined && elements.length > 0) {
        //
        //  iterate through all the forms that have been flagged to be checked for dirty looking for the one that lives
        //  inside the content div that is being passed into this function 
        for(var i = 0; i < elements.length; i++) {
            if(elements[i].parentNode) {
                var parent = elements[i].parentNode;
                if(parent) {
                    var grandParent = parent.parentNode;
                    if(grandParent) {
                        if(grandParent.id == content.id) {
                            //
                            //  this is the form that needs to be checked
                            hide = confirmUserWantsToAbandonChanges(elements[i].id);
                            break;               
                        }
                    }
                }
            }
        }
    }
	
    if(hide) {
        content.className = 'collapsible2010col';
	    image.src = '/images/dk2010/expand.png'
	    image.alt = 'Expand section'
    }
}

// Callback function used by the design kit's collapsable block. 
// Expected to be called by an event listener on the block's header's click event, and passed the block's content div as a callback parameter.
function dk2010ToggleCollapse(e, content) {
    // Determine whether the content div is currently collpased or expanded.
    var collapsed = (content.className == 'collapsible2010col' ? true : false); 
    // Get a handle to the collapsed/expanded image within the header h2.
    var image = this.getElementsByTagName("img")[0];   
    
    if (collapsed) {
	    expandBlock(content, image);	
	} else {
        collapseBlock(content, image);
	}
}

function collapseFaqAnswer(e, content) {
	// Collapses (empties) the active FAQ answer when the corresponding
	// FAQ section is collapsed.
	var answerDiv = content.id.replace("faq", "faqa");
	if (YAHOO.util.Dom.get(answerDiv)) { YAHOO.util.Dom.get(answerDiv).innerHTML = ''; }
	
	// Remove any link highlighting
	var answersHolder = document.getElementById(content.id + "_answers");
	
	// Get a list of all answers for this category, i.e. children of the
	// holder div.
	var arrAnswers = answersHolder.childNodes;
	
	// Iterate the answers and remove the highlight for all except the
	// currently selected question.
	for (var i = 0; i < arrAnswers.length; i++) {
		var linkId = arrAnswers[i].id.replace('a', 'q');
		document.getElementById(linkId).style.color = '#797979';
	}
}

function makeQuestionActive(element) {
	// Makes the current selected question more prominent than the other
	// question links in the same collapsible block.
	
	// Highlight the selected question
	element.style.color = '#000000';
	
	// Remove highlighting from previously selected questions. Locate
	// the div element which contains the list of answers for the current
	// FAQ category and create an array of its child nodes.
	var answerDiv = document.getElementById(element.id.replace('q', 'a'));
	
	// Get a list of all answers for this category, i.e. children of the
	// holder div.
	var arrAnswers = answerDiv.parentNode.childNodes;
	
	// Iterate the answers and remove the highlight for all except the
	// currently selected question.
	for (var i = 0; i < arrAnswers.length; i++) {
		var linkId = arrAnswers[i].id.replace('a', 'q');
		if (linkId != element.id) { document.getElementById(linkId).style.color = '#797979'; }
	}
}

//  function that will prompt the user to make a desicion about the form they have just tried to minimise:
//      just minify the form if no changes to the form have been made
//      reset the form then minify if changes have been made but the user doesnt want to keep them
//      keep everything just how it is so they can carry on clicking, pushing and typing
function confirmUserWantsToAbandonChanges(formName) {
    var form = YAHOO.util.Dom.get(formName);
    var userHasMadeChangesToTheForm = isFormDirty(form);
    if (userHasMadeChangesToTheForm) {
        if (confirm('You have unsaved changes on this form. Please click "OK" to minimise this form and lose your changes or click  "CANCEL" to leave the form open and continue with your changes')) {            
            resetDirtyForm(form);
            return true;
        } else {            
            return false;
        }
    } else {
        return true;
    }
}

//
//  function that when passed a form will check all the elements to see if the user or the dom has changed anything therefore making the form dirty. 
//  
//  to be used when you want to inform the user that they have made changes to a form and are they sure they want to to cancel or if you want to autosave changes.
//  am not checking for password fields as firefox and other browsers will autofill these and always make the form dirty || type === 'password' was removed next to textarea
function isFormDirty(form) {        
    if(form === null || form === undefined) {return false;}
    for (var i = 0; i < form.elements.length; i++){
        var element = form.elements[i];
        var id = element.id;
        var type = element.type;
        var before = '';
        var after = '';
        if (type == 'checkbox' || type == 'radio') {            
            before = element.defaultChecked;
            after = element.checked;            
            if(after != before) {                
                return true;
            }
        } else if (type == 'hidden' || type == 'text' || type == 'textarea') {            
            before = element.defaultValue;
            after = element.value;            
            if(after != before) {                
                return true;
            }            
        } else if (type == 'select-one' || type == 'select-multiple') {
            for (var j = 0; j < element.options.length; j++) {                
                before = element.options[j].defaultSelected;
                after = element.options[j].selected;                
                if (after != before) {                
                    if(before == false && element.selectedIndex == 0) {                        
                        continue;
                    } else {                        
                        return true;
                    }
                }
            }
        }
    }        
    return false;
}

//
//  function to reset a forms values to the their original states and values
function resetDirtyForm(form) {
    if(form === null || form === undefined) {return false;}
    for (var i = 0; i < form.elements.length; i++){
        var element = form.elements[i];
        var id = element.id;
        var type = element.type;
        var before = '';
        var after = '';
        if (type == 'checkbox' || type == 'radio') {            
            before = element.defaultChecked;
            after = element.checked;            
            if(after != before) {
                element.checked = before;
            }
        } else if (type == 'hidden' || type == 'text' || type == 'textarea') {            
            before = element.defaultValue;
            after = element.value;            
            if(after != before) {
                element.value = before;                
            }            
        } else if (type == 'select-one' || type == 'select-multiple') {
            for (var j = 0; j < element.options.length; j++) {                
                before = element.options[j].defaultSelected;
                after = element.options[j].selected;                
                if (after != before) {                
                    if(before == false && element.selectedIndex == 0) {                        
                        continue;
                    } else {
                        element.options[j].selected = before;                        
                    }
                }
            }
        }
    }        
    return false;
}



/* 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;

/* 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("/");
	var mainImage;
	if (test[0]=="show"){		
		mainImage = document.getElementById('bigPic_'+rhid[1]);
		mainImage.src = "/picsmall/"+test[1];	
	}
	if (test[0]=="hide"){
		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
}

var allowEnquirySubmit = false;

if (typeof jQuery != 'undefined') { 
	$(function() {
		$.fn.flashToError = function() {
			this.stop().css("background-color", "#ffffff").animate({backgroundColor: "#ffb2b2"}, 1500);
			return this;
		};
	});
}

/* Takes enquiry form data format and converts into a yyyy-MM-dd format date - or empty string for no date */
function toDateString(input) {
	if (input.length != 10) { return ""; }
	if (input == "dd/mm/yyyy") { return ""; }

	var components = input.split("/");
	if (components.length != 3) { return ""; }

	return components[2] + "-" + components[1] + "-" + components[0];
}

/* Advert page on-page enquiry validation */
function testEnquiryData(homeId) {
	if (allowEnquirySubmit) { return true; }

	// Only fill out the bits that actually need validation (so tel / guest # can be skipped)
	var overrideTypo = ($("#override_typo").val().length > 0),
		overrideBooked = $("#override_booked").is(':checked'),
		termsAccepted = $("#terms_tick").is(':checked'),
		request = "{ 'request' : " +
		"{ 'HomeId' : " + homeId + ", " +
		"'FromFirstName' : '" + $("#fname").val() + "', " +
		"'FromLastName' : '" + $("#lname").val() + "', " +
		"'FromEmail' : '" + $("#from_email").val() + "', " +
		"'ArrivalDate' : '" + toDateString($("#arrival_dt").val()) + "', " +
		"'DepartureDate' : '" + toDateString($("#departure_dt").val()) + "', " +
		"'Message' : '" + $("#main_message").val() + "', " +
		"'AttemptBookedDatesOverride' : " + overrideBooked + ", " +
		"'OverrideTypoCheck' : " + overrideTypo + ", " +
		"'TermsAccepted' : " + termsAccepted + " } }";
	
	$.ajax({
		type: "POST",
		url: "/services/json/enquiries.asmx/TestEnquiry",
		data: request,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: enquiryTestSuccess,
		error: enquiryTestError
	});

	$("#email_button input").toggle();
	$("#email_button img").toggle();

	return false;
}

function enquiryTestSuccess(msg) {
	if (msg.d == "OK") {
		allowEnquirySubmit = true;
		$("#contact_advertiser_form").submit();
	} else {
		clearContactFormErrors();

		var results = jQuery.parseJSON(msg.d),
			errors = new Array();
		
		// The indices used in the error messages are the zero-based positions of the data in the form - e.g. First name is the first item in the form
		// so errors with it are put into errors[0]. We're doing this so that the errors that come back from the API (which can be in any order) are
		// displayed in the order they are in the form - and without requiring the API to know about the form order.

		for (var i = 0; i < results.length; i++) {

			switch(results[i].Code) {
				case ERR_NO_EMAIL:
					errors[2] = "<li>E-mail is required</li>";
					highlightForError("#from_email");
					break;

				case ERR_NO_NAME:
					errors[0] = "<li>First name is required</li>";
					errors[1] = "<li>Last name is required</li>";
					highlightForError("#fname");
					highlightForError("#lname");
					break;

				case ERR_NO_FNAME:
					errors[0] = "<li>First name is required</li>";
					highlightForError("#fname");
					break;

				case ERR_NO_LNAME:
					errors[1] = "<li>Last name is required</li>";
					highlightForError("#lname");
					break;

				case ERR_EMAIL_INVALID:
					errors[2] = "<li>E-mail is required</li>";
					highlightForError("#from_email");
					break;

				case ERR_NO_MESSAGE:
					errors[8] = "<li>A message is required</li>";
					highlightForError("#main_message");
					break;

				case ERR_STARTS_IN_PAST:
					errors[4] = "<li>Arrival date is in the past</li>";
					highlightForError("#arrival_dt");
					break;

				case ERR_EMAIL_TYPO:
					errors[2] = "<li>E-mail address contains a common mistake - please review</li>";
					highlightForError("#from_email");
					$("#typo_suggestion").html(results[i].Message);
					$("#typo_info").show("slow");
					break;

				case ERR_DATES_BOOKED:
					errors[4] = "<li>Dates are booked - please check dates</li>";
					highlightForError("#arrival_dt");
					highlightForError("#departure_dt");
					$("#booked_dates").show("slow");
					break;

				case ERR_DATES_INVERTED:
					errors[4] = "<li>Departure date is before arrival date - please correct</li>";
					highlightForError("#arrival_dt");
					highlightForError("#departure_dt");
					break;

				case ERR_TERMS_NOT_ACCEPTED:
					errors[10] = "<li>T&Cs need to be accepted</li>";
					$("#terms_label").css('font-weight', 'bold').css('color', '#000');
					break;

				default:
					// TODO : build reporting system so that we get notifications of this unexpected error
			}
		}

		$("#advert_contact_error").html("Please check the following errors: <ul>" + errors.join("") + "</ul>").show("slow");
		
	}
}

function highlightForError(selector) {
	$(selector).css('border', '1px inset #f0f0f0').css('padding', '4px').flashToError();
}

function clearContactFormErrors() {
	$("#email_button input").toggle();
	$("#email_button img").toggle();
	$(".contact_form_table input").css('border-width', '0').css('padding', '5px').css("background-color", "#ffffff");
	$("#main_message").css('border-width', '0').css('padding', '5px').css("background-color", "#ffffff");
}

function contactFormTakeSuggestion() {
	$("#from_email").val($("#typo_suggestion").text());
	$("#typo_info").hide("slow");
}

function contactFormRejectSuggestion() {
	$("#override_typo").val("true");
	$("#typo_info").hide("slow");
}


function enquiryTestError(request, status, error) {
	// Just forward the user on and let the classic ASP page handle this!
	allowEnquirySubmit = true;
	$("#contact_advertiser_form").submit();
}

/* Functions relating to displaying reviews via an ajax request */
function displayReviews(page) {
	$("[id^='page_']").hide();
	$("#page_" + page).show();
}

// Show full review when the 'more' link is clicked when the review source is TA.
function showFullReview(homeId, reviewId) {
    var url = "/ajax/display_reviews_ajax.aspx";
	$.ajax({
		url: url,
		data: "home_id=" + homeId + "&review_id=" + reviewId + "&ts=" + getEpochTime(),
		async: false,
		success: function(data){ 
			$("#review_row_" + reviewId).replaceWith(data); },
		error: function(){ 
			//nothing
		}
	});
}

function fetchAllReviews(homeId, startAtPage){
    var url = "/ajax/display_reviews_ajax.aspx";
	$.ajax({
		url: url,
		data: "home_id=" + homeId + "&fetch_all=" + startAtPage + "&ts=" + getEpochTime(),
		async: false,
		success: function(data){ 
			$("#reviews_home").html(data); },
		error: function(){ 
			//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 advert page - called from hd_functions */
function videoSharePopupShow() {    
    var contentHtml = createShareThisTable(document.location.href);
    createTrianglePopup('parent_link', 'video_share_popup', -10, 17, 310, 5, contentHtml);
}

/* Functions relating to the video takedown popup on 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', -95, 17, 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 restrictChars(obj, maxchar) 
{     
    if(this.id) obj = this; 
        
    var remainingChar = maxchar - obj.value.length; 
    
    if(remainingChar <= 0) 
    { 
        obj.value = obj.value.substring(maxchar,0); 
        obj.style.bgColor = "#ffb2b2";
        obj.style.backgroundColor = "#ffb2b2";
        return false; 
    } 
    else 
    {
        obj.style.bgColor = "#fff";
        obj.style.backgroundColor = "#fff";
        return true;
    } 
} 
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;
}

//Form Seeding start
	//Handle the seeding when entering or leaving an input
	function formSeed(el, bFocus){
		txt = el.attr("seedTxt");
		if(txt!=undefined && txt!=null){
			if(bFocus){
				if(el.val()==txt){ el.val("").css("color","#000"); }
			}else{
				if(el.val()==""){ el.val(txt).css("color","#666"); } else { el.css("color","#000"); }
			}
		}
	}
	
	//Set the seed values for all inputs
	function setSeeds(){
		$("[seedTxt]").bind("focus", function(){ 
						formSeed($(this),true); 
					}).bind("blur", function(){ 
						formSeed($(this),false); 
					}).each(function(){ 
						formSeed($(this),false);
					});

		//Set up the listeners for the submission of the form to clear the seeds when form is submitted
		$("form").bind("submit", function() { unSetSeeds(); });
	}

	//Clear all the seed values for all inputs
	function unSetSeeds(){
		$("[seedTxt]").each(function(){ formSeed($(this),true); });	
	}
//Form Seeding end

if (typeof(YAHOO) != "undefined") {
	YAHOO.util.Event.onDOMReady(function() {
		var elem = document.getElementById('femLocationInput');
		if(elem){
			elem.removeAttribute("name");
		}
	})
}              

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;
		case "thb": lsOut = "Thai &#3647; ";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;
		case "thb": lsOut = "TH&#3647; "; 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;
		case "thb": lsOut = "&#3647;";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 = {};
var coloTabsUrlAjaxCache = {};

// 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, reviewRating, reviewCount){
	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 + "<br>" + homeId;
	
	// Update the review details in the advert's title row
	if (document.getElementById("td_colo_reviews_" + parentId)) {
		if (reviewRating > -1 && reviewCount > 0) {	
			document.getElementById("td_colo_reviews_" + parentId).style.visibility = "visible";

			if (document.getElementById("spn_colo_review_rating_" + parentId)) {
				document.getElementById("spn_colo_review_rating_" + parentId).className = "review_rating r" + reviewRating * 10;
				document.getElementById("img_colo_review_rating_" + parentId).alt = reviewRating + " out of 5";
				document.getElementById("img_colo_review_rating_" + parentId).title = reviewRating + " out of 5";
				document.getElementById("link_colo_review_count_" + parentId).innerHTML = "(" + reviewCount + ")";
			}
		} else {
			document.getElementById("td_colo_reviews_" + parentId).style.visibility = "hidden";
		}
	}

	//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 && coloTabsUrlAjaxCache[homeKey] != null) {
            // There is already a cached value for the home so display it immediately.
            updateSRPTableRowContent(parentId, coloTabsAjaxCache[homeKey], coloTabsUrlAjaxCache[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) || !(homeKey in coloTabsUrlAjaxCache)) {
        // Set a null value first to show that the ajax call is in progress.
        coloTabsAjaxCache[homeKey] = null;
		coloTabsUrlAjaxCache[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 three parts on the delimiter
	var delimiter = "|>delimiter<|";
	var responseParts = o.responseText.split(delimiter, 3);
	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];
		coloTabsUrlAjaxCache[homeKey] = responseParts[2];
	}
	
	// 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], coloTabsUrlAjaxCache[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, homeUrl) {
	// 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;
	}

	// Update the link for the advert title.
	document.getElementById("lnk_colo_details_" + parentId).href = homeUrl;
	if (document.getElementById("link_colo_review_count_" + parentId)) {
		document.getElementById("link_colo_review_count_" + parentId).href = homeUrl + "#reviews_home";	
	}
	
}

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
	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 google.maps.LatLng(lat, lng));
    map.setZoom(zoom);
}

//--------------------------------------------------------------------------------
// 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(isAWParallel) {
  var expiry = new Date();  
  expiry.setDate(expiry.getDate() + 30);

  if (getQuerystring("awaid") != "") {

    // Remove Partner cookie if exists
    if (getCookie("aff%5Fid") != "" && !isAWParallel) {
        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 {
		track("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);
		}
	}
	

function ppeEnquiryValueCalculate(){
	var bands = new Array();
	bands[0] = "High";
	bands[1] = "Medium";
	bands[2] = "Low";
    var weeklyPrice = parseFloat(document.getElementById('max_rate_price').value);
    var expectedNumEnq = parseFloat(document.getElementById("exp_enquiries").value);
    var conversionRate = parseFloat(document.getElementById("conversion_rate").value) / 100;
    var pmCommissionRate = parseFloat(document.getElementById("commission_rate").value) / 100;
	var enquiryBand = "Low";
	
	//Find out which hidden band value to use with the calculations
	for (var x = 0; x <= bands.length -1; x++){
		if (parseInt(weeklyPrice) >= document.getElementById(bands[x]).value){
			enquiryBand = bands[x] + "_rate";
			break;
		}
	}
	
    document.getElementById("profit_per_lead").value = roundNumber(weeklyPrice * conversionRate * pmCommissionRate, 2);
	document.getElementById("proposed_price_per_lead").value = document.getElementById(enquiryBand).value;
	document.getElementById("roi").value = roundNumber(parseFloat(((document.getElementById("profit_per_lead").value) / parseFloat(document.getElementById("proposed_price_per_lead").value) -1) * 100, 2), 2);
	
	document.getElementById("conversion_rate_span").value = roundNumber(conversionRate * 100, 2);
	document.getElementById("average_num_bookings").value = roundNumber(conversionRate * expectedNumEnq, 1);
	document.getElementById("revenue_gend").value = roundNumber(parseFloat(document.getElementById("average_num_bookings").value, 2) * weeklyPrice, 2);
	document.getElementById("pm_commission_rate_span").value = roundNumber(pmCommissionRate * 100, 2);
	//document.getElementById("commission_earned").value = roundNumber(parseFloat(document.getElementById("revenue_gend").value) * pmCommissionRate, 2);
	document.getElementById("commission_earned").value = roundNumber(weeklyPrice * expectedNumEnq * conversionRate * pmCommissionRate, 0);
	document.getElementById("cost_of_enquiries").value = roundNumber(expectedNumEnq * parseInt(document.getElementById("proposed_price_per_lead").value), 2);
	document.getElementById("profit_earned_roi").value = roundNumber(((parseFloat(document.getElementById("commission_earned").value) - parseFloat(document.getElementById("cost_of_enquiries").value)) / parseFloat(document.getElementById("cost_of_enquiries").value)) * 100, 2);
}

function moreInfo(lsName, iWidth){
	if(iWidth==null){ iWidth=620; }
	var x = YAHOO.namespace(lsName);
	if(YAHOO.util.Dom.get(lsName)!=null){
		if(x.dialog==null){
			x.dialog = new YAHOO.widget.Dialog(lsName,
			{ width: iWidth + "px", fixedcenter: true, visible: false, draggable: false, modal: true, close: false, constraintoviewport: false, underlay: "shadow", zIndex:305, hideaftersubmit: false });
			x.dialog.render();
			document.getElementById(lsName).style.display="block";
		}
	}
	x.dialog.show();
}

function closeInfo(lsName) {
	var x = YAHOO.namespace(lsName);
	$('#' + lsName + '_content').html("");
	x.dialog.cancel();
}

function trip_wow_light_box(id,taId){
	var url = "/ajax/TripWowDisplay.aspx?ta_id=" + taId;
	$.ajax({
	  url: url,
	  success: function(data){
		if(data=="404"){
			$('#' + id + '_content').html("Sorry we are unable to display the slideshow for this property");
		}else{
			$('.pop_up_more_help').css("padding", "0px");
			$('#' + id + '_content').html(data);
			$('#' + id + '_content div div').css("display","none");
		}
		moreInfo(id,680);
	  }
	});	
}
//--------------------------------------------------------------------------------
// TripAdvisor landing pages functions
//--------------------------------------------------------------------------------

function fetchTestimonial(forward, flipLabels, language) {
    if (flipLabels) {
        $("#prev_comment_start").css("display","none");
        $("#prev_next_comment").css("display","block");
    }
    var url = '/ajax/testimonials_ajax.aspx?quote=' + $('#current_quote').val() + '&dir=' + (forward ? "forward" : null) + '&language=' + language;
	$.ajax({
	  url: url,
	  dataType: 'json',
	  success: function(data){
		
		if(data) {
			$("#testimonial").fadeOut("fast", function(){
				$('#comment').html(data.Message);
				$('#comment_author').html('Home ' + data.HomeId + ' | ' + data.Town + ', ' + data.Country + ' | ' + data.Authour);
				$('#comment_date').html(data.QuotedDate);
				$('#current_quote').val(data.Order);
				$('#pic_path').attr("src","/picsmall/" + data.PicPath);
				$('#author').html("<b>" + data.Authour + "</b> <span>|</span> <a onclick=\"_gaq.push(['_trackEvent','wcu','testimonial','home_link']);\" href='" + data.HomeUrl + "' target='_blank'>Home " + data.HomeId + "</a> <span>|</span> <a onclick=\"_gaq.push(['_trackEvent','wcu','testimonial','country_link']);\" href='" + data.CountryUrl + "' target='_blank'>" + data.Country + "</a>");
				$("#testimonial").fadeIn("fast");
			});
		}
	  }
	});

}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if ((version >= 5.5) && (document.body.filters)) {
        for (var i = 0; i < document.images.length; i++) {
        	var img = document.images[i];
        	var imgName = img.src.toUpperCase();
        	if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
        		var imgID = (img.id) ? "id='" + img.id + "' " : "";
        		var imgClass = (img.className) ? "class='" + img.className + "' " : "";
        		var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
        		var imgStyle = "display:inline-block;" + img.style.cssText;
        		if (img.align == "left") imgStyle = "float:left;" + imgStyle;
        		if (img.align == "right") imgStyle = "float:right;" + imgStyle;
        		if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
        	    var strNewHTML = "<span " + imgID + imgClass + imgTitle
            	    + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                	    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                    	    + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
        		img.outerHTML = strNewHTML;
        		i = i - 1;
        	}
        }
    }
}

function displayEmailFailureMessage() {
    var html =  "<p>Oops! For some reason this email wasn’t sent. We've logged this issue and will fix it soon. " +
        		"If you want to contact us directly please call <%= Globals.TelephoneMain %> or email <a href='mailto:advertise@holidaylettings.co.uk'>advertise@holidaylettings.co.uk</a>" + 
        		"</p>";
    return html;
}



 	
//--------------------------------------------------------------------------------
// TripAdvisor landing pages functions - end
//--------------------------------------------------------------------------------

//Originally in saut.js  Now merged as it is required on every page
function sautHookOn(sautForm, sautContainer, sautInput, sautHidden) {   
    YAHOO.example.ItemSelectHandler = function() {
        //Point to our bespoke file that gives back location names 
        var oDS = new YAHOO.util.XHRDataSource("/saut_ajax.aspx");

        oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
        // Define the schema of the delimited results
        oDS.responseSchema = {
            recordDelim: "\n",
            fieldDelim: "\t"
        };

        // Instantiate the AutoComplete
        var oAC = new YAHOO.widget.AutoComplete(sautInput, sautContainer, oDS);
        oAC.resultTypeList = false;

        // Define an event handler to populate a hidden form field
        // when an item gets selected
        var myHiddenField = YAHOO.util.Dom.get(sautHidden);

        var myHandler = function(sType, aArgs) {
            var myAC = aArgs[0]; // reference back to the AC instance
            var elLI = aArgs[1]; // reference to the selected LI element
            var oData = aArgs[2]; // object literal of selected item's result data

            // ajf - aArgs[2] seems to be the whole line
            // ajf aArgs[2][2] is the 3rd column of data 
            myHiddenField.value = aArgs[2][1];
        };
        oAC.itemSelectEvent.subscribe(myHandler);

        var onFormSubmit = function(e, mySautForm) {
			unSetSeeds();
            YAHOO.util.Event.preventDefault(e);
            var formAction = YAHOO.util.Dom.get(sautForm);
            var userTypedValue = YAHOO.util.Dom.get(sautInput);

            //When users type too fast, the myHiddenValue is not up to date with what user has typed.
            if (myHiddenField.value.length == 0) {
                myHiddenField.value = userTypedValue.value;
                formAction.method = 'POST';
                formAction.action = '\/' + 'homesearch.asp' + '?' + 'locationkeywords=' + myHiddenField.value;
                formAction.submit();
            } else {
                window.location = '\/' + myHiddenField.value;
				return false;
            }
        };

        YAHOO.util.Event.addListener(YAHOO.util.Dom.get(sautForm), "submit", onFormSubmit);

        return {
            oDS: oDS,
            oAC: oAC
        };
    } ();

    //Set the input field and the hidden value to default values
    var myHiddenField = YAHOO.util.Dom.get(sautHidden);
    myHiddenField.value = '';
}
