/*
1) Useful functions.
2) Postcodes: validation and find in modal dialog box.
3) Email: validation and send from modal dialog box.
4) Availability: highlighting, synching and validation.
5) Form Level validation
6) Fieldset level validation
*/
//1) Useful functions.
var intSubmission = 0;
var curFocus = '';
var postcodeModal = false;
var pendingEvent;
function firstSubmission() {
    if (intSubmission == 0) {
        intSubmission++;
        return true;
    }
    return false;
}
function selectAll(id) {
    document.getElementById(id).focus();
    if (id != curFocus) {
        document.getElementById(id).select();
    }
    curFocus = id;
}
//2) Postcodes: validation and find in modal dialog box.
function validatePostcode(Postcode) {
    if (stringContainsTags(Postcode)) {
        alert('This is not a valid UK postcode.');
        return false;
    }
    return true;
}
function resField_Keypress(ctl, evt) {
    if (enterKey(ctl, evt)) {
        document.forms['frmOption'].cmdContinue.click();
        return false;
    }
    return true;
}
function txtFindPostcode_Keypress(ctl, evt) {
    if (enterKey(ctl, evt)) {
        findAddress_Click();
        return false;
    }
    return true;
}
function txtFindPostcode2_Keypress(ctl, evt) {
    if (enterKey(ctl, evt)) {
        findAddress2_Click();
        return false;
    }
    return true;
}
function enterKey(ctl, evt) {
    var keyCode = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
    return (keyCode == 13);
}
function findAddress_Click() {
    $('matchingAddresses').options.length = 0;
    $('noAddresses').innerHTML = '';
    $('showAddresses').style.display = 'none';
    var postCode = $('txtFindPostcode').value;
    $('PersonDetails1_txtPostCode').value = postCode;
    if (validatePostcode(postCode)) {
        sm('box', 380, 275);
        if ($('txtFindPostcode2')) {
            postcodeModal = true;
            $('fsPostcode').style.display = 'block';
            selectAll('txtFindPostcode2');
            $('txtFindPostcode2').value = postCode;
            findAddress(postCode);
        } else {
            /*can't use modal dialog, open in situ */
            hm('box');
            postcodeModal = false;
            $('fsPostcode').style.display = 'none';
            $('box').style.display = 'block';
            findAddress(postCode);
        }
    }
}
function findAddress2_Click() {
    $('matchingAddresses').options.length = 0;
    $('noAddresses').innerHTML = '';
    $('showAddresses').style.display = 'none';
    $('noAddresses').style.display = 'none';
    var postCode = $('txtFindPostcode2').value;
    $('txtFindPostcode').value = postCode;
    $('PersonDetails1_txtPostCode').value = postCode;
    if (validatePostcode(postCode)) {
        findAddress(postCode);
    }
}
function findAddress(postCode) {
    if (postCode.length == 0) {
        $('noAddresses').style.display = 'block';
        $('noAddresses').innerHTML = 'Enter a UK Postcode to find your address.';
        $('waitAddresses').style.display = 'none';
        selectAll('txtFindPostcode2');
        return;
    }
    if (pendingEvent != null) {
        clearTimeout(pendingEvent);
    }
    $('waitAddresses').style.display = 'block';
    $('showAddresses').style.display = 'none';
    var url = '/ajax_postcode.aspx' + '?postCode=' + postCode;
    var method = "GET";
    var ajax = xmlHttpRequestObject();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            findAddress_OnResponse(ajax.responseXML);
        }
    }
    pendingEvent = setTimeout('$("waitAddresses2").style.display="block";', 5000)
    ajax.open(method, url, true);
    ajax.setRequestHeader("Connection", "close");
    ajax.send(null);
}
function findAddress_OnResponse(responseXML) {
    if (pendingEvent != null) {
        clearTimeout(pendingEvent);
    }
    $('waitAddresses').style.display = 'none';
    $('waitAddresses2').style.display = 'none';
    var matchingAddresses = $('matchingAddresses');
    var noAddresses = $('noAddresses');
    var xmlDoc = responseXML;
    var results = xmlDoc.getElementsByTagName('Item');
    var i;
    matchingAddresses.options.length = 0;
    noAddresses.innerHTML = '';
    if (results.length == 0) {
        noAddresses.style.display = 'block';
        noAddresses.innerHTML = 'Sorry, no addresses were found for this postcode.';
        if (postcodeModal) {
            selectAll('txtFindPostcode2');
        }
    } else if (results.length == 1) {
        if (results[0].getAttribute('error_number')) {
            $('noAddresses').style.display = 'block';
            noAddresses.innerHTML = 'Sorry, no addresses were found for this postcode.';
            if (postcodeModal) {
                selectAll('txtFindPostcode2');
            }
        } else {
            $('matchingAddresses').value = results[0].getAttribute('id');
            matchingAddresses_Click();
        }
    } else if (results.length > 1) {
        $('showAddresses').style.display = 'block';
        $('noAddresses').style.display = 'none';
        for (i = 0; i < results.length; i++) {
            if (results[i].getAttribute('description')) {
                matchingAddresses.options[matchingAddresses.options.length] = new Option(results[i].getAttribute('description'), results[i].getAttribute('id'));
            }
        }
    }
}
function matchingAddresses_Click() {
    $('waitAddresses').style.display = 'block';
    $('showAddresses').style.display = 'none';
    var addressID = $('matchingAddresses').value;
    var url = '/ajax_postcode.aspx' + '?addressID=' + addressID;
    var method = "GET";
    var ajax = xmlHttpRequestObject();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            matchingAddresses_OnResponse(ajax.responseXML);
        }
    }
    ajax.open(method, url, true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
    ajax.setRequestHeader("Connection", "close");
    ajax.send(null);
}
function matchingAddresses_OnResponse(responseXML) {
    //var matchingAddresses=$('matchingAddresses');
    var xmlDoc = responseXML;
    var result = xmlDoc.getElementsByTagName('Item')[0];
    if (result.getAttribute('error_number')) {
        $('waitAddresses').style.display = 'none';
        $('noAddresses').style.display = 'block';
        $('noAddresses').innerHTML = 'Sorry, no addresses were found for this postcode.';
        if (postcodeModal) {
            selectAll('txtFindPostcode2');
        }
        return;
    }
    $('PersonDetails1_txtAdd1').value = ''
    if (result.getAttribute('organisation_name')) {
        $('PersonDetails1_txtAdd1').value += result.getAttribute('organisation_name') + ', ';
    }
    $('PersonDetails1_txtAdd1').value += result.getAttribute('line1');
    if (result.getAttribute('line2')) {
        $('PersonDetails1_txtAdd2').value = result.getAttribute('line2');
    } else {
        $('PersonDetails1_txtAdd2').value = '';
    }
    if (result.getAttribute('line3')) {
        $('PersonDetails1_txtAdd3').value = result.getAttribute('line3');
    } else {
        $('PersonDetails1_txtAdd3').value = '';
    }
    if (result.getAttribute('line4')) {
        $('PersonDetails1_txtAdd3').value += ', ' + result.getAttribute('line4');
    }
    $('PersonDetails1_txtTown').value = result.getAttribute('post_town');
    $('PersonDetails1_txtCounty').value = result.getAttribute('county');
    if (result.getAttribute('postcode')) {
        $('PersonDetails1_txtPostCode').value = result.getAttribute('postcode');
    }
    if (postcodeModal) {
        hm('box', 550, 355);
    } else {
        $('box').style.display = 'none';
    }
}
function popDependantDdl(strH1Index, ddlH2Container) {
    var strH2ArrayItems;
    var strH2ArrayValues;
    ddlH2Container.options.length = 0;
    if (strH1Index != '0') {
        strH2ArrayItems = eval('arrH2Items_' + strH1Index);
        strH2ArrayValues = eval('arrH2Values_' + strH1Index);
        for (var i = 0; i < strH2ArrayItems.length; i++) {
            ddlH2Container.options[ddlH2Container.options.length] = new Option(strH2ArrayItems[i], strH2ArrayValues[i]);
        }
    }
    else {
        ddlH2Container.options[ddlH2Container.options.length] = new Option('                                                                            ', '0');
    }
}
//3) Email: validation and send from modal dialog box.
function emailWin() {
    sm('box', 550, 355);
    document.getElementById('emailForm').style.display = 'block';
    document.getElementById('emailOutcomeException').style.display = 'none';
    document.getElementById('emailOutcomeSent').style.display = 'none';
    selectAll('emailFrom');
}
function test() {
    alert('a');
}
function emailDept(dept) {
    sm('box', 550, 355);
    /*problem in Safari on Mac: Object refs no longer work after content is rendered in box.
    Check here, if fails return true causes link to open email in new browser window.*/
    if (!$('emailData')) {
        hm('box');
        return true;
    }
    $('emailData').value = dept;
    switch (dept) {
        case 'B':
            $('emailSubject').value = 'Contact the Booking Office';
            $('emailTitle').innerHTML = 'Contact the Booking Office';
            $('introText').innerHTML = 'Complete this form to send a message to the booking office. Please make sure that your email address is correct or we will be unable to reply.';
            break;
        case 'P':
            $('emailSubject').value = 'Contact the Property Department';
            $('emailTitle').innerHTML = 'Contact the Property Department';
            $('introText').innerHTML = 'Complete this form to send a message to the property department. Please make sure that your email address is correct or we will be unable to reply.';
            break;
        case 'I':
            $('emailSubject').value = 'Web site feedback';
            $('emailTitle').innerHTML = 'Web site feedback';
            $('introText').innerHTML = 'Complete this form to feedback comments on our Web site. Please make sure that your email address is correct or we will be unable to reply.';
            break;
    }
    $('emailForm').style.display = 'block';
    $('emailOutcomeException').style.display = 'none';
    $('emailOutcomeSent').style.display = 'none';
    selectAll('yourName');
    return false;
}
function sendEmail() {
    var frm = document.forms['frmEmail'];
    if (validateEmailForm()) {
        var url = "/ajax_email.aspx";
        var method = "POST";
        var postData = emailPostData();
        var ajax = xmlHttpRequestObject();
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
                sendEmail_OnResponse(ajax.responseXML);
            }
        }
        ajax.open(method, url, true);
        ajax.setRequestHeader("Content-type", "application/x-www-form-URLencoded");
        ajax.setRequestHeader("Content-length", postData.length);
        ajax.setRequestHeader("Connection", "close");
        ajax.send(postData);
    }
}
function sendEmail_OnResponse(responseXML) {
    var xmlDoc = responseXML;
    var results = xmlDoc.getElementsByTagName('results')[0];
    var outcome = results.getAttribute('outcome');
    var message = '';
    switch (outcome) {
        case "validation":
            var valErrors = xmlDoc.getElementsByTagName('validation')[0];
            for (v = 0; v <= valErrors.childNodes.length - 1; v++) {
                message += valErrors.childNodes[v].getAttribute('error') + '\n';
            }
            alert(message);
            break;
        case "exception":
            document.getElementById('emailForm').style.display = 'block';
            document.getElementById('emailOutcomeSent').style.display = 'none';
            document.getElementById('emailOutcomeException').style.display = 'block';
            break;
        case "sent":
            document.getElementById('emailForm').style.display = 'none';
            document.getElementById('emailOutcomeSent').style.display = 'block';
            document.getElementById('emailOutcomeException').style.display = 'none';
            _gaq.push(['_trackEvent', 'email', $('emailType').value, 'sent']);
            break;
        default:
    }
}
function validateEmailForm() {
    curFocus = '';
    if ($('emailFrom')) {
        if (stringContainsTags($('emailFrom').value)) {
            alert("The from email address contains restricted characters, please limit your entry to a single email address.")
            selectAll('emailFrom');
            return false;
        }
    }
    if ($('emailTo')) {
        if (stringContainsTags($('emailTo').value)) {
            alert("The to email address contains restricted characters, please limit your entry to a single email address.")
            selectAll('emailTo');
            return false;
        }
    }
    if ($('yourName')) {
        if (stringContainsTags($('yourName').value)) {
            alert("Your name contains restricted characters, please limit your entry to plain text (no html tags).")
            selectAll('yourName');
            return false;
        }
        if ($('yourname').value == '' || $('yourname').value == 'Enter your name') {
            alert("Please enter your name.")
            selectAll('yourName');
            return false;
        }
    }
    if ($('yourEmail')) {
        if (stringContainsTags($('yourEmail').value)) {
            alert("Your email address contains restricted characters, please limit your entry to a single email address.")
            selectAll('yourEmail');
            return false;
        }
        if ($('yourEmail').value == '' || $('yourEmail').value == 'Enter your email address') {
            alert("Please enter your email address.")
            selectAll('yourEmail');
            return false;
        }
    }
    if (stringContainsTags($('emailSubject').value)) {
        alert("The email subject contains restricted characters, please limit your entry to plain text (no html tags).")
        selectAll('emailSubject');
        return false;
    }
    if (stringContainsTags($('emailBody').value)) {
        alert("The email message contains restricted characters, please limit your entry to plain text (no html tags).")
        selectAll('emailBody');
        return false;
    }
    if ($('emailFrom')) {
        if (!validateEmail($('emailFrom').value, 'from')) {
            selectAll('emailFrom');
            return false;
        }
    }
    if ($('emailTo')) {
        if (!validateEmail($('emailTo').value, 'to')) {
            selectAll('emailTo');
            return false;
        }
    }
    return true;
}
function emailPostData() {
    var str = "";
    if ($('emailFrom')) {
        str += 'emailFrom' + "=" + encodeURI($('emailFrom').value) + "&";
    }
    if ($('emailTo')) {
        str += 'emailTo' + "=" + encodeURI($('emailTo').value) + "&";
    }
    if ($('yourName')) {
        str += 'yourName' + "=" + encodeURI($('yourName').value) + "&";
    }
    if ($('yourEmail')) {
        str += 'yourEmail' + "=" + encodeURI($('yourEmail').value) + "&";
    }
    str += 'emailSubject' + "=" + encodeURI($('emailSubject').value) + "&";
    str += 'emailBody' + "=" + encodeURI($('emailBody').value) + "&";
    str += 'emailType' + "=" + encodeURI($('emailType').value) + "&";
    str += 'emailData' + "=" + encodeURI($('emailData').value)
    return str;
}
function formPostData(frm) {
    var str = "";
    for (var i = 0; i < frm.elements.length; i++) {
        var els = frm.elements[i];
        str += els.name + "=" + encodeURI(els.value) + "&";
    }
    str = str.substr(0, (str.length - 1));
    return str;
}
function validateEmail(email, fromto) {
    if (email == "") { return true; }
    var posat = email.indexOf("@");
    var possp = email.indexOf(" ");
    var poscm = email.indexOf(",");
    var ename = email.slice(0, posat);
    var edomain = email.slice(posat + 1)
    if (posat == -1) {
        if (fromto == "from") {
            alert("A valid email address must contain an '@' sign\nPlease re-enter the ''From'' email address")
            return false
        } else if (fromto == "to") {
            alert("A valid email address must contain an '@' sign\nPlease re-enter the ''To'' email address")
            return false
        } else {
            alert("A valid email address must contain an '@' sign.")
            return false
        }
    } else if (possp > -1) {
        if (fromto == "from") {
            alert("A valid email address cannot contain a space\nPlease re-enter the ''From'' email address")
            return false
        } else if (fromto == "to") {
            alert("A valid email address cannot contain a space\nPlease re-enter the ''To'' email address")
            return false
        } else {
            alert("A valid email address cannot contain a space.")
            return false
        }
    } else if (poscm > -1) {
        if (fromto == "from") {
            alert("A valid email address cannot contain a comma\nPlease re-enter the ''From'' email address")
            return false
        } else if (fromto == "to") {
            alert("A valid email address cannot contain a comma\nPlease re-enter the ''To'' email address")
            return false
        } else {
            alert("A valid email address cannot contain a comma.")
            return false
        }
    } else if (email.slice(0, posat) == "") {
        if (fromto == "from") {
            alert("A valid email address must contain a name before the '@' sign\nPlease re-enter the ''From'' email address")
            return false
        } else if (fromto == "to") {
            alert("A valid email address must contain a name before the '@' sign\nPlease re-enter the ''To'' email address")
            return false
        } else {
            alert("A valid email address must contain a name before the '@' sign.")
            return false
        }
    } else if (email.slice(posat + 1) == "") {
        if (fromto == "from") {
            alert("A valid email address must contain a domain name after the '@' sign\nPlease re-enter the ''From'' email address")
            return false
        } else if (fromto == "to") {
            alert("A valid email address must contain a domain name after the '@' sign\nPlease re-enter the ''To'' email address")
            return false
        } else {
            alert("A valid email address must contain a domain name after the '@' sign.")
            return false
        }
    }
    return true
}
//4) Availability: highlighting, synching and validation.
var mCurStopMessage;
var defRentMessage = 'Select your holiday dates to reserve or check the price.';
function resDatesChange() {
    if (document.getElementById('tblAvail')) {
        clearHighlight();
    }
    var dfrom;
    var dto;
    if ($('hdnArrDate')) {
        dfrom = new Date($('hdnArrDate').value);
        dto = new Date($('hdnDepDate').value);
    } else {
        // Fetch  dfrom & dto
        var from = $('CtlAvailability1_hdnFrom').value;
        var to = $('CtlAvailability1_hdnTo').value;

        if (from == "" || to == "") {
            return;
        }
        if ($('txtFrom').innerHTML == "Select your arrival") {
            $('txtFrom').innerHTML = PrettyPrintDate(new Date(from));
        }
        if ($('txtTo').innerHTML == "Select your departure") {
            $('txtTo').innerHTML = PrettyPrintDate(new Date(to));
        }

        var to = $('CtlAvailability1_hdnTo').value;

        dfrom = new Date(from);
        dto = new Date(to);

        var varString = escape(dfrom.getDate() + '/' + (dfrom.getMonth() + 1) + '/' + dfrom.getFullYear() + ',' + dto.getDate() + '/' + (dto.getMonth() + 1) + '/' + dto.getFullYear());

        $('divRent').innerHTML = 'Checking Dates...';
        $('divWarn').innerHTML = '';
        $('divWarn').style.display = 'none';
        var url = "/feeds/pricingFeed.aspx";
        var method = "GET";
        var queryString = '?c=' + document.getElementById('CtlAvailability1_hdnCdrn').value + '&h=' + varString
        var ajax = xmlHttpRequestObject();
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
                resDatesChange_OnResponse(ajax.responseXML);
            }
        }
        ajax.open(method, url + queryString, true);
        ajax.setRequestHeader("Connection", "close");
        ajax.send(null);
    }
    if (document.getElementById('tblAvail') && dfrom) {
        highlightCells(dfrom, dto);
    }
}
function availCalendar_mouseOut() {
    clearHvr();
}
function highlightCells(dfrom, dto, lite) {
    var d = new Date(dfrom.getFullYear(), dfrom.getMonth(), dfrom.getDate());
    if (!dto) {
        dto = dfrom;
    }
    while (d <= dto) {
        s = 'd' + d.getDate() + '-' + (d.getMonth() + 1) + '-' + d.getFullYear();
        if ($(s)) {
            var firstCell = (d.getDate() == dfrom.getDate() && d.getMonth() == dfrom.getMonth());
            var lastCell = (d.getDate() == dto.getDate() && d.getMonth() == dto.getMonth());
            if (lite) {
                addHvr($(s), firstCell, lastCell);
            } else {
                addSel($(s), firstCell, lastCell);
            }
        }
        d.setDate(d.getDate() + 1);
    }
}
var hvrCells = [];
var selCells = [];
function addHvr(cell, first, last) {
    var classType = 'hvr';
    var newClassName;
    if (first) { //first selected cell, need a transition gif.
        newClassName = cell.className.substring(0, 3) + '-' + classType;
    } else if (last) { //last selected cell, need a transition gif.
        newClassName = classType + '-' + cell.className.substring(cell.className.length - 3, cell.className.length)
    } else {
        newClassName = classType;
    }
    cell.noHvrClassName = cell.className;
    cell.className = newClassName;
    hvrCells[hvrCells.length] = cell;
}
function clearHvr() {
    for (i = 0; i < hvrCells.length; i++) {
        if (hvrCells[i]) {
            hvrCells[i].className = hvrCells[i].noHvrClassName;
            hvrCells[i].noHvrClassName = null;
        }
    }
    hvrCells = [];
}
function addSel(cell, first, last) {
    var classType = 'sel';
    var newClassName;
    if (first) { //first selected cell, need a transition gif.
        newClassName = cell.className.substring(0, 3) + '-' + classType;
    } else if (last) { //last selected cell, need a transition gif.
        newClassName = classType + '-' + cell.className.substring(cell.className.length - 3, cell.className.length)
    } else {
        newClassName = classType;
    }
    cell.noSelClassName = cell.className;
    cell.className = newClassName;
    selCells[selCells.length] = cell;
}
function clearSel() {
    for (i = 0; i < selCells.length; i++) {
        if (selCells[i]) {
            selCells[i].className = selCells[i].noSelClassName;
            selCells[i].noSelClassName = null;
        }
    }
    selCells = [];
}
function clearHighlight() {
    if ($('hdnArrDate')) {
    } else {
        $('divRent').innerHTML = defRentMessage;
        $('divWarn').innerHTML = '';
        $('divWarn').style.display = 'none';
        $('dayArrive').innerHTML = '';
        $('dayDepart').innerHTML = '';
    }
    if ($('tblAvail')) {
        clearHvr();
        clearSel();
    }
}
function resDatesChange_OnResponse(responseXML) {
    var result = responseXML.getElementsByTagName('Result').item(0);
    if (result) {
        //if mCurStopMessage is not null the user will receive the message 'mCurStopMessage' when they click the reserve button.
        if (result.getAttribute("CanReserve")) {
            mCurStopMessage = null;
        } else {
            mCurStopMessage = result.getAttribute("WarningMessage") + '.';
        }
        var strHTML = '';
        if (result.getAttribute("ShowRent")) {
            var holidayDesc = result.getAttribute("HolidayDesc");
            var strHRBCost = result.getAttribute("HRBCost");
            var strLRBCost = result.getAttribute("LRBCost");
            strHTML = 'Rent for this ' + holidayDesc + '<br /><div class="divPrice">&pound;' + strHRBCost + '</div>';
            if (strLRBCost) {
                var strMaxAdultsAtLRB = result.getAttribute("LRBMaxAdults");
                if (strMaxAdultsAtLRB) {
                    var strMaxBabiesAtLRB = result.getAttribute("LRBMaxBabies");
                    strHTML = strHTML + '<br/>' + 'Reduced to &pound;' + strLRBCost + ' for parties of ' + strMaxAdultsAtLRB;
                    if (strMaxBabiesAtLRB == 0) {
                    } else {
                        if (strMaxBabiesAtLRB == 1) {
                            strHTML = strHTML + ' + cot'
                        } else {
                            strHTML = strHTML + ' + ' + strMaxBabiesAtLRB + ' cots'
                        }
                    }
                    strHTML = strHTML + ' or less.'
                } else {
                    strHTML = 'Rent for this ' + holidayDesc + '<br /><div class="divPrice">&pound;' + strLRBCost + '</div>';
                }
            }
        }
        document.getElementById('divRent').innerHTML = strHTML;
        var warningMessage = result.getAttribute("WarningMessage");
        if (warningMessage) {
            $('divWarn').innerHTML = warningMessage + '.';
            $('divWarn').style.display = 'block';
            if (result.getAttribute("CanReserve")) {
                $('divWarn').innerHTML += ' You can reserve these dates but we will check with the Owner before confirming whether they can take your booking.'
            }
        } else {
            $('divWarn').innerHTML = '';
        }
        if (result.getAttribute("ShortBreak")) {
            $('divWarn').innerHTML += '<br/>' + '<a href="javascript:popInfo3(\'/popups/shortbreaks.aspx\',550,650)">Information on Short Breaks &gt;</a>'
        }
        if (!document.getElementById('tblAvail')) {
            if (result.getAttribute("CheckAvailability")) {
                $('divWarn').innerHTML += '<br/>' + '<a href="javascript:__doPostBack(\'checkAvail\',\'\');">Check Availability &gt;</a>'
            }
        }
    }
}
function setAvailFromDate(day, mon) {
    if (mon > 12) {
        alert("Please select an arrival date in the current year.");
    } else {

        document.getElementById('txtFrom').innerHTML = PrettyPrintDate(new Date($('CtlAvailability1_hdnYear').value, mon - 1, day));
        document.getElementById('CtlAvailability1_hdnFrom').value = PrintDate(new Date($('CtlAvailability1_hdnYear').value, mon - 1, day));
    }
}
function setAvailToDate(day, mon) {
    document.getElementById('txtTo').innerHTML = PrettyPrintDate(new Date($('CtlAvailability1_hdnYear').value, mon - 1, day));
    document.getElementById('CtlAvailability1_hdnTo').value = PrintDate(new Date($('CtlAvailability1_hdnYear').value, mon - 1, day));
}
function optionDate(day, mon) {
    if (document.getElementById('txtFrom')) {
        var from = document.getElementById('txtFrom').innerHTML;
        var to = document.getElementById('txtTo').innerHTML;
        var firstMon = parseInt(_dMin.getMonth());
        mon = parseInt(mon) + firstMon;
        if (from == "Select your arrival") {
            setAvailFromDate(day, mon)
        } else if (to == "Select your departure") {
            setAvailToDate(day, mon)
        } else {
            if (confirm("Are you sure you want to clear both dates and start again?") == true) {
                document.getElementById('txtFrom').innerHTML = 'Select your arrival';
                document.getElementById('txtTo').innerHTML = 'Select your departure';
                document.getElementById('CtlAvailability1_hdnFrom').value = '';
                document.getElementById('CtlAvailability1_hdnTo').value = '';
            }
        }
        resDatesChange();
    }
}
function hoverDate(day, mon) {
    if (document.forms[0].CtlAvailability1_hdnFrom && document.getElementById('tblAvail')) {
        var fromday = $('CtlAvailability1_hdnFrom').value;
        var today = $('CtlAvailability1_hdnTo').value;
        var firstMon = parseInt(_dMin.getMonth());
        if (fromday == "" && today == "") {
            var dfrom = new Date($('CtlAvailability1_hdnYear').value, (parseInt(mon) + firstMon - 1), day);
            var dto = dfrom;
            clearHvr();
            highlightCells(dfrom, dto, true);
        } else if (fromday != "" && today == "") {
            var dfrom = new Date($('CtlAvailability1_hdnYear').value, (new Date(fromday).getMonth()), (new Date(fromday).getDate()));
            today = day;
            tomon = parseInt(mon) + firstMon;
            var dto = new Date($('CtlAvailability1_hdnYear').value, (tomon - 1), (today));
            clearHvr();
            highlightCells(dfrom, dto, true);
        }
    }
}
function validateAvail() {
    if (mCurStopMessage) {
        alert(mCurStopMessage + '\n\nIf you require any assistance you can contact our Booking Office as follows:\nTelephone: 01326 555555\nEmail: enquiries@classic.co.uk');
        return false;
    } else {

        if (document.forms[0].CtlAvailability1_hdnFrom.value == "") {
            alert("Please complete the arrival date.");
            return false;
        }
        if (document.forms[0].CtlAvailability1_hdnTo.value == "") {
            alert("Please complete the departure date.");
            return false;
        }
        var from = document.forms[0].CtlAvailability1_hdnFrom.value;
        var to = document.forms[0].CtlAvailability1_hdnTo.value;
        var dfrom = new Date(from);
        var dto = new Date(to);
        var lhol = parseInt((dto - dfrom) / (24 * 60 * 60 * 1000))
        if (lhol == 0) {
            alert("The arrival date can not be the same as the departure date.");
            return false;
        } else if (lhol < 0) {
            alert("The departure date must be after the arrival date.");
            return false;
        } else if (lhol > 28) {
            alert("The maximum length of a holiday is 28 days (4 weeks).");
            return false;
        }
        return true;
    }
}
function resetAvail() {
    $('divRent').innerHTML = defRentMessage;
    $('divWarn').innerHTML = '';
    $('divWarn').style.display = 'none';
    document.getElementById('txtFrom').innerHTML = 'Select your arrival';
    document.getElementById('txtTo').innerHTML = 'Select your departure';
    document.getElementById('CtlAvailability1_hdnFrom').value = '';
    document.getElementById('CtlAvailability1_hdnTo').value = '';
    resDatesChange();
    return false;
}
function showWait() {
    document.getElementById('divHide').style.display = 'block';
    setTimeout('document.images["pbar"].src = "/media/progbar.gif"', 500);
}
function dispCardHolder() {
    if (document.forms['frmBalance'].rdoCardHolder) {
        var rdoState;
        for (var i = 0; i < document.forms['frmBalance'].rdoCardHolder.length; i++) {
            if (document.forms['frmBalance'].rdoCardHolder[i].checked) {
                rdoState = document.forms[0].rdoCardHolder[i].value;
            }
        }
        if (rdoState == 1) {
            document.getElementById('altCardHolder').style.display = 'block';
        } else {
            document.getElementById('altCardHolder').style.display = 'none';
        }
    }
}
function setCard(strCType) {
    var ddl = document.getElementById('ddlCardType');
    var len = ddl.length - 1;
    var selIndex = -1;
    var i;
    for (i = 0; i <= len; i++) {
        if (ddl.options[i].value == strCType) {
            selIndex = i;
        }
    }
    ddl.selectedIndex = selIndex;
    dispSurcharge();
}
function dispSurcharge() {
    var strCType = document.getElementById('ddlCardType').value;
    var lblShowSurcharge;
    var fltAmountDue;
    var lblShowTotal;
    if (document.getElementById('lblSurcharge')) {
        lblShowSurcharge = document.getElementById('lblSurcharge');
        fltAmountDue = parseFloat(document.getElementById('lblBalDue').innerHTML);
        lblShowTotal = $('lblTotal');
    } else {
        if (document.getElementById('lblDepSurcharge')) {
            lblShowSurcharge = document.getElementById('lblDepSurcharge');
            fltAmountDue = parseFloat(document.getElementById('lblDepToPay').innerHTML);
            lblShowTotal = $('lblDepTotal');
        }
    }
    lblShowTotal2 = $('lblTotalToCharge');

    //Old surcharge of 1% applies for holidays booked before 1st october 2011
    //New surcharge of 1.25% applies to all new bookings

    if ((strCType == 'MCC' || strCType == 'VC') && fltAmountDue > 50) {
        if (lblShowSurcharge && lblShowTotal) {
            var dfrom;
            var dStart;
            dnNewSurcStart = new Date(2012, 0, 1);
            if ($('hdnArrDate')) {
                dfrom = new Date($('hdnArrDate').value);
            } else {
                dfrom = new Date();
            }
            if (dfrom < dnNewSurcStart) {
                lblShowSurcharge.innerHTML = (fltAmountDue * 0.01).toFixed(2);
                lblShowTotal.innerHTML = (fltAmountDue * 1.01).toFixed(2);
                lblShowTotal2.innerHTML = '&pound;' + (fltAmountDue * 1.01).toFixed(2);
            }
            else {
                lblShowSurcharge.innerHTML = (fltAmountDue * 0.0125).toFixed(2);
                lblShowTotal.innerHTML = (fltAmountDue * 1.0125).toFixed(2);
                lblShowTotal2.innerHTML = '&pound;' + (fltAmountDue * 1.0125).toFixed(2);
            }
        }
    } else {
        if (lblShowSurcharge) {
            lblShowSurcharge.innerHTML = '0.00';
            lblShowTotal.innerHTML = fltAmountDue.toFixed(2);
            lblShowTotal2.innerHTML = '&pound;' + fltAmountDue.toFixed(2);
        }
    }

    if (strCType == 'MO') {
        $('maestroOnly').style.display = 'block';
    } else {
        $('maestroOnly').style.display = 'none';
    }
}
function val() {
    if (document.forms[0].ddlCardType.selectedIndex == 0) {
        alert('You must select your Card Type.');
        document.forms[0].ddlCardType.focus();
        return false;
    }
    if (document.forms[0].txtCardNo.value == '') {
        alert('You must complete your Card Number.');
        document.forms[0].txtCardNo.focus();
        return false;
    }
    if (document.forms[0].ddlExpMonth.selectedIndex == 0 || document.forms[0].ddlExpYear.selectedIndex == 0) {
        alert('You must complete the Card Expiry Date.');
        document.forms[0].ddlExpMonth.focus();
        return false;
    }
    if ((document.forms[0].ddlFromMonth.selectedIndex == 0 || document.forms[0].ddlFromYear.selectedIndex == 0) && (document.forms[0].txtIssueNo.value == '')) {
        alert('You must complete either the Issue Number or Card Valid From Date.');
        document.forms[0].ddlExpMonth.focus();
        return false;
    }
    if (document.forms[0].txtSecurityCode.value == '') {
        alert('You must complete your Security Code.');
        document.forms[0].txtSecurityCode.focus();
        return false;
    }
    return true;
}
//5) Form Level validation  
function validateBroReq() {
    if (validatePerson() != true) {
        return false;
    }
    if (validateContacts(1) != true) {
        return false;
    }
    return true;
}
function validateResStage1() {
    if (validatePerson() != true) {
        return false;
    }
    if ($('PersonDetails1_OtherCon_txtHomeTel')) {
        if (validateAdditionalContacts(1) != true) {
            return false;
        }
    } else {
        if (validateContacts(2) != true) {
            return false;
        }
    }
    return true;
}
function validateResStage2() {
    /*Show the wait screen whilst the reservation request is processed server side.*/
    sm('procBox', 450, 275);
    setTimeout('document.images["pbar"].src = "/media/progresscircle.gif"', 300);
    return true;
}
function validateBookStage1() {
    if (validatePerson() != true) {
        return false;
    }
    if (atleastoneContacts() != true) {
        alert("Please provide at least one email address or telephone number on which we may contact you.");
        return false;
    }
    if (allPartyMembers() != true) {
        return false;
    }
    return true;
}
function validateBookStage2() {
    if (validateCard() != true) {
        return false;
    }
    if (document.forms[0].CtlDeclaration1_chkBookCond.checked == false) {
        alert("Please note that you must check the booking condtions\ndeclaration box before we can accept an option");
        return false;
    }
    return true;
}
function validateBalance() {
    if (validateCard() != true) {
        return false;
    }
    return true;
}
function validateFeedback() {
    if (document.forms[0].CtlFeedback1_txtName.value.length == 0) {
        alert("Please complete your name");
        return false;
    }
    if (document.forms[0].CtlFeedback1_txtEmail.value.length == 0) {
        alert("Please complete your email address");
        return false;
    }
}
function validateSendMail() {
    if (document.forms[0].txtFromAddr.value.length == 0) {
        alert('Please complete your email address.');
        return false;
    }
    if (document.forms[0].txtToAddr.value.length == 0) {
        alert('Please complete the recipients email address.');
        return false;
    }
    if (validateEmail(document.forms[0].txtFromAddr.value, 'from') != true) {
        return false;
    }
    if (validateEmail(document.forms[0].txtToAddr.value, 'to') != true) {
        return false;
    }
    return true;
}
function validateAdvRes() {
    if (validatePerson() != true) {
        return false;
    }
    if (validateContacts(1) != true) {
        return false;
    }
    if (document.forms[0].lstFromDay.value == 0 || document.forms[0].lstFromMonth.value == 0) {
        alert("Please complete your intended arrival date.");
        return false;
    }
    if (document.forms[0].lsttoDay.value == 0 || document.forms[0].lsttoMonth.value == 0) {
        alert("Please complete you intended departure date.");
        return false;
    }
    return true;
}
function validateLogin() {
    if (document.forms[0].Login1_txtTRN.value == "") {
        alert("Please enter your personal reference number");
        document.forms[0].Login1_txtTRN.focus();
        return false;
    }
    if (document.forms[0].Login1_txtBRN.value == "") {
        alert("Please enter your booking reference number");
        document.forms[0].Login1_txtBRN.focus();
        return false;
    }
    if (isInteger(document.forms[0].Login1_txtTRN.value) != true) {
        alert("Your personal reference number must be numeric.");
        document.forms[0].Login1_txtTRN.focus();
        return false;
    }
    if (isInteger(document.forms[0].Login1_txtBRN.value) != true) {
        alert("Your booking reference number must be numeric.");
        document.forms[0].Login1_txtBRN.focus();
        return false;
    }
    return true;
}
//6) Fieldset level Validation
function allPartyMembers() {
    for (var i = 0; i <= 16; i++) {
        if (document.getElementById('PartyMembers1_txtNameA' + i)) {
            if (document.getElementById('PartyMembers1_txtNameA' + i).value == '') {
                alert("Please complete the details of the other members in your party, you can enter 'TBC' if you do not yet know who is accompanying you.");
                return false;
            }
        }
        if (document.getElementById('PartyMembers1_txtNameB' + i)) {
            if (document.getElementById('PartyMembers1_txtNameB' + i).value == '') {
                alert("Please provide the name of all babies in your party, you can enter 'TBC' if you are not yet sure!");
                return false;
            } else {
                if (document.getElementById('PartyMembers1_txtAgeB' + i).value == '') {
                    alert("Please provide the age (in months) of all babies in your party, you can enter 'TBC' if you are not yet sure!");
                    return false;
                }
            }
        }
    }
    return true;
}
function validateCard() {
    if (document.forms[0].CardDetails1_ddlCardType.value == "Please Select") {
        alert("Please select your card type");
        return false;
    }
    if (document.forms[0].CardDetails1_txtCardNo.value == "") {
        alert("Pleae enter your card number");
        return false;
    }
    if (document.forms[0].CardDetails1_ddlExpMonth.value == "--" || document.forms[0].CardDetails1_ddlExpYear.value == "--") {
        alert("Please complete the expiry date");
        return false;
    }
    if (document.forms[0].CardDetails1_ddlFromMonth.value == "--" && document.forms[0].CardDetails1_ddlFromYear.value != "--") {
        alert("Valid From Date incorrectly completed");
        return false;
    }
    if (document.forms[0].CardDetails1_ddlFromMonth.value != "--" && document.forms[0].CardDetails1_ddlFromYear.value == "--") {
        alert("Valid From Date incorrectly completed");
        return false;
    }
    if (document.forms[0].CardDetails1_ddlFromMonth.value == "--" && document.forms[0].CardDetails1_ddlFromYear.value == "--" && document.forms[0].CardDetails1_txtIssueNo.value == "") {
        alert("Please provide either the valid from date or an issue number");
        return false;
    }
    return true;
}
function validatePerson() {
    if (document.forms[0].PersonDetails1_txtTitle.value == "") {
        alert("Please enter your title");
        document.forms[0].PersonDetails1_txtTitle.focus();
        return false;
    }
    if (document.forms[0].PersonDetails1_txtInitials.value == "") {
        alert("Please enter your initials");
        document.forms[0].PersonDetails1_txtInitials.focus();
        return false;
    }
    if (document.forms[0].PersonDetails1_txtSurname.value == "") {
        alert("Please enter your surname");
        document.forms[0].PersonDetails1_txtSurname.focus();
        return false;
    }
    if (document.forms[0].PersonDetails1_txtAdd1.value == "") {
        alert("Please enter the first line of your address");
        document.forms[0].PersonDetails1_txtAdd1.focus();
        return false;
    }
    if (document.forms[0].PersonDetails1_txtPostCode.value == "") {
        alert("Please enter your Postcode or ZIP");
        document.forms[0].PersonDetails1_txtPostCode.focus();
        return false;
    }
    return true;
}
function validateContacts(numRequired) {
    var numCompleted = 0;
    numCompleted += (($('PersonDetails1_txtEMail').value == "") ? 0 : 1)
    numCompleted += (($('PersonDetails1_txtHomeTel').value == "") ? 0 : 1)
    numCompleted += (($('PersonDetails1_txtWorkTel').value == "") ? 0 : 1)
    numCompleted += (($('PersonDetails1_txtMobile').value == "") ? 0 : 1)
    if (numCompleted < numRequired) {
        alert("Please provide at least " + numRequired + " way" + ((numRequired > 1) ? "s" : "") + " in which we may contact you.");
        return false;
    }
    if (validateEmail($('PersonDetails1_txtEMail').value) == false) {
        selectAll('PersonDetails1_txtEMail');
        return false
    }
    return true;
}
function validateAdditionalContacts(numRequired) {
    var numCompleted = 0;
    numCompleted += (($('PersonDetails1_OtherCon_txtHomeTel').value == "") ? 0 : 1);
    numCompleted += (($('PersonDetails1_OtherCon_txtWorkTel').value == "") ? 0 : 1);
    numCompleted += (($('PersonDetails1_OtherCon_txtMobile').value == "") ? 0 : 1);
    if (numCompleted < numRequired) {
        alert("Please provide at least " + numRequired + " telephone number" + ((numRequired > 1) ? "s" : "") + " we can use to contact you.");
        return false;
    }
    return true;
}
function highlightBedroom(bedroomNumber, over) {
    if ($('bedroomDescription')) {
        if ($('bedroomDesc' + bedroomNumber)) {
            var bedroomDesc = $('bedroomDesc' + bedroomNumber);
            if (over) {
                bedroomDesc.initialClassName = bedroomDesc.className;
                bedroomDesc.className = bedroomDesc.className + ' highlightBedroom';
            } else {
                bedroomDesc.className = bedroomDesc.initialClassName;
            }
        }
    }
}
