// Example: obj = findObj("image1");
function findObj(theObj, theDoc) {
    var p, i, foundObj;
    if (!theDoc) theDoc = document;
    if ((p = theObj.indexOf("?")) > 0 && parent.frames.length) {
        theDoc = parent.frames[theObj.substring(p + 1)].document;
        theObj = theObj.substring(0, p);
    }
    if (!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
    for (i = 0; !foundObj && i < theDoc.forms.length; i++)
    foundObj = theDoc.forms[i][theObj];
    for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
    foundObj = findObj(theObj, theDoc.layers[i].document);
    if (!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
    return foundObj;
}

// Check if a form object has a value in it,  supply a warning text if it has no value and return false
function checkFormObject(objName, inMessage, DisplayInDiv) {
    var obj = document.getElementById(objName);
    if (obj.value == "") {
        obj.focus();
        var WarningObj = document.getElementById(DisplayInDiv);
        if (WarningObj.innerHTML == '') {
            $('#' + DisplayInDiv).html('<strong>Please enter</strong> <br/>' + inMessage);
        }
        else {
            $('#' + DisplayInDiv).html(WarningObj.innerHTML + '<br/>' + inMessage);
        }
        return false;
    }
    return true;
}
// Check if a form object has a value in it,  supply a warning text if it has no value and return false
function checkFormObjectNoFocus(objName, inMessage, DisplayInDiv) {
    var obj = document.getElementById(objName);
    if (obj.value == "") {
        var WarningObj = document.getElementById(DisplayInDiv);
        if (WarningObj.innerHTML == '') {
            WarningObj.innerHTML = '<strong>You must complete the following to continue</strong> <br/>' + inMessage
        }
        else {
            WarningObj.innerHTML = WarningObj.innerHTML + '<br/>' + inMessage
        }
        return false;
    }
    return true;
}
// Check if a form object has a value in it,  supply a warning text if it has no value and return false
function checkConfSpecialCases() {
    var warningText = '';
    if ($('#cboTCOnArrival').val() != 'Not Required' && $('#txtTCOnArrival').val() == 0) {
        warningText = warningText + 'You have requested tea and coffee on arrival but have not specified a quantity<br/>'
    };
    if ($('#cboTCAM').val() != 'Not Required' && $('#txtTCAM').val() == 0) {
        warningText = warningText + 'You have requested tea and coffee during the morning but have not specified a quantity<br/>'
    };
    if ($('#cboTCPM').val() != 'Not Required' && $('#txtTCPM').val() == 0) {
        warningText = warningText + 'You have requested tea and coffee during the afternoon but have not specified a quantity<br/>'
    };
    if ($("input[name='optLunchType']:checked").val() == undefined && $('#txtNoOfLunches').val() != 0) {
        warningText = warningText + 'You have requested lunches,  you need to select a lunch style as well<br/>'
    };
    if ($("input[name='optDinner']:checked").val() == undefined && $('#txtNoOfDinners').val() != 0) {
        warningText = warningText + 'You have requested dinner,  you need to select a dining style as well<br/>'
    };
    if (warningText != '') {
        return '<br/>' + warningText;
    } else {
        return ''
    } // WarningText not ''
} // function


// Check if a form object EXISTS,  if it does it must have a value in it,  supply a warning text if it has no value and return false
function checkFormObjectIfAvailable(objName, inMessage, DisplayInDiv) {
    if (document.getElementById(objName) != null) {
        var obj = document.getElementById(objName);
        if (obj.value == "") {
            obj.focus();
            var WarningObj = document.getElementById(DisplayInDiv);
            if (WarningObj.innerHTML == '') {
                WarningObj.innerHTML = '<strong>The following must be completed</strong> <br/>' + inMessage
            }
            else {
                WarningObj.innerHTML = WarningObj.innerHTML + '<br/>' + inMessage
            }
            return false;
        }
        return true;
    } else {
        return true;
    }
}

// Check if a form object has a value in it,  supply a warning text if it has no value and return false
function checkDateFormat(objName, DisplayInDiv) {
    var dateInput = $('#' + objName).val();
    if (dateInput.length != 10 && dateInput.length != 0) {
		$('#' + DisplayInDiv).append('<br/>Your arrival date is incorrectly formatted,  you entered (' + dateInput + ')  please don`t type dates,  use the pop out calendar provided instead');
        return false;
    }
    return true;
}


// Check if a form object EXISTS,  if it does it must have a value in it,  supply a warning text if it has no value and return false
function checkFormObjectIfAvailableV2(objName, DisplayInDiv) {
    if (document.getElementById(objName) != null) {
        var obj = document.getElementById(objName);
        if (obj.value == "") {
            if (obj.type!='hidden'){
				obj.focus();
			}
            var FieldLabel = $("label[for=" + objName + "]").text();
            var WarningObj = document.getElementById(DisplayInDiv);
            if (WarningObj.innerHTML == '') {
                WarningObj.innerHTML = 'Please complete the following <br/> <br/>' + FieldLabel
            }
            else {
                WarningObj.innerHTML = WarningObj.innerHTML + '<br/>' + FieldLabel
            }
            return false;
        }
        return true;
    } else {
        return true;
    }
}

// Check if a form object EXISTS,  if it does it must have a value in it,  supply a warning text if it has no value and return false
// This version is used where a hidden field holds the actual varified value the user has typed
// therefore it strips "checked" from the element name when looking up the matching lable
// used mainly in cost centre validation scenarios
function checkFormObjectIfAvailableV3(objName, DisplayInDiv) {
    if (document.getElementById(objName) != null) {
        var obj = document.getElementById(objName);
        if (obj.value == "") {
            if (obj.type!='hidden'){
				obj.focus();
			}
			var FieldLabel = $("label[for=" + objName.replace('Checked','') + "]").text();
            var WarningObj = document.getElementById(DisplayInDiv);
            if (WarningObj.innerHTML == '') {
                WarningObj.innerHTML = 'Please complete the following <br/> <br/>' + FieldLabel
            }
            else {
                WarningObj.innerHTML = WarningObj.innerHTML + '<br/>' + FieldLabel
            }
            return false;
        }
        return true;
    } else {
        return true;
    }
}



// Check if a form object has a value in it,  supply a warning text if it has no value and return false
function checkFormLocationOrLongLat(inMessage, DisplayInDiv) {
    var obj2 = document.getElementById('PCVerifyResult');
    if (obj2.innerHTML != 'OK') {
        var WarningObj = document.getElementById(DisplayInDiv);
        if (WarningObj.innerHTML == '') {
            WarningObj.innerHTML = '<strong>Please enter</strong> <br/>' + inMessage
        } else {
            WarningObj.innerHTML = WarningObj.innerHTML + '<br/>' + inMessage
        }
        return false;
    } else {
        return true;
    }
}


function ResetValidationErrors()
//Hide this DIV if we have been there before, also remove its contents
{
    $('div.inntelWarningArea').hide();
    var WarningObj = document.getElementById('ValidationErrors');
    WarningObj.innerHTML = ''
}


function resetValidationErrorsCASE(inDivID)
//Hide this DIV if we have been there before, also remove its contents
// This is for Login.asp Registered Users
{
    $('div.inntelWarningArea').hide();
    var WarningObj = document.getElementById(inDivID);
    WarningObj.innerHTML = ''
}


function IsNumeric(strString)
//  check for valid numeric strings	
{
    var strValidChars = "0123456789.-";
    var strChar;
    var blnResult = true;
    if (strString.length == 0) return false;
    //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++) {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1) {
            blnResult = false;
        }
    }
    return blnResult;
}


function CheckVal(inControlName) {
    var TheControl = findObj(inControlName)
    if (TheControl.value.length == 0) {
        alert("Please enter a value between 0 and 9.");
        TheControl.value = 0;
    }
    else if (IsNumeric(TheControl.value) == false) {
        alert("Please check - you have entered a non numeric value!");
        TheControl.value = 0;
    }
}


function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57)) return false;
    return true;
}


function randomString() {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = 8;
    var randomstring = '';
    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }
    document.randform.randomfield.value = randomstring;
}



function addEvent(obj, evType, fn, useCapture) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        alert("Handler could not be attached");
    }
}


function isNumberKeyV2(evt)
//this check for numeric only and allows decimals and backspace
{
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if ((charCode == 46) || (charCode == 8) || (charCode > 47 && charCode < 58)) return true;
    return false;
}


function left(str, n) {
    if (n <= 0) return "";
    else if (n > String(str).length) return str;
    else return String(str).substring(0, n);
}


function right(str, n) {
    if (n <= 0) return "";
    else if (n > String(str).length) return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}


function DisplayWaitingDialog() {
    var ran_number = Math.floor(Math.random() * 3) + 1;
    var myRand = Math.floor(Math.random() * 5000);
    var swPage = 'SearchWait' + ran_number + '.asp?cb=' + myRand;
    $('#LoadingWait').load(swPage);
    $('#LoadingWait').dialog({
        autoOpen: false,
        position: 'top',
        width: 650,
        modal: true,
        open: function (event, ui) {
            $('select').hide();
        },
        beforeclose: function (event, ui) {
            $('select').show();
        }
    });
    $('#LoadingWait').dialog('open');
} //-->


// Global function as a variable to handle poping up the rate rules for a given Booking ID
var glbFuncReviewBookingNoRateRules = function (inBookingID) {
    var MyRand = Math.floor(Math.random() * 5000);
    var $rrrDiv = $('#jqRRDetails');
    var i
    $rrrDiv.html('<div align="center"><img src="/images/ajax-loader.gif"/><h2 align="center">Contacting hotel for booking rules</span></h2><p align="center">Please wait...</p></div>');
    $.ajax({
        url: 'AJAXAccomExistingBookingRateRules.asp',
        data: 'BookingID=' + inBookingID,
        dataType: 'json',
        cache: false,
        success: function (data) {
            $rrrDiv.html('<table width=500 class="tablesorter" id="tblRateRules"><thead><tr><th>Item</th><th>Details</th></tr></thead><tbody></tbody></table>');
            var i = 0;
            var rrArray = [];
            var dlen = data.length;
            for (var a = 0; a < dlen; a += 1) {
                if (data[a].data.length > 0) {
                    rrArray[i++] = '<tr><td>';
                    rrArray[i++] = data[a].dataTitle.replace('.', ' ');
                    rrArray[i++] = '</td><td>';
                    rrArray[i++] = data[a].data;
                    rrArray[i++] = '</td></tr>';
                };
            } // For loop
            $('#tblRateRules tbody').append(rrArray.join(''));
            $rrrDiv.dialog({
                autoOpen: false,
                position: 'top',
                bgiframe: true,
                minHeight: 400,
                width: 550,
                modal: true,
                title: 'Rate Rules',
                buttons: {
                    "Close": function () {
                        $rrrDiv.html('');
                        $(this).dialog("close");
                        $(this).dialog("destroy");
                    }
                } //buttons
            });
            $rrrDiv.dialog('open');
        }
    }); //ajax
} // glbFuncDisplayPopOverHotel


// Global function as a variable to handle poping up Last rate rules where needed
var glbFuncReviewLastRateRules = function () {
    var MyRand = Math.floor(Math.random() * 5000);
    var $rrrDiv = $('#jqRRDetails');
    $rrrDiv.html('<div align="center"><img src="/images/ajax-loader.gif"/><h2 align="center">Contacting hotel for booking rules</span></h2><p align="center">Please wait...</p></div>');
    $rrrDiv.load('Accom_DisplayRateRulesV2.asp?MyCB=' + MyRand + '&Review=TRUE');
    $rrrDiv.dialog({
        autoOpen: false,
        position: 'top',
        bgiframe: true,
        minHeight: 400,
        width: 950,
        modal: true,
        title: 'Rate Rules',
        buttons: {
            "Close": function () {
                $('#jqRRDetails').html('');
                $(this).dialog("close");
                $(this).dialog("destroy");
            }
        } //buttons
    });
    $rrrDiv.dialog('open');
} // glbFuncDisplayPopOverHotel


// Global function as a variable to handle poping up hotel details to book from
var glbFuncDisplayPopOverHotel = function (x) {
    $.ajax({
        url: 'Accom_SingleHotelChoice.asp',
        data: x,
        dataType: 'html',
        cache: false,
        success: function (data) {
            $('#FullHotelDisplay').html(data);
            $('#FullHotelDisplay').dialog({
                autoOpen: false,
                modal: true,
                position: 'top',
                stack: true,
                width: 800,
                close: function (event, ui) {
                    $(this).dialog('destroy');
                }
            }); //FullHotelDisplay .Dialog
            $('#FullHotelDisplay').dialog('open');
            $('.RatePlanYetToQuery').each(function (index) {
                var HotelID = $('input:hidden[name|=txtAjaxHotelID]', this).val();
                var SubsLimit = $('input:hidden[name|=txtAjaxSubsLimit]', this).val();
                var PegsCode = $('input:hidden[name|=txtHotelCodeToQuery]', this).val();
                var $ThisDiv = $('#RatePlanToQuery' + HotelID);
                var MyRand = Math.floor(Math.random() * 5000);
                $ThisDiv.removeClass('RatePlanYetToQuery').addClass('HotelAvail').html('Loading Rates <img src="images/ajax-loaderTrans.gif"></img>');
                $.get('AJAXAccomSingleSAQuery.asp', 'MyCB=' + MyRand + '&PegsCode=' + PegsCode + '&SubsLimit=' + SubsLimit + '&HotelID=' + HotelID, function (data) {
                    $ThisDiv.html(data);
                    $('#HotelRateTable' + HotelID).tablesorter({
                        sortList: [
                            [2, 0]
                        ],
                        headers: {
                            0: {
                                sorter: false
                            },
                            1: {
                                sorter: false
                            },
                            3: {
                                sorter: false
                            },
                            4: {
                                sorter: false
                            }
                        }
                    });
                    //Hide all but the first three rows,  they are now the cheapest
                    $('#HotelRateTable' + HotelID + ' TR').hide();
                    $('#HotelRateTable' + HotelID + ' thead').show();
                    $('#HotelRateTable' + HotelID + ' TR.NonDepositRate').slice(0, 4).show();
                    /// Get our Hotel No to link to
                    var hotelNo = $('#lnkHotelNo' + HotelID).attr('name');
                    var hotelName = $('#lblHotelNo' + HotelID).text()
                    var hotelDist = $('#lblHotelDistance' + HotelID).text()
                    //Now get the 1st row from the table and put into the summary at top of the page
                    var noOfResults = $('#HotelRateTable' + HotelID + ' tr').length - 1;
                    var noOfDepositResults = $('#HotelRateTable' + HotelID + ' tr .HideDepositRate').length;
                    if (noOfResults > 0 && noOfDepositResults != noOfResults) {
                        var summaryResult = noOfResults - noOfDepositResults + ' room types'
                        var GBPCheapestRate = $('#HotelRateTable' + HotelID + ' .NonDepositRate:eq(1)>td:eq(2) .GBPGuideRateRAW').text();
                        var hotelCheapestRate = $('#HotelRateTable' + HotelID + ' .NonDepositRate:eq(1)>td:eq(2) .LocalGuideRateRAW').text();
                    } else if (noOfResults != 0 && noOfDepositResults > 0) {
                        var summaryResult = noOfDepositResults + ' deposit rates only'
                        var GBPCheapestRate = 'NA'
                        var hotelCheapestRate = 'Not Available'
                    } else {
                        var summaryResult = 'Not Available'
                        var GBPCheapestRate = 'NA'
                        var hotelCheapestRate = 'Not Available'
                    }
                    if ($('div.HotelHeader').length == hotelNo) {
                        // Setup a custom sort algorytm for our Summary table
                        $.tablesorter.addParser({
                            // set a unique id         
                            id: 'priceSort',
                            is: function (s) {
                                // return false so this parser is not auto detected             
                                return false;
                            },
                            format: function (s) {
                                if (isNaN(s)) {
                                    // format your data for normalization             
                                    return s.toLowerCase().replace(/na/, 9999.99);
                                } else {
                                    return s
                                } // isNaN
                            },
                            // set type, either numeric or text        
                            type: 'numeric'
                        });
                        //Sort the table
                        $('#tblPricingProgress').tablesorter({
                            headers: {
                                0: {
                                    sorter: false
                                },
                                5: {
                                    sorter: 'priceSort'
                                }
                            },
                            sortList: [
                                [5, 0]
                            ]
                        });
                    }
                });
            }); // Div RatePlanTOQuery
        } //function
    }); // ajax					
} // glbFuncDisplayPopOverHotel