;/**
  * Explore Holidays
  * 
  */
;EH.HOLIDAYS = 
{
    destinations: {},
    
    defaults: {},
    
    init: function() 
    {
        this.setupForm();
        this.loadFormDefaults();
    },
    
    /** 
     * Bind form events and load contintent data
     */    
    setupForm: function()
    {    
        $('#byContinent').bind('change', function(event) 
        {
            EH.HOLIDAYS.updateCountries($(this).val());
        });
        
        $('#byCountry').bind('change', function(event) 
        {
            EH.HOLIDAYS.updateDestinations($(this).val());
        });
        
        $('#browseDeals').bind('submit', function(event) 
        {
					 event.preventDefault();
					 EH.HOLIDAYS.validate();          
        }); 
        
        var JSON = "/wps/wcm/myconnect/exploreholidays.com.au/global/destinations/continents?callback=";
        $.getJSON(JSON, function(data) 
        {
            EH.HOLIDAYS.destinations = data;
            EH.HOLIDAYS.setupContinents();               
        });

    },
    
    /**
     * Every time the form is used the state of the form is saved in a cookie
     * If this cookie exists, extract the defaults and save them to EH.EVENTS,
     * then for the select fields that are not dynamic, set them to their previously
     * selected value
     */
    loadFormDefaults: function()
    {

        if($.cookie('EH.HOLIDAYS.COOKIE') != null)
        {
            this.defaults = JSON.parse($.cookie('EH.HOLIDAYS.COOKIE'));
            //this.setSelectedIfDefault('byExperience');
            this.setSelectedIfDefault('byCategory');
            this.setSelectedIfDefault('byPrice');
        }
    },
    
    /**
     * JSON AJAX request to get all continents
     * We replace Oceania Australia with Australia & South Pacific for usability
     */
    setupContinents: function() 
    {

        var destinations = [];
        var continents = EH.HOLIDAYS.destinations.continents;
        var options = '';
        
        for (var i=0; i < continents.length; i++) 
        {
            destinations[i] = continents[i];
        };
 
        for (var i=0; i < continents.length; i++) 
        {
            options += '<option value="'+destinations[i]+'">'+destinations[i]+'</option>'; 
        }
        
        $('#byContinent').append(options);
        $('#byContinent option[value="Oceania and Australia"]').text('Australia & South Pacific');
        
        this.setSelectedIfDefault('byContinent');
    },

    /**
     * If a default field value exists from a previous form instance and its not blank 
     * (has not been set already), set the field name to the default value
     */
    setSelectedIfDefault: function(fieldName)
    {
				
        // This is prone to crash in IE6
        try
        {
            var defaultVar = this.defaults[fieldName];
            if(typeof(defaultVar) != 'undefined' && defaultVar != '' && defaultVar != null)
            {
                $('#browseDeals').find('select[name="' + fieldName +'"] option[value="'+  defaultVar +'"]')
                                  .attr('selected', 'selected')
                                  .parent().trigger('change');
                this.defaults[fieldName] = '';
            }
        }
        catch(e)
        {
            // Reset this field to its blank state to avoid confusion
             $('#browseDeals').find('select[name="' + fieldName +'"]').val('');
         }
    },
    
    /**
     * Using the supplied contitent, modify it and it to execute a JSON AJAX which will return
     * the list of countries in byCountry for that continent.
     */
    updateCountries: function(strContinent) 
    {
        //$('#byRegion').hide().attr('disabled', true);
        var strContinent = strContinent.toLowerCase().split(' ').join('');
        if (strContinent == '')
        {
            //$('#byCountry').hide().attr('disabled', true);
            return;
        }

        var JSON = "/wps/wcm/myconnect/exploreholidays.com.au/global/destinations/"+strContinent+"?callback=";
        $.getJSON(JSON, function(data) 
        {
            if (data.countries.length > 0) 
            {
                EH.HOLIDAYS.destinations = data;
                var arrList = [];
                var objCountries = EH.HOLIDAYS.destinations.countries.sort();
                var options = '';
                
                for (var i=0; i < objCountries.length; i++) 
                {
                      options += '<option value="'+objCountries[i]+'">'+objCountries[i]+'</option>'; 
                };
                
                if ($('#byCountry option').length > 1) 
                {
                    $('#byCountry').empty();
                    $('#byCountry').show().attr('disabled',false).append('<option value="">All countries</option>').append(options);
                } 
                else 
                {
                    $('#byCountry').show().attr('disabled',false).append(options);  
                };
                
                EH.HOLIDAYS.setSelectedIfDefault('byCountry');     
            };            
        });    
    },
    
    /**
     * Using supplied country as a key, get the list of regions for this country
     * and update the byRegion field.
     */
    updateDestinations: function(strCountry) 
    {
        if (strCountry == '')
        {
            //$('#byRegion').hide().attr('disabled', true);
            return;
        }
        
        var countries = EH.HOLIDAYS.destinations[strCountry];
        var options = '';
        
        for (var i=0; i<countries.length; i++) 
        {
              options += '<option value="'+countries[i]+'">'+countries[i]+'</option>'; 
        };

        $('#byRegion').empty()
                      .append('<option value="">All destinations</option>')
                      .append(options)
                      .attr('disabled', false)
                      .show();
              
        this.setSelectedIfDefault('byRegion');      
    },
    
    /**
     * Basically, we need at least one field filled out before we can search
     */
    validate: function() 
    {
			
        var byContinent = $('#byContinent').val();
        var byExperience = $('#byExperience').val();
        var byCategory = (typeof $('#byCategory').val() != 'undefined') ? $('#byCategory').val() : 'Holiday Package';
        var byCountry = $('#byCountry').val();
        var byRegion = $('#byRegion').val();
        var byPrice = $('#byPrice').val();
        
        if (byContinent == '' && byCountry == '' && byRegion == '' && byPrice == '' && byExperience == '')
        {
            alert('Please select a holiday type or destination.');
            return false;
        };
        this.buildQueryString(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry);	
    },
    
	/* Post-Bloat Continent Fix */
	fixContinent: function(continent){
		/*if(EH.getEnv() == 'production'){
			return ' ';
		}else{
			return continent;
		}*/
	},

    /**
     * Based on a combination of field selections, build the search string
     */
    buildQueryString: function(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry) 
    {
			
        var query='';
        var extra='';
        var sort='+sort+weighting+price+';

        if(byRegion!='') 
        {
            query='destination+is+"'+byRegion+'"';
            extra='&region='+byRegion;
        } 
        else if(byCountry!="") 
        {
            query='destination+is+"'+byCountry+'"';
        } 
        else if(byContinent !="") 
        {
            query = 'destination+is+"'+byContinent+'"';
        };
        
        if(byCountry!='') 
        {
            extra=extra+'&destination='+byCountry;
        };
        
        if(byContinent !='') 
        {
            if(byCountry == '' && byRegion == '')
            {
                extra=extra+'&destination='+byContinent;
            }
        };
               
        /*if(byPrice !='') 
        {
            if(query!='') query += "+and+";
            query=query + 'price+between+' + byPrice;
        };
        
        if(byExperience!='') 
        {
            if (query!='') query += "+and+";
            query += 'holiday_experience+like+"' + byExperience + '"';
        };
        
        if(byCategory!='') 
        {
            if (query!='') query += "+and+";
            
            if(byCategory == "Ski")
            {
                query += 'package_name+like+"ski","snow"';
            }
            else
            {
                query += 'product_category+is+"' + byCategory + '"';
            }
        };*/
        
        var holidaysCookie = {};
        $('#browseDeals').find('select').each(function()
        {
            holidaysCookie[$(this).attr('name')] = $(this).val();
        });
				
				// TODO: DOES NOT WORK IN IE
        // Save field values so we can re-create its selections when next used
        //$.cookie('EH.HOLIDAYS.COOKIE', JSON.stringify(holidaysCookie), { path: '/' });
 				
        window.location.href="/search/results&query="+query+sort+extra;
    }
};
EH.HOLIDAYS.init();
