﻿var allcities;
var allstates;

function getStates(countryName)
{
    var foundstates;
    countries.each(function(acountry){
        if(acountry.name == countryName)
        {
            foundstates = acountry.states;
        }

    });
    
    return foundstates;
    
}

function getCities(countryName, stateName)
{

    var foundcities;
    
    var cStates = getStates(countryName);
    
    if(cStates)
    {
        cStates.each(function(astate){
            if(astate.name == stateName)
            {
                foundcities = astate.cities;    
            }
        });
    }
    
    return foundcities;
}

function setSelected(selectId, newValue)
{
    var found = false;
    var selectedOptions = $A($(selectId).options);
    var newIndex = -1;
    
   
    selectedOptions.each(function(anoption, theIndex){
        //I hate IE.  We have to check the actual text too
        
        if(anoption.value == newValue || anoption.text == newValue)
        {
           
            newIndex = theIndex;
            found = true;
           
            return;
        }
    
    });

    $(selectId).selectedIndex = newIndex;
    
}

function loadSelects(selectId, newOptions)
{
      $(selectId).options.length = 0; //clear any options
      
            newOptions.each(function(anewoption){
                
               var newValue;
               
                
                //add the All option
                if(selectId == "searchCitySelect")
                {
                    $(selectId).options[0] = new Option("All Cities","", true, true);
                    
                }
                if(selectId == "searchStateSelect")
                {
                    $(selectId).options[0] = new Option("All States / Provinces...","", true, true);
                }
                //does this thing have a name?
                if(anewoption && !Object.isUndefined(anewoption.name) && anewoption.name != null )
                {
                    newValue = anewoption.name
                }
                else
                {
                    if(Object.isString(anewoption) )
                    {
                        newValue = anewoption;
                    }
                    else
                    {
                        newValue = "";
                    }
                }
                
                if(newValue != "" && anewoption != "undefined")
                {
                    $(selectId).options[$(selectId).options.length] = new Option(newValue,newValue);
                }
               
             
            });

}

function getUniqueStatesArray(options)
{
    var uniqueStates = new Array();
    if(!options)
    {
        options = {};
        options.country = null;
    
    }
    
    if(options.country == "")
    {
        options.country = null;
    }
    
    countries.each(function(acountry){
        //are we filtering by country?
        if(options.country)
        {
           if(options.country == acountry.name)
           {
                acountry.states.each(function(astate){
                    uniqueStates.push(astate.name);
                    
                });
           
           }
        }
        else
        {
            //we have to grab just the name of the state
            acountry.states.each(function(astate){
                uniqueStates.push(astate.name);
            
            });
        
        }
    
    });
    
    //dedupe, sort, and send off
    
    return  uniqueStates.uniq().sort();
}

function getUniqueCitiesArray(options)
{
    var uniqueCities = new Array();
    if(!options)
    {
        options = {};
        options.country = null;
        options.state = null;
    }
    
    if(options.country == "")
    {
        options.country = null;
    }
    
    if(options.state == "")
    {
        options.state = null;
    }
    
    countries.each(function(acountry){
        //are we filtering out by country?
        if(options.country)
        {
            if(acountry.name == options.country)
            {
                acountry.states.each(function(astate){
                
                    //are we filtering by state?
                    if(options.state)
                    {
                        if(options.state == astate.name)
                        {
                            uniqueCities = uniqueCities.concat(astate.cities);
                        }
                    }
                    //nope grab all the cities in the states
                    else
                    {
                        uniqueCities = uniqueCities.concat(astate.cities);
                    }
                });
           }
        }
        
        //no country filter, grab all the cities
        else
        {
                acountry.states.each(function(astate){
                    uniqueCities = uniqueCities.concat(astate.cities);
                });
        }

   
     });
    //return the deduped alphabetized city list
    return uniqueCities.uniq().sort();
}


function getCityStateAndCountry(someCity)
{
    var results = {};
    countries.each(function(acountry){
        //found a result, don't process further
        if(results.country) return;
        
        acountry.states.each(function(astate){
        
            //found a result, don't process further
            if(results.country) return;
            
            astate.cities.each(function(acity){
            
                if(results.country) return;
                
                if(acity == someCity)
                {
                    results.country = acountry.name;
                    results.state = astate.name;
                    return;
                    
                }
            
            });
        
        });
        
    
    });
    
    if(results.country == null || Object.isUndefined(results.country))
    {
        results.country = "";
    }
    
    if(results.state == null || Object.isUndefined(results.state))
    {
        results.state = "";
    }
    
    return results;
}

function getStateCountry(someState)
{
    var thecountry = null;
    countries.each(function(acountry){
        
        if(thecountry) return;
        acountry.states.each(function(astate){
        
            if(astate.name == someState)
            {
                thecountry = acountry.name;
            }
        });
    
    });

    return thecountry;
}

function initializeSearchOptions()
{
 //load the initial countries
     //add the empty state
    $("searchCountrySelect").options[0] = new Option("All Countries...","", true, true);
    
    countries.each(function(acountry){
        $("searchCountrySelect").options[$("searchCountrySelect").options.length] = new Option(acountry.name);
    });
    
     $("searchCountrySelect").observe('change',countryChange);
     $("searchStateSelect").observe('change',stateChange);
     $("searchCitySelect").observe('change',cityChange);
    //setup the link
    $("searchButton").observe('click',sendoff);
    
   
        //load all the cities
        allCities = getUniqueCitiesArray();
        loadSelects("searchCitySelect",allCities);
        
        //load all the states
        allStates = getUniqueStatesArray();
        loadSelects("searchStateSelect",allStates);
        
        
  
}
    
function loadStates(event) {
   //get the states for the country
   var foundstates = getStates($F("searchCountrySelect"));
        
   if(foundstates)
   {
       loadSelects("searchStateSelect",foundstates);
           
   }      
   loadCities();
        
}
    
    function loadCities(event)
    {
        //var foundcities = getCities($F("searchCountrySelect"),$F("searchStateSelect"));
        var options = {};
        options.country = $F("searchCountrySelect");
        options.state = $F("searchStateSelect");
        foundcities = getUniqueCitiesArray(options);
        if(foundcities)
        {
            loadSelects("searchCitySelect",foundcities);
        }      
    
    }
    
    function cityChange(event)
    {
          var info = getCityStateAndCountry($F("searchCitySelect"));
          var selectedCity = $F("searchCitySelect");
          setSelected("searchCountrySelect",info.country);
          loadStates();
          setSelected("searchStateSelect",info.state);
          loadCities();
          setSelected("searchCitySelect",selectedCity);
          
           
        
    }
    
    function stateChange(event)
    {
            //set the country to the current state's country
            setSelected("searchCountrySelect",getStateCountry($F("searchStateSelect")));
            
            //load the cities for that state
            loadCities();
            
    
    
    }
    
    function countryChange(event)
    {
        //if we select an empty country value (All), then reinitialize
        if($F("searchCountrySelect") == "" || $F("searchCountrySelect") == null || $F("searchCountrySelect") == "All")
        {
            //start over
             initializeSearchOptions();
            // alert("Starting Over");
        }
        else
        {
            //otherwise just filter the states (cities will propogate through the loadStates function
            loadStates();
        }
        
    
    }
    
    function sendoff(event)
    {
        var theCountry = $F("searchCountrySelect");
        var theState = $F("searchStateSelect");
        var theCity = $F("searchCitySelect");
        var arrive = $F("arrive");
        var numberOfNights = $F("numberOfNights");
        var adults = $F("adults");
        var children = $F("children");
        var offerCode = $F("offerCode");
        
       //prepare the redirect URL and hidden form so that when we decide where we have to send them, both are ready
        var newURL = "./searchResults.aspx?fml=0";  
		
		if(arrive && arrive != "" && Object.isString(arrive))
		{
			//window.alert(arrive);
			if(arrive == "MM%20/%20DD%20/%20YYYY" || arrive == "MM / DD / YYYY")
			{
				var arrive1 = "void";
				//window.alert(arrive1);
			}
			else
			{
				newURL += "&arrive=" + encodeURIComponent(arrive);
				//window.alert(arrive);
			}
		}
        if(theCountry && theCountry != "" && Object.isString(theCountry))
        {
            newURL += "&country=" + encodeURIComponent(theCountry);
            //load the hidden form values too 
            $('country').value = theCountry;
       
        }
        
        if(theState && theState != "" && Object.isString(theState))
        {
            newURL += "&state=" + encodeURIComponent(theState);
            $('state').value = theState;
            
        }
        
        if(theCity && theCity != "" && Object.isString(theCity))
        {
            newURL += "&city=" + encodeURIComponent(theCity);
            $('city').value = theCity;
        }
                
        //old arrive
        /*if(arrive && arrive != "" && Object.isString(arrive))
        {
            //window.location.href = newURL;
            newURL += "&arrive=" + encodeURIComponent(arrive);
        }*/
        
        if(numberOfNights && numberOfNights != "" && Object.isString(numberOfNights))
        {
            //window.alert(numberOfNights);
            if(numberOfNights == "Nights")
            {
                var numberOfNights1 = "void";
                //window.alert(numberOfNights1);
                //window.location.href = "Default.aspx?error=2";
            }
            else
            {
                newURL += "&numberOfNights=" + encodeURIComponent(numberOfNights);
            }
        }
        
        if(adults && adults != "" && Object.isString(adults))
        {
            newURL += "&adults=" + encodeURIComponent(adults);
        }
        
        if(children && children != "" && Object.isString(children))
        {
            newURL += "&children=" + encodeURIComponent(children);
            
        }
        //code from master page
        //set stuff
        var state;
        var country;
        var city;
        var currentURL;
                
        //capture URL
        currentURL = document.URL;
                
        //pull parameters
        var url_object = currentURL.toQueryParams();
                
        //identify parameters and set variables
        if(url_object.city)
        {
            if(url_object.city != "")
            {
                city = url_object.city;
            }
            else
            {
                city = "";
            }
        }
        //window.alert(city);
                
        if(url_object.country)
        {
            if(url_object.country != "")
            {
                country = url_object.country;
            }
            else
            {
                country = "";
            }
        }
        //window.alert(country);
                
        if(url_object.state)
        {
            if(url_object.state != "")
            {
                state = url_object.state;
            }
            else
            {
                state = "";
            }
        }
        //window.alert(state);
                
            function setThisStuff(city, state, country){
                if (city && city != "")
                {
                    $('city').value = city;
                }
                        
                if (state && state != "")
                {
                    $('state').value = state;
                }
                        
                if (country && country != "")
                {
                    $('country').value = country;
                }
            }
        
        setThisStuff(city, state, country);
        //REMOVED: split page action logic
        
        if(offerCode && offerCode != "" && Object.isString(offerCode))
        {
            newURL += "&rateCode=" + encodeURIComponent(offerCode);
        }

        
        //heres where you need to add the logic determining which way we're sending
        if (!arrive1) 
        {
            if(!numberOfNights1)
            {
                //send them to netbooker somehow
                window.location.href = newURL;
            }
            else
            {
                window.location.href = "Default.aspx?error=2";
            }
        }
        else 
        {
                //send them to tig via form
                document.forms["hiddenForm"].submit();
        }
    }