/**
 * Tours
 *
 * @author          Jason Rundell
 * @modifiedby      $LastChangedBy: warrens $
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * @version         $Revision: 12770 $
 * @lastmodified    $Date: 2011-09-09 15:37:23 +1000 (Fri, 09 Sep 2011) $
 * @requires        jQuery, jQuery.cookie
 */
;ET.TOURS = 
{
    destinations: {},
    
    defaults: {},
    
    init: function() 

    {
        this.setupForm();
        this.loadFormDefaults();
    },
    
    /** 
     * Bind form events and load contintent data
     */    
    setupForm: function()
    {    
        $('#byContinent').bind('change', function(event) 
        {
            ET.TOURS.updateCountries($(this).val());
        });
        
        $('#byCountry').bind('change', function(event) 
        {
            ET.TOURS.updateDestinations($(this).val());
        });
        
        $('#toursForm').bind('submit', function(event) 
        {
            event.preventDefault();
            ET.TOURS.validate();
        }); 

        $.ajax({
            url: "/wps/wcm/myconnect/escape-travel/global/destinations/continents",
            dataType: "text",
            success: function(data){
                ET.TOURS.destinations = $.parseJSON(data);
                ET.TOURS.setupContinents();
            }
        });
        $('#byCountry').hide(); 
        $('#byRegion').hide();
    },
    
    /**
     * 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 ET.EVENTS,
     * then for the select fields that are not dynamic, set them to their previously
     * selected value
     */
    loadFormDefaults: function()
    {
        if($.cookie('ET.TOURS.COOKIE') != null)
        {
            this.defaults = $.parseJSON($.cookie('ET.TOURS.COOKIE'));
            this.setSelectedIfDefault('byExperience');
            this.setSelectedIfDefault('bySupplier');
            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 = ET.TOURS.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)
            {
                $('#toursForm').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
             $('#toursForm').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 == '')
        {
            $('#byContinent').show()    ;
            $('#byCountry').hide().attr('disabled', true);
            return;
        }

        $.ajax({
            url: "/wps/wcm/myconnect/escape-travel/global/destinations/"+strContinent,
            dataType: 'text',
            success: function(data){
                data = $.parseJSON(data);
                if (data.countries.length > 0)
                {
                    ET.TOURS.destinations = data;
                    var arrList = [];
                    var objCountries = ET.TOURS.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);
                    }

                    ET.TOURS.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 = ET.TOURS.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 bySupplier = $('#bySupplier').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 == '' && bySupplier == '')
        {
            alert('Please select a holiday type or destination.');
            return false;
        };

        this.buildQueryString(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry, bySupplier);	
    },
    
    /**
     * Based on a combination of field selections, build the search string
     */
    buildQueryString: function(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry, bySupplier) 
    {
        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+'&country='+byCountry;
        };
        
        if(byContinent !='') 
        {
            if(byCountry == '' && byRegion == '')
            {
                extra=extra+'&continent='+byContinent;
            }
        };
               
        if(byPrice !='') 
        {
            if(query!='') query += "+and+";
            query=query + 'price+between+' + byPrice;
        };
        
        if(byExperience!='') 
        {
            if (query!='') query += "+and+";
            query += 'holiday_experience+like+"' + byExperience + '"';
        };
        
        if(bySupplier!='') 
        {
            if (query!='') query += "+and+";
            query += 'supplier+like+"' + bySupplier + '"';
        };
        
        if(byCategory!='') 
        {
            if (query!='') query += "+and+";
            
            if(byCategory == "Ski")
            {
                query += 'package_name+like+"ski","snow"';
            }
            else
            {
                query += 'product_category+is+"' + byCategory + '"';
            }
        };
        
        
        
        var holidaysCookie = {};
        $('#toursForm').find('select').each(function()
        {
            holidaysCookie[$(this).attr('name')] = $(this).val();
        });

        // Save field values so we can re-create its selections when next used
        // $.cookie('ET.TOURS.COOKIE', JSON.stringify(holidaysCookie), { path: '/' });
        // line above commented due to the JSON section breaking the form in internet explorer when submitting
 
        window.location.href="/search-results-tours/results&query="+query+sort+extra;
    },
    
    ausHolidayResultsCheck: function()
    {
        $('.subTitleTop').each(function()
        {
            if($(this).next().find('img.imageBorder').length == 0)
            {        
                $('.sorryNoHolidays:first').clone().insertAfter($(this));
                $(this).next().show();
            }
        });
    }
};
ET.TOURS.init();
