//
// First we have general js functions that apply independent of the booking tab

function bmlPopup(url) {
    bookingPopup(url, "bml_popup", "500", "500");
}

function privacyPopup(url) {
    bookingPopup(url, "privacy_popup", "700", "590");
}

function bookingPopup(url, label, screenX, width) {
    var w = window.open(url, label, "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width=" + width + ",height=350,screenX=" + screenX + ",screenY=110,top=300,left=100");
    w.focus();
}

function openAlamoImage(url) {
    var w = window.open(url, '_blank', 'width=800,height=600,menubar=yes,location=yes,scrollbars=yes,status=yes,toolbar=yes,resizable=yes');
    w.focus();
}

function disableAll(a, value) {
    for (var i = 0; i < a.length; ++i) {
        var t = a[i].type;
        if (t == 'text' || t == 'select-one' || t == 'radio' || t == 'hidden' || t == 'checkbox') {
            a[i].disabled = value;
        }
    }
}

function disableElements(object, value) {
    if (dom) {
        disableAll(object.getElementsByTagName("input"), value);
        disableAll(object.getElementsByTagName("select"), value);
    }
    else if (allobject) {
        var a = object.all;
        for (var i = 0; i < a.length; ++i) {
            var n = a[i].tagName.toLowerCase();
            if (n == 'input' || n == 'select') {
                var arr = new Array(a[i]);
                disableAll(arr, value);
            }
            else {
                disableElements(a[i], value);
            }
        }
    }
    // else NN4 which does not disable form fields
}

function doReformPhone(field, paymentcountry) {
    var value = trim(getValue(field));
    var newValue = value.replace(/\D/g, "");
    if (isPaymentCountryUsaorCanada(paymentcountry) && isUSStylePhone(value, newValue)) {
        if (newValue.length == 11 && newValue.charAt(0) == "1") {
            newValue = newValue.substring(1);
        }
        newValue = newValue.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
        field.value = newValue;
    }
}

function isUSStylePhone(value, newValue) {
    if (newValue.charAt(0) == '0') {
        return false;
    }
    if (newValue.length == 10) {
        return true;
    }
    if (newValue.length == 11 && newValue.charAt(0) == '1') {
        return true;
    }
    return false;
}

function isPaymentCountryUsaorCanada(value) {
    if (value == 'US' || value == 'CA' || value == 'USA'  || value == 'CAN') {    	
    	return true;	
    }	    
    return false;
}
    
// Reformat the credit card number given the field names of the credit card number
//  and the credit card type field.
// Some assumptions are made:
//  * the supplied fields are type='text'    
//  * the three arrays have been built from the Java CreditCardType class' information

// Here is what the arrays would look like if typed in:
/*
// number of digits in the card number based on the card type
var cardDigits = new Array();
cardDigits["A"] = 15;
cardDigits["D"] = 16;
cardDigits["I"] = 14; <%-- diners --%>
cardDigits["M"] = 16;
cardDigits["V"] = 16;
cardDigits["V13"] = 13;

// pattern of digits in the card number, where to put spaces 
var cardPattern = new Array();
cardPattern["A"] = new Array(4,6,5);
cardPattern["D"] = new Array(4,4,4,4);
cardPattern["I"] = new Array(4,6,4);
cardPattern["M"] = new Array(4,4,4,4);
cardPattern["V"] = new Array(4,4,4,4);
cardPattern["V13"] = new Array(4,3,3,3); // this is the information for the older Visa cards

// translate beginning digits to a card type 
var cardBegin = new Array();
cardBegin[3] = "A"; // Diners is also 3 but this will partly work as is
cardBegin[4] = "V";
cardBegin[5] = "M";
cardBegin[6] = "D";
*/

function doReformCC(typeField, field) {
    var ccType = typeField.value;
    
    var value = trim(getValue(field));
    var newValue = value.replace(/\D/g, "");
    
    if (!ccType) { // missing card type, guess based on 1st digit
        ccType = cardBegin[parseInt(newValue.charAt(0), 10)];
    }
    
    if (ccType == "V" && newValue.length == 13) { // special case for old? 13 digit visa card
        ccType = "V13";
    }
    
    // If its a valid number with the right number of digits for the type, reformat it
    if (mod10(newValue) && (cardDigits[ccType] == newValue.length)) {
        newValue = divideCC(newValue, ccType);
        field.value = newValue;
    }
}

// Divide the digits into groups based on the credit card type
function divideCC( cardNumber, ccType) {
    var digits = cardPattern[ccType];
    var newNumber = "";
    if (digits) {
        var col = 0;
        for (i = 0 ; i < digits.length ; ++i) {
            newNumber += cardNumber.substring(col, col + digits[i]);
            col += digits[i];
            if (i+1 < digits.length) {
                newNumber += " ";
            }
        }
        return newNumber;
    }
    else {
        return cardNumber;
    }
}

// LUHN Formula for validation of credit card numbers.
function mod10( cardNumber ) { 
    var ar = new Array( cardNumber.length );
    var i = 0,sum = 0;

    for( i = 0; i < cardNumber.length; ++i ) {
        ar[i] = parseInt(cardNumber.charAt(i));
    }
    for( i = ar.length -2; i >= 0; i-=2 ) {
        ar[i] *= 2;                        
        if( ar[i] > 9 ) ar[i]-=9;          
    }                                      

    for( i = 0; i < ar.length; ++i ) {
        sum += ar[i];                        
    }
    return (((sum%10)==0)?true:false);      
}

function getValue(field) {
    var value = "";
    if ((field.type == 'hidden' ||
        field.type == 'text' ||
        field.type == 'textarea' ||
        field.type == 'file' ||
        field.type == 'password') &&
        field.disabled == false) {

        value = field.value;
    }
    return value;
}

// Trim whitespace from left and right sides of s.
function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

// Tell if the string is empty    
function empty(str) {
    return str.match(/^\s*$/);
}

function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

// test for objects
(document.layers) ? layerobject=true : layerobject=false;
(document.all) ? allobject = true: allobject = false;
(document.getElementById) ? dom = true : dom = false;

// change the visibilty of an object on the document
function changeVisibility(id, action) {
    switch (action) {
        case "show":
            if (layerobject)
                document.layers[''+id+''].display = "inline";
            else if (allobject)
                document.all[''+id+''].style.display = "inline";
            else if (dom) 
                document.getElementById(''+id+'').style.display = "inline";  
            break;
        case "hide":
            if (layerobject)
                document.layers[''+id+''].display = "none";
            else if (allobject)
                document.all[''+id+''].style.display = "none";
            else if (dom)
                document.getElementById(''+id+'').style.display = "none";
            break;
        default:
            return;
    }
    return;
}

function getById(id) {
    if (layerobject)
        return document.layers[''+id+''];
    else if (allobject)
        return document.all[''+id+''];
    else if (dom)
        return document.getElementById(''+id+'');
}
 
function getObj(name)
{
  if (document.getElementById) {
    this.obj = document.getElementById(name);
    this.style = document.getElementById(name).style;
  }
  else if (document.all) {
    this.obj = document.all[name];
    this.style = document.all[name].style;
  }
  else if (document.layers) {
    this.obj = getObjNN4(document,name);
    this.style = this.obj;
  }
}

function getObjNN4(obj, name)
{
    var x = obj.layers;
    var foundLayer;
    for (var i=0;i<x.length;i++) {
        if (x[i].id == name)
            foundLayer = x[i];
        else if (x[i].layers.length)
            var tmp = getObjNN4(x[i],name);
        if (tmp) foundLayer = tmp;
    }
    return foundLayer;
}
 
/* this will be null until mousedown on the checkbox on tab3 and then
   set back to null on mouseup. If there is a down without an up, the
   value remains but there isn't a user scenario where this matters. */
var checkboxClickState = null;
   
function checkEmailAddressEntry(emailAddressField, copyItineraryField) {
    copyItineraryField.checked = !empty(emailAddressField.value);
    //addDebug( "field change1: " + checkboxClickState);
    if (checkboxClickState != null) {
        checkboxClickState = !copyItineraryField.checked;
        //addDebug( "field change2: " + checkboxClickState);
    }
}

function beginCheckClick(checkbox) {
    checkboxClickState = checkbox.checked;
    var message = "down: " + checkboxClickState;
    //addDebug(message);
    return true;
}

function endCheckClick(checkbox) {
    //addDebug ( "click: " + checkboxClickState);
    if (checkboxClickState != null) {
        checkbox.checked = !checkboxClickState;
        checkboxClickState = null;
    }
    return true;
}

/* To use this method you should have a <div id="debugMessages"> on
   the page. The message text will be added to the end of that <div>
   in its own <div> */
function addDebug(message) {
    var div = document.getElementById('debugMessages');
    if (div) {
	    var objHTML, objText;
	    objHTML = document.createElement('DIV');
	    div.appendChild(objHTML);
	    objText = document.createTextNode(message);
	    objHTML.appendChild(objText);
	    delete objHTML;
	    delete objText
    }
}

/* This function is used in step 3 and registration page, to remove if any state/province
is selected and if the country selected is not USA or Canada

The code for mexico on registration page is MEX and code for the same in step 3 page is MX
The code for USA on registration page is USA and code for the same in step 3 page is US
The code for Canada on registration page is CAN and code for the same in step 3 page is CA
*/
function onSelectCountryRegistration() {
	if (document.all.Country.value != 'USA' && document.all.Country.value != 'CAN') {
    	document.all.StateProvince.value = "";
  }
}

function onSelectCountryStep3() {
	if (document.all.paymentCountry.value != 'US' && document.all.paymentCountry.value != 'CA') {
    	document.all.paymentStateProvince.value = "";
  }
}

function createCookie(name,value,days) {
    if (days) {
    	var date = new Date();
    	date.setTime(date.getTime()+(days*24*60*60*1000));
    	var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/; domain=.hotels.com"
}

