var stateCodeAutoSet = true;
var countryCodeAutoSet = true;
var search_searchForm = new WebForm();


function favProp_onSubmit(v,c) {
    search_searchForm.resetErrors();

	var displayBlock =  "favErrorContainer_"+c
	search_dateStatus = search_checkDates(v, displayBlock, "fav_", c);

    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}



function simpleForm_onSubmit(v,d) {
    search_searchForm.resetErrors();
    search_dateStatus = search_checkDates(v);
    if(v.complexSearchField.value == d || v.complexSearchField.value == "")
        search_searchForm.addError("search_errorBlock","search_simpleSearchRequiredError" );
    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}

function standardCityForm_onSubmit(t,v) {
    // By default my fav page does not need city state country validations, so skipping that part for my fav page
    if(yuiDom.getElementsByClassName('locationBlock')[0] != null && yuiDom.getElementsByClassName('locationBlock')[0].style.display != 'block') {
            search_dateStatus = search_checkDates(t);
    } else {
            if((!stateCodeAutoSet || !countryCodeAutoSet)&&t.stateCode.value == "") {
              city_onBlur(t);
            }
            search_searchForm.resetErrors();
            search_locationStatus = search_getLocationStatus(t);
            search_dateStatus = search_checkDates(t);
            if(document.getElementById("locationWrapper").className != "hide"){
	            if(t.city.value == v) search_city_onFocus(t);
	            if ((search_locationStatus =="BLANK")) {
	                search_searchForm.addError("search_errorBlock","search_searchCriteriaRequiredError" );
	            }
	            if ((search_locationStatus =="INVALID_US_SEARCH") ) {
	                search_searchForm.addError("search_errorBlock","search_toGeneralUSSearchError" );
	            }
	            if ((search_locationStatus =="MISSING_STATE_US_SEARCH") ) {
	                search_searchForm.addError("search_errorBlock","search_stateProvinceRequiredError" );
	            }
	            if ((search_locationStatus =="CITY_ONLY") ) {
	                search_searchForm.addError("search_errorBlock","search_countryRequiredForCitySearchError" );
	            }
	            if(t.countryCode.value == "US" && t.stateCode.value == "" && (t.city.value == "" || t.city.value == v)) {
	              search_searchForm.addError("search_errorBlock","search_toGeneralUSSearchError" );
	            }
	            if(t.countryCode.value == "" && t.stateCode.value == "" && (t.city.value == "" || t.city.value == v)) {
	              search_city_onFocus(t);
	              search_searchForm.addError("search_errorBlock","search_searchCriteriaRequiredError" );
	            }
            }
    }

    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}

function hotelForm_onSubmit(f) {
    search_searchForm.resetErrors();
    if (f.hotelName.value == "") {
        search_searchForm.addError("search_errorBlock","search_hotelNameRequiredError");
    } else if (f.hotelName.value.length<=3 ||
        "sheraton".indexOf(f.hotelName.value.toLowerCase())!=-1 ||
        "four points".indexOf(f.hotelName.value.toLowerCase())!=-1 ||
        "westin".indexOf(f.hotelName.value.toLowerCase())!=-1 ||
        "luxury collection".indexOf(f.hotelName.value.toLowerCase())!=-1 ||
        "le m�ridien".indexOf(f.hotelName.value.toLowerCase())!=-1 ||
        "le meridien".indexOf(f.hotelName.value.toLowerCase())!=-1) {
        search_searchForm.addError("search_errorBlock","search_hotelNameTooVagueError");
    }
     if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
 }

function airportForm_onSubmit(f) {
    search_searchForm.resetErrors();
    search_dateStatus = search_checkDates(f);
    if (f.airportCode.value == "") {
        search_searchForm.addError("search_errorBlock","search_airportCodeRequiredError");
    }
    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}

function conventionForm_onSubmit(f) {
    search_searchForm.resetErrors();
    dateStatus = search_checkDates(f);
    if (f.conventionCenterName.selectedIndex == 0) {
        search_searchForm.addError("search_errorBlock","search_conventionCenterRequiredError");
    }
    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}

function search_city_onFocus(t) {
    t.city.value = "";
    if (stateCodeAutoSet) { t.stateCode.selectedIndex = 0; }
    if (countryCodeAutoSet) { t.countryCode.selectedIndex = 0; }
}

function city_onBlur(t) {
    a = isIn(t.city.value.toLowerCase(),topCities)
    if (a != false) {
        search_setDropDown(a[1],t.stateCode);
        search_setDropDown(a[2],t.countryCode);
        //country_onChange();
        stateCodeAutoSet = true;
        countryCodeAutoSet = true;
    }
}

function stateCode_onChange(t) {
    c = false;
    if(isIn(t.stateCode.value,us_states)) {
        c = "US";
    } else if(isIn(t.stateCode.value,ca_prov)) {
        c = "CA";
    } else if(isIn(t.stateCode.value,misc)) {
        c = "US";
    }
    if (c != false) {
        search_setDropDown(c,t.countryCode);
    }
    countryCode_onChange(t);
    stateCodeAutoSet = false;
}

function countryCode_onChange(t) {
    if ((t.countryCode[t.countryCode.selectedIndex].value != "US") && (t.countryCode[t.countryCode.selectedIndex].value != "CA")) {
        search_setDropDown("",t.stateCode);
    }
    stateCodeAutoSet = false;
    countryCodeAutoSet = false;
}

function isIn(elt, list){
    for(var i=0; i < list.length; i++){
        var tempArray = list[i].split(":")
        if( tempArray[0] == elt ){
            return tempArray;
        }
    }
    return false;
}
function search_setDropDown(v,dd) {
    for (i = 0; i < dd.options.length ; i++ ) {
        if ( dd.options[i].value == v ) {
            dd.selectedIndex = i;
            return true
        }
    }
    return false;
 }

function search_checkDates(f,errorBlock,idPrefix,endText) {

    if ((f.arrivalDate.value == dateFormatString) && (f.departureDate.value == dateFormatString)) {
        return "DATES_NOT_SET";
    }	
	if(errorBlock == undefined){
		errorBlock = "search_errorBlock"
		idPrefix = "~search_"
		endText = "";
	}
 
    var checkIn = new validDate(f.arrivalDate);
    var checkOut = new validDate(f.departureDate);
    if (!(checkIn.valid) && (!checkOut.valid) ) {
        search_searchForm.addError(errorBlock,idPrefix+"ciAnddepartureDatesInvalidError"+endText, "arrivalDateLabel","departureDateLabel")
    } else if (!checkIn.valid ) {
        search_searchForm.addError(errorBlock,idPrefix+"arrivalDateInvalidError"+endText,"arrivalDateLabel")
    } else if (!checkOut.valid ) {
        search_searchForm.addError(errorBlock,idPrefix+"departureDateInvalidError"+endText,"departureDateLabel")
    } else 	if ( (checkIn.valid) & (checkOut.valid)  ) {
        var datesDelta = checkIn.diffDate( checkOut.d);
        var nowDelta = checkIn.diffDate(new Date());
        if (nowDelta > 0 ) {
            search_searchForm.addError(errorBlock,idPrefix+"checkInEarlierThanTodayError"+endText,"arrivalDateLabel");
        } else if (nowDelta < -548) {
            search_searchForm.addError(errorBlock,idPrefix+"bookToFarInFutureError"+endText,"arrivalDateLabel");
            search_searchForm.addError()
        } else if (datesDelta < 0) {
            search_searchForm.addError(errorBlock,idPrefix+"departureBeforeArrivalError"+endText,"departureDateLabel");
        } else if (datesDelta > 90) {
            search_searchForm.addError(errorBlock,idPrefix+"maximumLengthStayExceededError"+endText, "arrivalDateLabel","departureDateLabel");
        } else if (datesDelta < 1) {
            search_searchForm.addError(errorBlock,idPrefix+"arrivalEqualsDepartureError"+endText, "arrivalDateLabel","departureDateLabel");
        }
    }
    return "";
}





function search_arrivalDate_onFocus(f) {
    var checkIn = new validDate(f.arrivalDate);
    if ( !checkIn.valid ) { f.arrivalDate.value="";}
}

function search_arrivalDate_onBlur(f) {
    var checkIn = new validDate(f.arrivalDate);
    if ( checkIn.valid ) {
        checkIn.setField();
        var checkOut = validDate(f.departureDate);
        if (checkOut.valid ) { before = (checkIn.diffDate(checkOut.d) <= 0);}
        if ( (! (checkOut.valid)) || before) {
            checkOut.setD(checkIn.d);
            checkOut.nextDay();
            checkOut.setField();
        }
    } else {
        f.arrivalDate.value=dateFormatString;
    }
}
function search_departureDate_onFocus(f) {
    var checkOut = new validDate(f.departureDate);
    if ( !checkOut.valid ) { f.departureDate.value="";}
}
function search_departureDate_onBlur(f) {
    var checkOut = new validDate(f.departureDate);
    if ( checkOut.valid ) { checkOut.setField(); } else {f.departureDate.value=dateFormatString;}
}
function getAirportCode_onClick() {
    window.open('/dp/en_US/common/search/airportLookUp.jsp?element=airportForm.airportCode&brand=meetings','AIRPORT','width=400,height=490,scrollbars=yes')
    return false;
}

function setDefaultText(defaultText,focus,element) {
    if (focus) {
        if (element.value == defaultText) {
            element.value = "";
        }
    } else {
        if (element.value == "") {
            element.value = defaultText;
        }
    }
}

function appendToSelect(select, value, content) {
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    opt.appendChild(document.createTextNode(content));
    select.appendChild(opt);
}

var conventionCenterValue;
var req;

function conventionCenterState_onChange() {
    var conCenterState = document.getElementById("conventionCenterState");
    var conCenterCountry = document.getElementById("conventionCenterCountry");

    //conCenterState.value = ""
    if (conCenterState.value != "") {
        if (isIn(conCenterState.value, us_states)) {
            conCenterCountry.value = "US";
        } else if (isIn(conCenterState.value, ca_prov)) {
            conCenterCountry.value = "CA";
        } else if (isIn(conCenterState.value, misc)) {
            conCenterCountry.value = "US";
        }

        //  constructXMLQuery();
        var conCenterStateValue = document.getElementById("conventionCenterState").value;
        var conCenterCountryValue = document.getElementById("conventionCenterCountry").value;

        var url = "/service/search/lookupservlet?" + "country=" + conCenterCountryValue + "&state=" + conCenterStateValue + "&lookupType=conCenter";
        // loadXMLDoc(url);

        elem = document.getElementById("conventionCenter");
        clearElemChildren(elem);
        appendToSelect(elem, '', 'Loading...');
        elem.disabled = true;

        // branch for native XMLHttpRequest object
        if (window.XMLHttpRequest) {
            req = new XMLHttpRequest();
            req.onreadystatechange = processReqChangeConventionCenter;
            req.open("GET", url, true);
            req.send(null);
            // branch for IE/Windows ActiveX version
        } else if (window.ActiveXObject) {

            req = new ActiveXObject("Microsoft.XMLHTTP");
            if (req) {
                req.onreadystatechange = processReqChangeConventionCenter;
                req.open("GET", url, true);
                req.send();
            }
            // The browser cannot support dynamic City loading - say so
        } else {
            clearElemChildren(elem);
            appendToSelect(elem, '', 'Feature Not Supported By Your Browser');
        }

    }

}


function conventionCenter_onChange(elem) {
    conventionCenterValue = elem.value;
}
function constructXMLQuery() {
    var conCenterStateValue = document.getElementById("conventionCenterState").value;
    var conCenterCountryValue = document.getElementById("conventionCenterCountry").value;

    var url = "/service/search/lookupservlet?" + "country=" + conCenterCountryValue + "&state=" + conCenterStateValue + "&lookupType=conCenter";
    loadXMLDoc(url);
}

function loadXMLDoc(url) {
    elem = document.getElementById("conventionCenter");
    clearElemChildren(elem);
    appendToSelect(elem,'', 'Loading...');
    elem.disabled=true;

    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = processReqChange;
        req.open("GET", url, true);
        req.send(null);
        // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = processReqChange;
            req.open("GET", url, true);
            req.send();
        }
        // The browser cannot support dynamic City loading - say so
    } else {
        clearElemChildren(elem);
        appendToSelect(elem,'', 'Feature Not Supported By Your Browser');
    }
}
function clearElemChildren(elem) {
    while (elem.childNodes.length > 0) {
        elem.removeChild(elem.firstChild);
    }
}
function processReqChangeConventionCenter() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
            var elem = document.getElementById('conventionCenter');
            while (elem.childNodes.length > 0) {
                elem.removeChild(elem.firstChild);
            }
            elem.disabled = false;
            buildConventionCenterList();
            // We had an error - keep the element disabled and write an error
        } else {
            elem = document.getElementById('conventionCenter');
            clearElemChildren(elem);
            appendToSelect(elem,'', 'An Error Occured');
        }
    }
}

function buildConventionCenterList() {
    var select = document.getElementById("conventionCenter");
    var items = req.responseXML.getElementsByTagName("ConventionCenter");
    appendToSelect(select,'', pleaseSelect);
    for (var i=0; i<items.length; i++) {
        appendToSelect(select,items[i].childNodes[0].nodeValue, items[i].childNodes[0].nodeValue);
    }
    if (items.length == 0) {
        clearElemChildren(elem);
        appendToSelect(select,"", noneFound);
    }

    if (conventionCenterValue != "") {
        n=0;
        while(  n < select.options.length) {
            if( select.options[n].value == conventionCenterValue ){
                select.selectedIndex = n;
                break;
            }
            n++;
        }
    }
    conventionCenterValue="";
}

function appendToSelect(select, value, content) {
    var opt;
    opt = document.createElement("option");
    opt.value = value;
    opt.appendChild(document.createTextNode(content));
    select.appendChild(opt);
}



function search_getLocationStatus(t) {
    cityEmpty = (t.city.value =="");
    stateProvinceEmpty = (t.stateCode.value == "");
    countryEmpty = (t.countryCode.value=="");
    countryUS = (t.countryCode.value=="US");

    if ((!cityEmpty) && (!stateProvinceEmpty) && (!countryEmpty)) { return "COMPLETE_SEARCH"; }
    if ((!stateProvinceEmpty) && (!countryEmpty)) { return "STATE_SEARCH"; }
    if ((!cityEmpty) && (!countryUS) && (!countryEmpty)) { return "NON_US_CITY_SEARCH"; }
    if ((!countryEmpty) && (!countryUS) ) { return "NON_US_COUNTRY_SEARCH"; }
    if ((stateProvinceEmpty) && (countryUS) ){ return "INVALID_US_SEARCH"; }
    if ((!cityEmpty) && (stateProvinceEmpty) && (countryEmpty)) { return "CITY_ONLY"; }
    if ((cityEmpty) && (stateProvinceEmpty) && (countryEmpty)) { return "BLANK"; }
    return "INCOMPLETE";
}

var displayBlock = undefined;
var displayText = undefined;
var displayEnd = "";

function simpleSearch_onFocus(t) {
    t.value = "";
}

function openHotelExplorer(obj) {
    var selectBox = obj;
    var item = selectBox.selectedIndex;
    window.location.href = selectBox[item].value;
}

function jaStandardCityForm_submit(t) {
    search_searchForm.resetErrors();
    search_checkDates(t);
    countryEmpty = (t.country.selectedIndex == 0);
    stateEmpty = (t.country.value == "US" && t.stateProvince.selectedIndex==0);
    if(document.getElementById("locationWrapper").className != "hide"){
    if(countryEmpty) {
        search_searchForm.addError("search_errorBlock","search_countryRequiredForCitySearchError" );
    }
    if(stateEmpty) {
        search_searchForm.addError("search_errorBlock","search_stateProvinceRequiredError" );
    }
    }
    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
	}
}

function zhCityForm_submit(t) {
    search_searchForm.resetErrors();
    search_checkDates(t);
    if(searchFormType=="pinyin"){
         if(!checkPinyinCityDefaultValueChange())  {
            t.cityField.value="";
        }
     }
    countryEmpty = (t.country.selectedIndex == 0);
    stateEmpty = (t.country.value == "US" && t.stateProvince.selectedIndex==0);
    if(countryEmpty) {
        search_searchForm.addError("search_errorBlock","search_countryRequiredForCitySearchError" );
    }
    if(stateEmpty) {
        search_searchForm.addError("search_errorBlock","search_stateProvinceRequiredError" );
    }
    if (search_searchForm.hasErrors()) {
		search_searchForm.showErrors();
		return false;
	} else {
		return true;
	}
}

function addressForm_onSubmit(t) {
    search_searchForm.resetErrors();

    search_locationStatus = search_getLocationStatus(t);
    zipCodeStatus = getZipCodeStatus(t);
    addressEntered = (t.address.value != "");

    if (zipCodeStatus == "INVALID") {
        search_searchForm.addError("search_errorBlock", "~search_invalidZipCodeError","zipLabel");
    }

    if ((search_locationStatus =="INVALID_US_SEARCH")) {
        search_searchForm.addError("search_errorBlock", "~search_stateProvinceRequiredError", "stateProvinceError");
    }

    if ((search_locationStatus == "BLANK")) {
        search_searchForm.addError("search_errorBlock", "search_searchCriteriaRequiredError");
    }

    if (addressEntered) {
        if ((t.city.value =="") && (t.stateCode.value == "")) {
            search_searchForm.addError("search_errorBlock", "~search_cityAndStateRequiredError");
        } else if(search_locationStatus=="STATE_SEARCH") {
            search_searchForm.addError("search_errorBlock", "~search_cityRequiredError");
        } else if(search_locationStatus=="INVALID_US_SEARCH") {
            search_searchForm.addError("search_errorBlock", "~search_stateRequiredError");
        }
    }

    if (search_searchForm.hasErrors()) {
        search_searchForm.showErrors();
        return false;
    } else {
        return true;
    }
}

function getZipCodeStatus(t) {
    var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    if(t.zipCode.value == ''){
        return "BLANK";
    } else if(!objRegExp.test(t.zipCode.value)){
        return "INVALID";
    } else {
        return "VALID"
    }
}
