function init() {
	// Test for browser support of js functionality eg. getElementById
	if (arguments.callee.done) return;
	arguments.callee.done = true;
    if (_timer) clearInterval(_timer);
    //all pages
    doPopups();
	// search page
    
    // search results page
	if(document.getElementById('key')){
		hideKey();
		giveBehaviourToKey();
	}
    //disambiguate page
	if(document.getElementById('disambiguate')){
		truncateLists('disambiguate');
	}
	// brochure page
    if(document.getElementById('embededded_datechange')){
        embeddedDateBox();
    }
    //select dates page
    if(document.getElementById('prebookingform')) {
        addCheckOutDate();
    }
    //select rooms page & brochure templates with room select
    if(document.getElementById('roomselectform')){
        roomDropdowns();
    }
    //enterdetails page
    if(document.getElementById('enterdetails')) {
        document.getElementById('pleasenopressagain').style.display = 'none';
        doCountryDropDownBehaviour();
    }
    //confirmation page
    if(document.getElementById('confirmation')) {
        hideConfirmationBoxes();
    }

}

/* for Mozilla */
if (document.addEventListener) {
   document.addEventListener("DOMContentLoaded", init, null);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
	document.write("<script id=__ie_onload defer src=\"//:\"><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = init;

//common functions

function doPopups() {
    if (!document.getElementsByTagName) return false;
    var popuplinks = getElementsByClassName(document, 'a', 'popup');
    for (var i=0; i < popuplinks.length; i++) {
      if (popuplinks[i].className.match("popup")) {
        popuplinks[i].onclick = function() {
          window.open(this.href,'NewWindow','width=450,height=300,scrollbars=yes,status=yes,resize=1,resizable=1');
          return false;
        }
      }
    }

}

//Search page functions

//Search results page functions
function hideKey(){
	var key = document.getElementById('key');
	key.style.position = 'absolute';
	key.style.display = 'none';
	key.style.margin = '0';
}

function giveBehaviourToKey(){
	if (!document.getElementsByTagName) return false;
	var imgs = document.getElementsByTagName("img");
	for (var i=0; i < imgs.length; i++) {
		if (imgs[i].className.match('facilityicon')) {
			imgs[i].onmouseover = function(){
				showDiv(this.id,'key','left');
			}
			imgs[i].onmouseout = function(){
				hideDiv('key');
			}
		}
	}
}

function showDiv (el, div, alignX, alignY) {
	if (document.getElementById){
		var i = document.getElementById(el);
		var c = document.getElementById(div);
		if (c.style.display != "block"){
			var l=0; var t=0;
			aTag = i;
			do {
				aTag = aTag.offsetParent;
				l += aTag.offsetLeft;
				t += aTag.offsetTop;
			} while (aTag.offsetParent && aTag.tagName != 'BODY');
			var left =  i.offsetLeft + l;
			var top = i.offsetTop + t + i.offsetHeight + 2;
			if (alignX == 'left' && c.style.width){
				left = left - parseInt(c.style.width);
			}
			if (alignY == 'top' && c.style.height){
				top = top - parseInt(c.style.height) -25;
			}
			c.style.left = left+'px';
			c.style.top = top+'px';
			c.style.display = "block";
		} else {
			c.style.display="none";
		}
	}
}

function hideDiv (div) {
	if (document.getElementById){
		var c=document.getElementById(div);
		c.style.display="none";
	}
}

// brochure page functions

// disambiguate page
function truncateLists(containerId){
    var container = document.getElementById(containerId);
    var lists = container.getElementsByTagName('ul');
    //alert("lists.length=" + lists.length)
    for(i=0;i<lists.length;i++){
        var listitems = lists[i].getElementsByTagName('li');
        for(j=5;j<listitems.length;j++){
            listitems[j].style.display = 'none';
        }
        if(listitems.length > 5){
            addShowAllLink(lists[i],containerId,i);
        }
    }
}

function addShowAllLink(thisList,containerId,number){
    var thislist = thisList;
    var showalllinkcontainer = document.createElement('div');
    setClassAttribute(showalllinkcontainer,'showalllinkcontainer');
    var showalllink = document.createElement('a');
    showalllink.setAttribute('href','#');
    setClassAttribute(showalllink,'strong');
    showalllink.setAttribute('id','showalllink'+number);
    var showalllinktext = document.createTextNode(transl_showall + ' >>');
    showalllink.appendChild(showalllinktext);
    showalllinkcontainer.appendChild(showalllink);
    thislist.parentNode.appendChild(showalllinkcontainer);
    giveonClickToLink('showalllink'+number);

}

function giveonClickToLink(hrefid){
	if (!document.getElementById) return false;
	document.getElementById(hrefid).onclick = function(){
		unTruncateList(this);
		return false;
	}
}

function setClassAttribute(theElementName,theClassValue){
	if (theElementName.getAttributeNode("class")) {
	  for (var a = 0; a < theElementName.attributes.length; a++) {
		var attrName = theElementName.attributes[a].name.toLowerCase();
		if (attrName == 'class') {
		  theElementName.attributes[a].value = theClassValue;
		}
	  }
	// otherwise create a new attribute
	} else {
	  theElementName.setAttribute("class", theClassValue);
	}
}

function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

if(typeof Array.prototype.push != "function"){
    Array.prototype.push = ArrayPush;
    function ArrayPush(value){
        this[this.length] = value;
    }
}

function unTruncateList(link){
    var thelistitems = link.parentNode.parentNode.getElementsByTagName('li');
    for(i=0;i<thelistitems.length;i++){
        thelistitems[i].style.display = 'block';
    }
    link.style.display = 'none';
}

function addEvent( obj, type, fn ){
	if (obj.addEventListener){
		obj.addEventListener( type, fn, false );
	}
	else if (obj.attachEvent){
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn ){
	if (obj.removeEventListener){
		obj.removeEventListener( type, fn, false );
	}
	else if (obj.detachEvent){
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

//from common.js



function OpenNewPopupWinRateGT(c) {
    window.open(c,
    'RateGuarantee',
    'width=500,height=300,scrollbars=yes,status=yes,resize=1,resizable=1');
}

function displayLoading(){
    if (!document.getElementById) return false;
    document.getElementsByTagName('html')[0].style.height = "100%";
    document.getElementsByTagName('html')[0].style.margin = "0";
    document.getElementsByTagName('html')[0].style.padding = "0";
    document.getElementsByTagName('html')[0].style.border = "none";
    document.getElementsByTagName('body')[0].style.height = "100%";
    document.getElementsByTagName('body')[0].style.margin = "0";
    document.getElementsByTagName('body')[0].style.padding = "0";
    document.getElementsByTagName('body')[0].style.border = "none";
    document.getElementById('mainbody').style.display = "none";
    var lp = document.createElement('div');
    lp.setAttribute('id', 'loadingpage');
    var lpi = document.createElement('div');
    var hone = document.createElement('h1');
    hone.appendChild(document.createTextNode(loadingpagetitle));
    lpi.appendChild(hone);
    var np = document.createElement('p');
    np.innerHTML = loadingpagetext;
    lpi.appendChild(np);
    lp.appendChild(lpi);
    document.body.appendChild(lp);
    lp.style.display = "block";
    lp.style.position = "absolute";
    lp.style.top = "0";
    lp.style.left = "0";
    lp.style.width = "100%";
    lp.style.height = "100%";
}

function prefill() {

    afirstname = document.getElementById('firstName').value;
    alastname = document.getElementById('lastName').value;
    firstguest = document.getElementById('guestdetails').getElementsByTagName('input')[0];
    cardholder = document.getElementById('cardHoldersName');

    if(cardholder.value == ""){
        cardholder.value = afirstname + " " + alastname;
    }

    if(firstguest.value == ""){
        firstguest.value = afirstname + " " + alastname;
    }

}

function hideConfirmationBoxes() {
    amendments = document.getElementById('conf_amendments');
    policies = document.getElementById('conf_policies');
    //directions = document.getElementById('conf_directions');

    var np = document.createElement('p');
    np.className = 'reveal';

    var new_link = document.createElement('a');
    new_link.setAttribute('href', '#conf_amendments');
    new_link.appendChild(document.createTextNode(howtocancel));
    new_link.onclick = function () {
        this.style.display = 'none';
        amendments.style.display = '';
    }

    np.appendChild(new_link);

    var new_link = document.createElement('a');
    new_link.setAttribute('href', '#conf_policies');
    new_link.appendChild(document.createTextNode(hotelpolicy));
    new_link.onclick = function () {
        this.style.display = 'none';
        policies.style.display = '';
    }

    np.appendChild(new_link);

//    var new_link = document.createElement('a');
//    new_link.setAttribute('href', '#conf_directions');
//    new_link.appendChild(document.createTextNode(gettingtoyourhotel));
//    new_link.onclick = function () {
//        this.style.display = 'none';
//        directions.style.display = '';
//    }
//
//    np.appendChild(new_link);

    amendments.style.display = policies.style.display = 'none';

    amendments.parentNode.insertBefore(np, amendments);
}

function toggleDropdowns(obj) {
    var next_cell = obj.parentNode.nextSibling;
    while (next_cell.nodeType != 1) {
        next_cell = next_cell.nextSibling;
    }
    var all_dropdowns = next_cell.getElementsByTagName('select');
    for (var i=1; i<all_dropdowns.length; i++) {
        all_dropdowns[i].style.display = (i+1 > obj.value) ? 'none' : '';
    }
}

function roomDropdowns() {
    var room_dropdowns = getElementsByClassName(document, 'select', 'no-of-rooms');
    for (var i=0; i<room_dropdowns.length; i++) {
        room_dropdowns[i].onchange = function () {
            toggleDropdowns(this);
        }
        toggleDropdowns(room_dropdowns[i]);
    }
}

var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

function addCheckOutDate() {
    var prebookingformfs = document.getElementById('startdatefs');
    // Create day dropdown
    checkout_day = document.getElementById('day').cloneNode(true);
    checkout_day.setAttribute('id', 'checkoutday');
    // Create month dropdown
    checkout_month = document.getElementById('month').cloneNode(true);
    checkout_month.setAttribute('id', 'checkoutmonth');
    // Create year dropdown
    checkout_year = document.getElementById('year').cloneNode(true);
    checkout_year.setAttribute('id', 'checkoutyear');

    // When the selected checkout date has changed, update the nights dropdown
    checkout_day.onchange = checkout_month.onchange = checkout_year.onchange = function () {
        // Find the UTC date from the checkout date dropdowns
        var checkout = Date.UTC(checkout_year.value, checkout_month.selectedIndex, checkout_day.selectedIndex + 1);
        var checkoutnonutc = new Date(checkout_year.value, checkout_month.selectedIndex, checkout_day.value);
        var checkin = Date.UTC(document.getElementById('year').value, document.getElementById('month').selectedIndex, document.getElementById('day').selectedIndex + 1);
        var checkinnonutc = new Date(document.getElementById('year').value, document.getElementById('month').selectedIndex, document.getElementById('day').selectedIndex + 1);
        var diff = checkout - checkin;
        if (diff > 0) {
            diff_in_days = diff / 1000 / 60 / 60 / 24;
            var nights_options = document.getElementById('nights').getElementsByTagName('option');
            for (var i=0; i<nights_options.length; i++) {
                nights_options[i].selected = (nights_options[i].value == diff_in_days) ? true : false;
            }
        }
        nh.innerHTML = "<strong>" + transl_checkout + ":</strong> " + days[checkoutnonutc.getDay()];
        document.getElementById('checkinday').innerHTML = days[checkinnonutc.getDay()];
    }

    // Also need to update the checkout date when the nights dropdown is changed
    document.getElementById('day').onchange = document.getElementById('month').onchange = document.getElementById('year').onchange = document.getElementById('nights').onchange = function () {
        var checkin = new Date(document.getElementById('year').value, document.getElementById('month').selectedIndex, document.getElementById('day').selectedIndex + 1);
        var nights = document.getElementById('nights').value;
        var checkout = new Date(checkin.getFullYear(), checkin.getMonth(), checkin.getDate()+parseInt(nights));
        checkout_year.value = checkout.getFullYear();
        checkout_month.value = checkout.getMonth() + 1;
        checkout_day.value = checkout.getDate();
        nh.innerHTML = "<strong>" + transl_checkout + ":</strong> " + days[checkout.getDay()];
        document.getElementById('checkinday').innerHTML = days[checkin.getDay()];
    }

    // Add a heading
    var nh = document.createElement('p');
    setClassAttribute(nh,'wl_clearfield');
    nh.innerHTML = "<strong>" + transl_checkout + ":</strong>";
    prebookingformfs.appendChild(nh);

    // Append new dropdowns
    prebookingformfs.appendChild(checkout_day);
    prebookingformfs.appendChild(checkout_month);
    prebookingformfs.appendChild(checkout_year);

    // Append another calendar popup thing
    var na = getElementsByClassName(document, 'a', 'calendar')[0].cloneNode(true);
    na.onclick = function () {
        displayCalendar(document.getElementById('checkoutyear'),document.getElementById('checkoutmonth'),document.getElementById('checkoutday'),this);
        return false;
    }
    prebookingformfs.appendChild(na);

    // Set the checkout date to equal the checkin date, to start with
    checkout_day.selectedIndex = document.getElementById('day').selectedIndex;
    checkout_month.selectedIndex = document.getElementById('month').selectedIndex;
    checkout_year.selectedIndex = document.getElementById('year').selectedIndex;

    // Select the correct day option
    var num_nights = parseInt(document.getElementById('nights').value);
    checkout_date = parseInt(document.getElementById('day').value) + num_nights;
    var checkout_date_options = checkout_day.getElementsByTagName('option');
    // If checkout date is more than the number of options available, we have crossed the end of a month
    if (checkout_date > checkout_date_options.length) {
        // Increment the month
        var current_month = parseInt(document.getElementById('month').value);
        if (current_month != 12) {
            var new_month = current_month + 1;
        } else {
            var new_month = 1;
            // Increment the year
            var next_year = parseInt(document.getElementById('year').value) + 1;
            var checkout_year_options = checkout_year.getElementsByTagName('option');
            for (var i=0; i<checkout_year_options.length; i++) {
                checkout_year_options[i].selected = (checkout_year_options[i].value == next_year) ? true : false;
            }
        }
        var checkout_month_options = checkout_month.getElementsByTagName('option');
        for (var i=0; i<checkout_month_options.length; i++) {
            checkout_month_options[i].selected = (checkout_month_options[i].value == new_month) ? true : false;
        }
        // And chop off a month from the date
        checkout_date -= checkout_date_options.length;
    }
    for (var i=0; i<checkout_date_options.length; i++) {
        checkout_date_options[i].selected = (checkout_date_options[i].value == checkout_date) ? true : false;
    }
}


function doCountryDropDownBehaviour(){

    var cdd = document.getElementById('country');
    var pcl = document.getElementById('postcodelabel');

    if(cdd.value != 'GB'){
        pcl.style.fontWeight = 'normal';
        document.getElementById('pclasterisk').style.visibility = 'hidden';
        document.getElementById('pcinfo').style.visibility = 'hidden';
    }

    cdd.onchange = function(){
        if(cdd.value != 'GB'){
            pcl.style.fontWeight = 'normal';
            document.getElementById('pclasterisk').style.visibility = 'hidden';
            document.getElementById('pcinfo').style.visibility = 'hidden';
        }
        else{
            pcl.style.fontWeight = 'bold';
            document.getElementById('pclasterisk').style.visibility = 'visible';
            document.getElementById('pcinfo').style.visibility = 'visible';
        }
    }
}

function embeddedDateBox(){
    document.getElementById('embededded_datechange').onclick = function(){
        // hide room selects and display dateselect box again but in new place
        var roomsinbrochurediv = document.getElementById('roomselectinbrochure');
        document.getElementById('roomselectsummary').style.display = 'none';
        document.getElementById('roomselect').style.display = 'none';
        var dtbox = document.getElementById('wl_roomselectdates');
        roomsinbrochurediv.appendChild(dtbox);
        dtbox.style.display = 'block';
        return false;
    }
}

// DATETIPS //

var LocationHandler = {

    valid: false,

    init: function () {

        this.location = (document.getElementById('placename')) ? document.getElementById('placename') : 'null';

    },

    throwError: function (msg) {

        $('#location_error').html('<p>' + msg + '</p>');
        $('#location_error').slideDown();

    }

}

var FormHandler = {

        checkForm: function (e) {

            $('.errormessage').hide();

            // Form submission - check that the start date entered is valid and not in the past
            if (DateHandler.startDate() < DateHandler.today) {
                // Date is in the past - throw error, recommend the same date in the next month
                DateHandler.suggested_dates = [];
                DateHandler.addSuggestedDate(new Date(DateHandler.start_year.value, DateHandler.today.getMonth() + 1, DateHandler.start_date.value));
                DateHandler.throwError(dateInPast + ' ' + DateHandler.days_of_the_week[DateHandler.today.getDay()] + ' ' + DateHandler.today.getDate() + DateHandler.suffixes[DateHandler.today.getDate() - 1] + ' ' + DateHandler.months[DateHandler.today.getMonth()] + ' ' + DateHandler.today.getFullYear());
            } else if(DateHandler.startDate().getTime() > (DateHandler.today.getTime() +  31104000000))  {
                //date is more than 360 days in the future
                DateHandler.throwError(tooFarInFuture);
            } else {
                // Date is in the future - check it is a valid date
                if (DateHandler.isValidDate(DateHandler.start_date.value, DateHandler.start_month.value - 1, DateHandler.start_year.value)) {
                    DateHandler.valid = true;
                } else {
                    DateHandler.suggested_dates = [];
                    DateHandler.addSuggestedDate(DateHandler.previousValidDate(DateHandler.start_date.value, DateHandler.start_month.value - 1, DateHandler.start_year.value));
                    DateHandler.addSuggestedDate(DateHandler.nextValidDate(DateHandler.start_date.value, DateHandler.start_month.value - 1));
                    DateHandler.throwError('' + nodateStart + ' ' + DateHandler.start_date.value + DateHandler.suffixes[DateHandler.start_date.value - 1] + ' ' + DateHandler.months[(DateHandler.start_month.value - 1)] + ' ' + DateHandler.start_year.value + ' ' + nodateEnd + '');
                }
            }

            if (LocationHandler.location.value == '') {
                LocationHandler.throwError(missingLocation);
            } else {
                LocationHandler.valid = true;
            }

            if (DateHandler.valid && LocationHandler.valid) {
                document.getElementById('wl_searchForm').submit();
            } else {
                return false;
            }

        }

}

var DateHandler = {

    valid: false,
    today: new Date(),

    suffixes: ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'],

    suggested_dates: [],

    setStartDate: function (date) {

        this.start_date.value = date.getDate();
        this.start_month.value = date.getMonth() + 1;
        this.start_year.value = date.getFullYear();

        //set numnights to 1 if left at 0
        if(document.getElementById('wl_searchForm').nights.value == 0){
            document.getElementById('wl_searchForm').nights.value = 1;
        }


        if (LocationHandler.location.value != '') {
            $('#error').html('<p>' + checkingAvail +'</p>');
            document.getElementById('wl_searchForm').submit();
        } else {
            $('#error').slideUp();
        }

    },

    startDate: function () {
        return new Date(this.start_year.value, this.start_month.value - 1, this.start_date.value, 23, 59, 59);
    },

    init: function () {

        // Grab references to the start date elements
        this.start_date = document.getElementById('day');
        this.start_month = document.getElementById('month');
        this.start_year = document.getElementById('year');

        this.days_of_the_week = dHdayArray;
        this.months = dHmonthArray;

    },

    isValidDate: function (date, month, year) {
        switch (month) {
            case 3:
            case 5:
            case 8:
            case 10:
            case "3":
            case "5":
            case "8":
            case "10":
                return (parseInt(date) != 31);
                break;
            case 1:
            case "1":
                if ((year % 4 == 0 && year % 100 != 0) || (year % 4 == 0 && year % 100 == 0 && year % 400 == 0)) {
                    return (parseInt(date) < 30);
                } else {
                    return (parseInt(date) < 29);
                }
                break;
            default:
                return true;
        }
    },

    nextValidDate: function (date, month) {
        return new Date(this.start_year.value, parseInt(month) + 1, 1);
    },

    previousValidDate: function (date, month, year) {
        switch (month) {
            case 3:
            case 5:
            case 8:
            case 10:
            case "3":
            case "5":
            case "8":
            case "10":
                return new Date(this.start_year.value, month, 30);
                break;
            case 1:
            case "1":
                var new_date = ((year % 4 == 0 && year % 100 != 0) || (year % 4 == 0 && year % 100 == 0 && year % 400 == 0)) ? 29 : 28;
                return new Date(this.start_year.value, month, new_date);
        }
    },

    addSuggestedDate: function (date) {
        this.suggested_dates[this.suggested_dates.length] = date;
    },

    throwError: function (msg) {
        if (this.suggested_dates.length > 0) {
            var message = '<p>' + msg + '</p><p>' + didYouMean + '</p><ul>';
        } else {
            var message = '<p>' + msg + '</p><ul>';
        }
        for (var i=0; i<this.suggested_dates.length; i++) {
            message += '<li><a href="#" onclick="DateHandler.setStartDate(new Date(' + this.suggested_dates[i].getFullYear() + ', ' + (this.suggested_dates[i].getMonth()) + ', ' + this.suggested_dates[i].getDate() + ')); return false;">' + this.days_of_the_week[this.suggested_dates[i].getDay()] + ' ' + this.suggested_dates[i].getDate() + this.suffixes[this.suggested_dates[i].getDate() - 1] + ' ' + this.months[this.suggested_dates[i].getMonth()] + ' ' + this.suggested_dates[i].getFullYear() + '</a></li>';
        }
        message += '</ul>';
        $('#error').html(message);
        $('#error').slideDown();
    }

}

$(document).ready(function () {
    if (document.getElementById('wl_searchForm')) {
        DateHandler.init();
        LocationHandler.init();
        document.getElementById('wl_searchForm').onsubmit = FormHandler.checkForm;
    }
});

$(window).unload(function () {
    $('#error').html('').hide();
});


// SCROLL INFO BOXES //

   $(document).ready(function() {
       $('div.roominfo').hide();

       $('a.roomname').click(function () {
           $(this).parent('td').parent('tr').next('tr').find('.roominfo').slideToggle();
           $(this).parent('h3, p').siblings('.roominfo').slideToggle();
           return false;
       });

   });
