var shortDayName = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var shortMonthName = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var townpostcodeattraction = "Hotel, attraction, postcode";
var hotelName = "-- Hotel Name --";
var arrivalDate = "-- Arrival Date --";
var moreTag = "more &gt;&gt;";
var lessTag = "&lt;&lt; less";
var moreTagBooking = "Show full booking information  &gt;&gt;";
var lessTagBooking = "&lt;&lt; Hide full booking information";

var showOffer = 'Hide offers for this room type';
var hideOffer = 'Show offers for this room type';

var varFree = "FREE";

var noRoomsSelected = "Please specify the number of rooms you require before proceeding to book";
var ErrNoSearchText = "You have not entered any valid search criteria. Please enter a keyword and perform your search again.";
var ErrDealsByEmail = "You have not entered a valid email address, please try again.";
var ErrMyBooking = "You have not entered a valid booking reference number, please try again.";
var showMoreSuggestions = "Show more suggestions";
var showLessSuggestions = "Show less suggestions";

var exceedsMaxPersons = "The maximum number of people for this room is";
var noPersonsSelected = "The minimum number of people for this room is";
var minimumNights = "This room must be booked for a minimum of";
var minimumNights2 = "nights!";
var minimumAdults = "The minimum number of people for this room is 1 adult.";

var roomInfo = "Room information";
var roomCanc = "Cancellation policy";

var tooManyGuests = "This room cannot accomodate this many people";
var tooFewGuests = "Please select at least one guest";

var CCErrorVal = "We've experienced a problem processing your credit card details.";

// GMap
var gMap_Directions   = "Directions:";
var gMap_ToHotel      = "To hotel";
var gMap_FromHotel    = "From hotel";
var gMap_StartAddress = "Start address:";
var gMap_EndAddress   = "End address:";
var gMap_GetDirections = "Get Directions";
var gMap_NoResults    = "Sorry, there were no results found. Please try entering the full address including country or entering a postcode.";
var gMap_MissingQuery = "Please enter an address or postcode.";
var gMap_DidYouMean   = "Did you mean?";

// Advanced Search
var as_InvalidRegion = "Sorry, we didn't recognise your requested destination. To perform an Advanced Search you must either select a region from the drop down menu or enter your required destination in the search box on the left.";

var siteLang="en";

var SortOrderBy="Order Search Results by...";
var SortHotelName="Hotel Name";
var SortDistance="Distance";
var GuestRating="Guest Rating";
var StarRating="Star Rating";
var PriceLH="Price (High to Low)";
var PriceHL="Price (Low to High)";

var mileskm="Miles";

//Address lookup text
var InvalidPostCode="Invalid Postcode";
var NoAddressFound ="No addresses Found";
var ManualEnterAddress= "---Manually enter address---";

//Booking Process
var valBlank = "Field cannot be blank";
var valBreakfast = "Please select a breakfast type";
var valNotAdded = "Some information was not added correctly";
var valPassMatch = "Passwords do not match";
var valPass = "Please enter a password at least 7 characters long";
var valAnsMatch = "Answers do not match";
var enterDetails = "Enter Details";
var editDetails = "Edit Details";
var hideDetails = "Hide Details";
var valBusLes = "Select reservation type";
var valEmail = "Invalid Email";
var valAddMatch = "Addresses do not match";
var valTel = "Invalid Telephone Number";
var valBedType = "Select a bed type";
var valSmoke = "Select a smoking option";
var valAdd = "Invalid Address";
var valCardNumb = "Invalid Card Number";
var valCardDate = "Start Date or Issue Number required";
var valCardExp = "Invalid expiry date";
var valCardCode = "Invalid security code";
var valCardIsu = "Invalid issue number";
var infoMiss = "Some information is missing";
var showSum = "Show Summary";
var valCredInfo = "The credit card information was incorrect";
var remCard = "Are you sure you want to remove the card details";
var cardSel = "Select a Credit Card";
var guestName = "Guest Name";
var bookerName = "Booker Name";
var minstaywarn1="A";
var minstaywarn2="night minimum stay applies on this date";
var bookerName = "Booker Name";
var showCancellation = "Show room cancellation policy";
var hideCancellation = "Hide room cancellation policy";
var autoCompleteHotel = "hotel";
var autoCompleteHotels = "hotels";
var showFacilities = "Show full room information";
var hideFacilities = "Hide full room information";
var childAgeAlert = "The maximum age for a child in this Hotel is ";
var NewGuest="Add a new guest";
var breakfastNotIncluded = "Breakfast not included";
var breakfastIncluded = "Breakfast included";

//hotelapartmentfilter
var hotelsOnly = "Hotels in";
var apartmentsOnly = "Apartments in";
var AllProperties = "Apartments and Hotels in";

//hotelfeedback
var pageError = "Please review the errors above.";
var completeInFull = "Please complete this section in full.";
var readMore = "Read more";
var readLess = "Read less";
var nextPage = "Next";
var prevPage = "Prev";

//London Searches
var londonTubes = "Select Tube";
var londonAreas = "Select Area";
var londonPostcodes = "Select Postcode";

//photo uploads
var browseText = "Browse";
var PhotoDeleted = "Your photo has been successfully deleted";
var showTags = "Show tags";
var hideTags = "Hide tags";
var upError = "Error";
var sizeError = "The image you are trying to upload is too small";
var selectFile = "Please select a file to upload";
var imageTooBig = "The image you are trying to upload exceeds<br>the maximum limit of 5MB";
var imgUploading = "Uploading...";
var creatingThumb = "Creating thumbnail...";
//vids
var vidSizeError = "The video you are trying to upload exceeds the limit of 50MB";
var savingVideo = "Saving video...";
var genUpError = "Your file does not meet the specified requirements and cannot be uploaded. Please amend your file and try again.";

//cancellation & confirmationresender
var canXbookingNotFound = "Booking not found. Please check your details and try again.";
var canXbookingsNotFound = "No bookings have been found for the details you entered. Check your details and try again.";
var canXbookingCancelled = "This booking cannot be cancelled online. Please contact our Customer Services Team on 0844 774 2004.";
var canXbookingAlreadyCancelled = "This booking has already been cancelled.";
var canXbookingSuccesfullyCancelled = "Thank you, your booking has been cancelled. We've sent you an email to confirm this.";
var canXbookingRoomSuccesfullyCancelled = "This room has been cancelled. You will receive a modification email shortly to confirm this. If you do not receive this please contact a member of our team immediately on 0844 774 2004.";
var showRooms = "show rooms";
var hideRooms = "hide rooms";
var canXyes = "Yes";
var canXno = "No";
var canXok = "OK";
var areYouSureCancelRoom = "Are you sure you want to amend this booking?";
var areYouSureCancelBooking = "Are you sure that you wish to cancel this booking?";
var confirmationResent = "Thank you, we've re-sent your confirmation by email.";
var cancelBookingText = "Booking is being cancelled...";
var cancelRoomText = "Booking is being amended...";
var pleaseEnterAll = "The highlighted information has been entered incorrectly. Please check your details and try again.";
var canxLoadingBookings = "Loading Bookings...";
var canxdateformat = "dd/mm/yyyy";
var canxCancel = "Cancel booking";
var canxCancelRoom = "Cancel room";
var canxResend = "Resend my confirmation";
var canxCannotCancel = "This booking cannot be cancelled online. Please contact our Customer Services Team on 0844 774 2004.";

//booking login process
var msgNotRegistered = "This username is not currently registered.";
var msgLoginError = "Your username or password is incorrect";
var msgPassReminder = "A password reminder has been sent to your email";

// for toggle map text , put in here for translations
var toggleMapText = {
		'true': 'Hide Map',
		'false': 'Show Map'
	};

var didStatus = {'true': 'Hide Suggestions','false': 'Show Suggestions'};
var statusMore = {'true': ' show less','false': ' show more'};
var searchView = "NEW! Search view";
var newSearch = "New";
var classicSearch = "Classic";
var hiltonMaxRoomsText = 'You can only book a maximum of 9 rooms at this hotel. Please amend the number of rooms to proceed. Additional rooms can be booked under a new reservation.';
var hiltonMaxSpecialRequest = '65 characters maximum';
var switchToNewOne = 'You are viewing our Classic search results page. Why not try viewing our ';
var switchToNewTwo = 'new look search results?';
var switchToClassicOne = 'You are viewing our new look search results page. ';
var switchToClassicTwo = '';
var switchToClassicThree = ' You can go back to our ';
var switchToClassicFour =  'classic results';
var switchToClassicFive = ' at any time';


// for PhoneReservation
var HideRoomInformation = 'Hide room information';
var ShowRoomInformation = 'Show room information';

// Top guest Rated hotels
var pricesFrom = "Prices from";


//hotel details 
var youSave = "You save";
var roomUnvailable = "Room unavailable";
var notAllAvailable = "Not all rooms are available";
var fullTxt = "Full";

//search result
var UpdatingResults = "Updating your results";

$(window).addEvent("domready", load);

var actb;
var timerId;
var isBusy;
// Client side cache to avoid repeat lookups
var cache = new Object();
var mouseOverItem;
var selectedItem;
var postUrl;
var autoCompleteActive = false;


function load() {

    actb = new AutoCompleteTextBox("txtSearch", "suggest", "suggestout");
    if ($("txtSearch").value == '') {
        $("txtSearch").value = townpostcodeattraction;
    }

    postUrl = document.forms["main"].action;
    $(document.forms["main"]).addEvent("submit", function(e) {
        actb.HideSuggestions();
        window.clearTimeout(timerId);
        return true;
    });

    $("txtSearch").addEvent("click", function(e) {
        ClearDefaultSearchText();
    });
}

function AutoCompleteTextBox(TextBoxId, DivId, DivIdOut, DivClass) {
	// initialize member variables
	var oThis = this;
	var oText = $(TextBoxId);
	var oDiv = $(DivId);
	var oDivOut = $(DivIdOut);
	this.TextBox = oText;
	this.Div = oDiv;
	if(typeof(formSubmitpath) != 'undefined')
    {
        this.DefaultFormAction = document.forms["main"].action;
    }
	this.DefaultFormAction = "http://www.laterooms.com/en/p5854/Hotels.aspx";

    // Set left and top coords
    oDivOut.style.left = oText.getCoordinates().left + "px";
    oDivOut.style.top = (oText.getCoordinates().bottom -1) + "px";
    
    if($('switch'))
    {
        oDivOut.style.top = (oText.getCoordinates().bottom + 34) + "px";
    }

	// attach handlers to the TextBox
	oText.AutoCompleteTextBox = this;
	
	// Use onkeypress for autorepeat up/down -Use onkeydown NOT onkeypress as ie does not prcoess tab button in onkeypress
	oText.onkeyup = AutoCompleteTextBox.prototype.OnKeyUp;
	oText.onkeydown = AutoCompleteTextBox.prototype.OnKeyDown;

	if (TextBoxId=="txtSearch")
	{
	    oText.onblur=CustomOnBlur;
	}
	else
	{
	    oText.onblur = AutoCompleteTextBox.prototype.OnBlur;
	}
	oText.onfocus = AutoCompleteTextBox.prototype.OnFocus;
}

function CustomOnBlur()
{
    ResetDefaultSearchText();
    this.AutoCompleteTextBox.HideSuggestions();
    autoCompleteActive = false;
}

AutoCompleteTextBox.prototype.OnBlur = function() {
	this.AutoCompleteTextBox.HideSuggestions();
	autoCompleteActive = false;
}

AutoCompleteTextBox.prototype.OnFocus = function() {
    autoCompleteActive = true;
    if(this.AutoCompleteTextBox.Div.childNodes.length > 0) {
	    this.AutoCompleteTextBox.Div.style.display = 'block';
	    if (Browser.Engine.trident4) 
            this.AutoCompleteTextBox.DropdownStyles("none");
    }
    ClearDefaultSearchText();
}

AutoCompleteTextBox.prototype.OnKeyDown = function(oEvent) {
	if ( ! oEvent) {
		oEvent = window.event;
	}
	var iKeyCode = oEvent.keyCode;
	if (iKeyCode == 13) {
		if (actb.Div.style.display == "block") {
			return false;
		}
		else {
		    $("search").click();
            this.cancelBubble = true;
            return false;
		}
	}
	if (iKeyCode == 9) {
	    if (selectedItem != null) {
	        AutoCompleteTextBox.prototype.MouseDown(selectedItem); 
	    }
	    actb.HideSuggestions();
	    autoCompleteActive = false;
	}
}

AutoCompleteTextBox.prototype.OnKeyUp = function(oEvent) {

    document.forms["main"].action = actb.DefaultFormAction  + getSpecialOfferParams();
    if (!oEvent) {
        oEvent = window.event;
    }

    var iKeyCode = oEvent.keyCode;
    if (iKeyCode == 13 && selectedItem != null)
        AutoCompleteTextBox.prototype.MouseDown(selectedItem);
    if (iKeyCode == 13 || iKeyCode == 27) {
        // Enter or Esc Pressed
        actb.HideSuggestions();
        return false;
    }
    if (iKeyCode == 8 || iKeyCode == 46) {
    }
    else if (iKeyCode == 40) { // Down
        divs = actb.Div.getElementsByTagName("div");
        index = mouseOverItem.index + 1;
        if (index == divs.length)
            index = 0;
        divs[index].onmousemove();
        return;
    } else if (iKeyCode == 38) { // Up
        divs = actb.Div.getElementsByTagName("div");
        index = mouseOverItem.index - 1;
        if (index < 0)
            index = divs.length - 1;
        divs[index].onmousemove();
        return;
    } else if (iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46)) {
        return;
    }
    actb.HideSuggestions();

    var txt = actb.TextBox.value;

    if (txt.length > 0 && txt != oldValue) {
        if (!cache[actb.TextBox.value.toLowerCase()]) {
            // clear any previous timer to avoid doing multiple lookups for fast typists
            window.clearTimeout(timerId);
            timerId = window.setTimeout("DoCallBack();", 1000);
        } else {
            actb.CreateList(cache[actb.TextBox.value.toLowerCase()]);
        }
    } else {
        actb.HideSuggestions();
    }
}

var oldValue = "";
function DoCallBack() {
	if (oldValue != actb.TextBox.value) {		
	    var url = "http://www.laterooms.com/en/p5854/AutoComplete/Index/" + encodeURI(actb.TextBox.value.toLowerCase()) + ".mvc";
	    new Request.JSON({ url:url , onComplete: XHR_Complete}).send();
		oldValue = actb.TextBox.value;
	}
}

function XHR_Complete(res) {
    //var res = eval("(" + responseText + ")");
	cache[res.SearchTerm.toLowerCase()] = res;
	actb.CreateList(res);
}

AutoCompleteTextBox.prototype.DropdownStyles = function(display) {
    if($$("#ddlSort select").length > 0) $$("#ddlSort select")[0].style.display = display;
    $("ddlDate").style.display = display;
    $("ddlNights").style.display = display;
    $("ddlRoomType").style.display = display;

}

AutoCompleteTextBox.prototype.CreateList = function(res) {
    $('suggestout').style.top = $('txtSearch').getCoordinates().bottom + "px";
    if (autoCompleteActive == true) {
        if (Browser.Engine.trident4)
            this.DropdownStyles("none");

        while (this.Div.childNodes.length > 0) // Delete all children
            this.Div.removeChild(this.Div.firstChild);

        // get all the matching strings from the server response
        // add each string to the popup-div
        var i,
	    n = res.Results.length;

        if (n > 0) {
            for (i = 0; i < n; i++) {
                var oDiv = document.createElement('div');
                oDiv.index = i;
                this.Div.appendChild(oDiv);

                try {
                    if (isSpecialOffersPage()) {
                        oDiv.innerHTML = "<span>" + res.Results[i].Text + "</span>";
                    }
                    else {
                        oDiv.innerHTML = "<b>" + res.Results[i].Count + " " + (res.Results[i].Count != 1 ? autoCompleteHotels : autoCompleteHotel) + "</b><span>" + res.Results[i].Text + "</span>";
                    }
                }
                catch (e) {
                    alert(e);
                    return;
                }

                oDiv.onmousemove = AutoCompleteTextBox.prototype.Div_MouseOver;
                oDiv.onmousedown = AutoCompleteTextBox.prototype.Div_MouseDown;
                oDiv.AutoCompleteTextBox = this;
                oDiv.data = res.Results[i];
                if (i == n - 1) {
                    mouseOverItem = oDiv;
                }
            }
            this.Div.style.display = 'block';
        } else {
            actb.HideSuggestions();
        }
    } else {
        actb.HideSuggestions();
    }
}

AutoCompleteTextBox.prototype.Div_MouseOver = function() {
	AutoCompleteTextBox.prototype.MouseOver(this);
}

AutoCompleteTextBox.prototype.Div_MouseDown = function() {
	AutoCompleteTextBox.prototype.MouseDown(this);
}

function getSpecialOfferParams() {
    if (window.location.href.indexOf("special-offers") != -1) {
        return "?q=10_special-offers";
    }
    else {
        return '';
    }
}

function isSpecialOffersPage() {
    return window.location.href.indexOf("special-offers") != -1;
}

AutoCompleteTextBox.prototype.MouseDown = function(div) {
    div.AutoCompleteTextBox.TextBox.value = div.data.Text;
    var actionUrl = "http://www.laterooms.com/en/p5854/" + div.data.Url + ".aspx" + getSpecialOfferParams();    
    if(typeof(formSubmitpath) != 'undefined')
    {
        actionUrl = formSubmitpath + actionUrl;
    }
    document.forms["main"].action = actionUrl;
}

AutoCompleteTextBox.prototype.MouseOver = function(div) {
	mouseOverItem.className = "";
	div.className = "hover";
	mouseOverItem = div;
    selectedItem = div;
}

AutoCompleteTextBox.prototype.HideSuggestions = function() {
    selectedItem = null;
	this.Div.style.display = 'none';
	if (Browser.Engine.trident4) 
        this.DropdownStyles("");
}

function ResetDefaultSearchText()
{
    if (actb.TextBox.value=="")
    {
        actb.TextBox.value=townpostcodeattraction;
    }
}

function ClearDefaultSearchText()
{
    if (actb.TextBox.value==townpostcodeattraction)
    {
        actb.TextBox.value="";
    }
}
