var us_states = [ "AL","AK","AP","AZ","AR","CA","CO","CT","DE","DC","FL","GA","HI","ID","IL",
	      		  "IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV",
	      		  "NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX",
	      		  "UT","VT","VA","WA","WI","WV", "WI","WY" ];
var ca_prov = [ "AB","BC","LB","MB","NB","NL","NWT","NS","NU","ON","PI","PE","QC","SK","YT" ];
var misc = [ "AS", "GU", "FM", "MH", "MP", "PW", "PR", "VI" ];

var stateProvinceAutoSet = true;      
var countryAutoSet = true;
var searchForm = new WebForm();
// declare the form to validate, can be (and is) overwritten on including JSP
var f = document.searchForm;

function searchForm_onSubmit() {
	searchForm.resetErrors();

    checkLocationFields();
	searchForm.collapseErrors("multipleError");

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

function checkLocationFields() {
	locationStatus = getLocationStatus();
	isAddressSearch = (f.searchType.value == "address")
	if (!isAddressSearch) {
		if (locationStatus =="BLANK") {
			searchForm.addError("~searchCriteriaRequiredError", "stateProvinceError", "countryError" );
			return;
		}
		if (locationStatus == "CITY_ONLY") {
			searchForm.addError("~countryRequiredForCitySearchError", "countryError" );
			return;
		}
		if (locationStatus == "INVALID_US_SEARCH") {
			searchForm.addError("~toGeneralUSSearchError","stateProvinceError" );
			return;
		}
	} else {
		if ((locationStatus =="INVALID_US_SEARCH") && (!addressEntered)) {
			searchForm.addError("~searchCriteriaRequiredError", "stateProvinceError" );
			return;
		}		
	}
}
function getLocationStatus() {
	cityEmpty = (f.city.value =="");
	stateProvinceEmpty = (f.stateProvince.value == "");
	countryEmpty = (f.country.value=="");
	countryUS = (f.country.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";
}
function getZipCodeStatus() {
	var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	if(f.postalCode.value == ''){
		return "BLANK";
	} else if(!objRegExp.test(f.postalCode.value)){
		return "INVALID";
	} else {
		return "VALID"
	}
}

function rateRange_onChange() {
	if (f.country[f.country.selectedIndex].value == "US") {
		f.rateRange.disabled = false;
	} else {
		f.rateRange.disabled = true;
		f.rateRange.selectedIndex = 0;
	}
}

function setDropDown(v,dd) {
	for (i = 0; i < dd.options.length - 1; i++ ) {
		if ( dd.options[i].value == v ) {
			dd.selectedIndex = i;
			return true
		}
	}
	return false;
}

function stateProvince_onChange() {
	c = false;
	if(isIn(f.stateProvince.value,us_states)) {
		c = "US";
	} else if(isIn(f.stateProvince.value,ca_prov)) {
		c = "CA";
	} else if(isIn(f.stateProvince.value,misc)) {
		c = "US";
	}
	if (c != false) {
		setDropDown(c,f.country);
	}
	stateProvinceAutoSet = 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 searchTab_onClick(searchAction, isLoggedIn) {
	searchForm.resetErrors();
	f.searchAction.value = searchAction;
	var t = (searchAction == 'findRooms')
	document.getElementById('rightSearchTab').className = t ? "faded" : "selected";
	document.getElementById('leftSearchTab').className = t ? "selected" : "faded";
	document.getElementById('roomInfo').style.display= t ? "" : "none";

	document.getElementById('redeemLoggedOut').style.display = (!isLoggedIn && (!t)) ? "block" : "none";
	document.getElementById('standardForm').style.display = (! (!isLoggedIn && (!t))) ? "block" : "none";
}

function searchType_onClick(searchType) {
	searchForm.resetErrors();
	f.searchType.value = searchType;
	document.getElementById('cityToggle').className = (searchType == "city") ? "toggleHREFSelected" : "toggleHREF";
	document.getElementById('favoritesToggle').className = (searchType == "favorite") ? "toggleHREFSelected" : "toggleHREF";
	var byF = (searchType == "favorite")
	document.getElementById('byLocationBlock').style.display = byF ? "none" : "block";
	document.getElementById('byFavoriteBlock').style.display = byF ? "block" : "none";
	if (!byF) {
		var t = (searchType == "city");
		document.getElementById('byLocationBlock').style.display = "none";
		if (!t) {f.country.selectedIndex = 1;}
		document.getElementById('byLocationBlock').style.display = "block";
		rateRange_onChange();
	} else {
		f.rateRange.disabled = true;
		f.rateRange.selectedIndex = 0;
	}
}

function advancedSearch_onClick() {
	f.searchAction.value = "advanced";
	if (f.sendRedirect.value != null){
		f.sendRedirect.value = "true";
	}
	f.submit();
}

function advancedSearchForm_onSubmit() {

   if(f.city.value=='(Enter city)') {
       f.city.value="";
   }
   if(f.address){
       if (f.address.value=='(Enter address)') {
           f.address.value="";
       }
   }
   if (f.hotelName.value=='(Hotel name)') {
       f.hotelName.value="";
   }
   if(f.zipCode){
        if(f.zipCode.value=='(Enter ZipCode)') {
            f.zipCode.value="";
        }
   }
   if(f.airportCode.value=='(Enter city)') {
       f.airportCode.value="";
   }
    searchForm.resetErrors();
	if (searchType=="city") {
        f.action = "/pro/search/results/city_advanced.html";
		checkDates();
		locationStatus = getLocationSearchStatus();
		if ((locationStatus =="BLANK")) {
			searchForm.addError("searchCriteriaRequiredError" );
		}
		if ((locationStatus =="INVALID_US_SEARCH") ) {
			searchForm.addError("toGeneralUSSearchError" );
		}
		if ((locationStatus =="MISSING_STATE_US_SEARCH") ) {
			searchForm.addError("stateProvinceRequiredError" );
		}
		if ((locationStatus =="CITY_ONLY") ) {
			searchForm.addError("countryRequiredForCitySearchError" );
		}
	}
	if (searchType=="address") {
		f.action = "/pro/search/results/address_advanced.html";
		//city_onBlur();
		checkDates();
		zipCodeStatus = getZipCodeStatus();
		locationStatus = getLocationSearchStatus();
		if (zipCodeStatus == "INVALID") {
			searchForm.addError("invalidZipCodeError", "zipCodeLabel");
		} else if (zipCodeStatus == "BLANK") {
			if ((locationStatus =="BLANK")) {
				searchForm.addError("searchCriteriaRequiredError" );
			}
			if ((locationStatus =="INVALID_US_SEARCH") ) {
				searchForm.addError("toGeneralUSSearchError" );
			}
			if ((locationStatus =="MISSING_STATE_US_SEARCH") ) {
				searchForm.addError("stateProvinceRequiredError" );
			}
			if ((locationStatus =="CITY_ONLY") ) {
				searchForm.addError("countryRequiredForCitySearchError" );
			}
		}
	}
	if (searchType=="hotelName") {
		f.action = "/pro/search/results/hotel_name.html";
		document.searchForm.departureDate.value = dateFormatString;
		document.searchForm.arrivalDate.value = dateFormatString;
		if ((f.hotelName.value == "") || (f.hotelName.value=="(Hotel Name)"))  {
			searchForm.addError("hotelNameRequiredError");
		}
	}
	if (searchType=="airportCode") {
		f.action = "/pro/search/results/airport_advanced.html";
		checkDates();
		if (f.airportCode.value == "") {
			searchForm.addError("airportCodeRequiredError");
		}
	}

    if (searchType=="conventionName") {

        f.action = "/pro/search/results/convention_center.html";
		checkDates();

	}

    if (searchForm.hasErrors()) {

        searchForm.showErrors();
		return false;
	} else {
        return true;
	}
}
function getLocationSearchStatus() {
	cityEmpty = (f.city.value =="");
	stateProvinceEmpty = (f.stateProvince.value == "");
	countryEmpty = (f.country.value=="");
	countryUS = (f.country.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) && (!cityEmpty) ){ return "MISSING_STATE_US_SEARCH"; }
	if ((stateProvinceEmpty) && (countryUS) ){ return "INVALID_US_SEARCH"; }
	if ((!cityEmpty) && (stateProvinceEmpty) && (countryEmpty)) { return "CITY_ONLY"; }
	if ((cityEmpty) && (stateProvinceEmpty) && (countryEmpty)) { return "BLANK"; }
	return "INCOMPLETE";
}
var globaTabName;
var allBlocksArray = ["cityField", "country", "optionsContainer", "address", "zipCode", "airportBlock", "message", "hotelName", "conventionName", "datesContainer", "searchWithin", "conventionCenterState"];

function tab_onClick(tabName) {

    allBlocksArray.forEach(displayProNone);
    allBlocksArray.forEach(function(block){
        setClass(block, "");
    });

    displayBlock("container3");
    displayBlock("iATAContainer");
    searchForm.resetErrors();

    document.getElementById("Radius").name="airportRadius";
    f.stateProvince.onchange=changedStateProv;

    var tempArray;
    switch(tabName){
        case "city":
            searchType="city";
            tempArray = ["cityField", "country", "optionsContainer","datesContainer","conventionCenterState"];
            setClass("cityTab", "selected");
            break;
        case "address":
            searchType="address";
            tempArray = ["cityField", "country", "optionsContainer","datesContainer", "searchWithin", "conventionCenterState"];  //No address and zip code for Japanese and Chinese
            setClass("addressTab", "selected");
            break;
        case "airport":
            searchType="airportCode";
            tempArray = ["airportBlock","datesContainer"];
            setClass("airportTab", "selected");
            break;
        case "hotelName":
            searchType="hotelName";
            tempArray = ["message","hotelName"];
            setClass("hotelNameTab", "selected");
            break;
        case "conventionName":
            searchType="conventionName";
            tempArray = ["conventionName", "datesContainer", "searchWithin", "conventionCenterState"];
            setClass("conventionNameTab", "selected");
            f.stateProvince.onchange = conventionCenterState_onChange;
            f.stateProvince.disabled = false;
            globaTabName = tabName;
            document.getElementById("Radius").name="conventionRadius";
            initConventionCenter()
            break;
    }
    tempArray.forEach(displayProBlock);
    return false;
}
var conventionCenterValue;
var req;
var conventionCenterState_onChange = function() {
    var conCenterState = f.stateProvince;
	//var conCenterCountry = document.getElementById("conventionCenterCountry");
    var conCenterCountry = f.country;

    //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";
		}
		constructXMLQueryForConventionCenter();
	}
}

function conventionCenter_onChange(elem) {
	conventionCenterValue = elem.value;
}
function constructXMLQueryForConventionCenter() {
	var conCenterStateValue = f.stateProvince.value;
    // For the convention center to work on change
    //var conCenterCountryValue = document.getElementById("conventionCenterCountry").value;
    var conCenterCountryValue = f.country.value;

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

function loadXMLDocForConventionCenter(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 = processReqChangeForConventionCenter;
		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 = processReqChangeForConventionCenter;
			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 processReqChangeForConventionCenter() {
       // 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');
           }
       }
   }
// Initialize form correctly
function initCities() {
   if(!((globaTabName)&&(globaTabName=="conventionName"))){
    var countryField = f.country;
	var stateProvince = f.stateProvince;
    var cityField = f.cityField;
	if ((countryField.value == "US") || (countryField.value == "CA")) {
		stateProvince.disabled = false;
		if (stateProvince.value != "") {
			constructXMLQuery();
		}
	} else {
		if (countryField.value != "") {
			constructXMLQuery();
		} else {
			stateProvince.value = "";
			stateProvince.disabled = true;
			cityField.value = "";
			cityField.disabled = true;

		}

	if ((countryField.value != "US") && (f.rateRange)) { f.rateRange.disabled = true; f.rateRange.value = ""; }
	else { if (f.rateRange) { f.rateRange.disabled = false; } }
         }
        }
}
