
;SF.HOLIDAYS = 
{
    
    destinations: {},
    
    allDestinations:{},
    
    defaults: {},
    
    init: function() 
    {
        this.tooltip();
        this.setupForm();
        this.loadFormDefaults();
        this.seeMore();
    },
    
    tooltip: function() 
    {
        $(document).ready(function($) 
        {
            var swapToolTip = $('#skinnyColumnRight').is('div');
            
            $('#browseSearch, #quickDestSearch, #specificHelper, #exploreToSearch').hover(
                function() 
                {
                    if (swapToolTip) {
                        $(this).find('span').css({left:-243}).fadeIn();
                    } 
                    else
                    {
                        $(this).find('span').css().fadeIn();
                    };
                    
                },
                function()
                {
                    $(this).find('span').hide();
                }
            );
        });
        

    },
	
	
    
    searchCookie: function()
    {
        $(function()
        {
            var $searchLinks = $('#main-panel area');
            
            if (typeof $searchLinks != 'undefined') 
            {
                jQuery.each($searchLinks, function(key, value)
                {  
                    try 
                    {
                        if ($(this).attr('href').indexOf('query') > -1)
                        {
                            $(this).bind('click', function() 
                            {
                                $.cookie('SF.HOLIDAYS.COOKIE', null ,{ path: '/' });

                                moreCookie.moreHolidays = getDestinationFromUrl();
    
                                $.cookie('SF.HOLIDAYS.COOKIE', JSON.stringify(moreCookie), { path: '/' });  
                               })
                        };    
                    } catch(e) 
                    {}
                })           
            };             
        })

    },
    
    submit: function()
    {
        var pageQuery = SF.GENERALVARS.url.indexOf('query');
        if (pageQuery >-1) {
            return true
        };
        
        return false  
    },
    
    /** 
     * Bind form events and load contintent data
     */    
    setupForm: function()
    {    
        // Kill cookie on map page
        if (SF.HOLIDAYS.submit() != true)
        {
            var holidaysCookie = {};
            holidaysCookie.quickSearch = null;
            SF.HOLIDAYS.setCookie(holidaysCookie);
            this.searchCookie();
        }

        if (this.submit() == true) {
            $('#seeLess').show();
            $('#moreList').show();
            $('#seeMore').hide();       
        }
        
        $('#byContinent').bind('change', function(event) 
        {
            SF.HOLIDAYS.updateCountries($(this).val());
        });
        
        $('#byCountry').bind('change', function(event) 
        {
            SF.HOLIDAYS.updateDestinations($(this).val());
        });
        
        $('#destinationDropDown').bind('submit', function(event) 
        {
            event.preventDefault();
            SF.HOLIDAYS.validate();
        }); 
        
        var JSON = "/wps/wcm/myconnect/student-flights/global/destinations/continents?callback=";
        $.getJSON(JSON, function(data) 
        {
            SF.HOLIDAYS.destinations = data;
            SF.HOLIDAYS.setupContinents();               
        });

        /** 
         * Auto complete
         */
        var $quickSearch = $('#quickSearch')
        var JSONDEST = "/wps/wcm/myconnect/student-flights/global/destinations/alldestinations?callback=";
        var arrDest = [];
        var data = '';
        var destValue ='';
        
        
        $.getJSON(JSONDEST, function(data) {
            SF.HOLIDAYS.allDestinations = data
                
            for (var i = 0; i < data.destinations.length; i++) {
                arrDest[i] = data.destinations[i].display;
            };
        
            $quickSearch.autocomplete(arrDest,{
                matchContains: true,
                width: 165
            }).result(function(event, item) {
                
                destValue = SF.HOLIDAYS.autoGetDestValue(item);
            
                // set cookie
                var holidaysCookie = {};
                holidaysCookie.quickSearch = destValue;
                SF.HOLIDAYS.setCookie(holidaysCookie);
                
                // PERFORM AJAX REQUEST  
                if (SF.HOLIDAYS.submit() == true) {
                    $('#ajaxLoaderSearch').show();
                    $('#productListLong').html('');
                    $('#querySearch').html('');
                    
                    $.get('/cheap-trips/cheap-holidays-results&query=destination+is+"'+destValue+'"+and+product_category+is+"Holiday Package","Accommodation","Cruise","Other Categories","Airfare Packages","Hotel Packages"', function(data){
                        var result = '';
                        try
                        {
                            result = data.replace(/[\n\r]*/gim, '').match(/<!-- Product list start -->(.*?)<!-- Product list end -->/im)[1];
                            $('#productListLong').append(result);
                            $('#ajaxLoaderSearch').hide();
							
                            SF.HOLIDAYS.addSearchText(destValue , null, null, null)
                            SF.HOLIDAYS.checkResults();
                        }
                        catch(e) { 
                            $('#ajaxLoaderSearch').hide();
                            SF.HOLIDAYS.checkResults();
                        }                            
                            
                        }, "html");
                                        
                } else {
                    window.location.href='/cheap-trips/cheap-holidays-results&query=destination+is+"'+destValue+'"+and+product_category+is+"Holiday Package","Accommodation","Cruise","Other Categories","Airfare Packages","Hotel Packages"'    
                };
                
                
            })
            
            SF.inputTextShowHide($quickSearch);
        });
        
        /** 
         * Slider
         */
         
        // Check for defaults, add defaults
        var minValue = 0;
        var maxValue = 10000;
        
        SF.HOLIDAYS.$priceSlider = $('#priceSlider');
        var maxPrice = '';
        var minPrice = '';
        $('#priceMin').text('$0');
        $('#priceMax').text('$10,000+');
         
        SF.HOLIDAYS.$priceSlider.slider({
            step: 100,
            range: true,
            min: 0,
            max: 10000,
            values: [minValue, maxValue],
            slide: function(event, ui){
                
                var minNum = SF.HOLIDAYS.formatCurrency(ui.values[0]).replace('.00', '');
                var maxNum = SF.HOLIDAYS.formatCurrency(ui.values[1]).replace('.00', '');
                
                $('#priceMin').text(minNum);
                
                if (ui.values[1] == 10000) 
                {
                    maxNum = '$10,000+'
                }
                
                $('#priceMax').text(maxNum);
                
            }
        });
                    
    },

    setCookie: function(cookie){
        // Save field values so we can re-create its selections when next used
        $.cookie('SF.HOLIDAYS.COOKIE', JSON.stringify(cookie), { path: '/' });
    },

    formatCurrency: function(strValue) {
    	strValue = strValue.toString().replace(/\$|\,/g,'');
    	dblValue = parseFloat(strValue);
    
    	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
    	dblValue = Math.floor(dblValue*100+0.50000000001);
    	intCents = dblValue%100;
    	strCents = intCents.toString();
    	dblValue = Math.floor(dblValue/100).toString();
    	if(intCents<10)
    		strCents = "0" + strCents;
    	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
    		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
    		dblValue.substring(dblValue.length-(4*i+3));
    	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
    },


    autoGetDestValue: function(value) {
        var destinationValue = '';
        var tempDestArr;
        
        for (var i = 0; i < SF.HOLIDAYS.allDestinations.destinations.length; i++) {
            tempDestArr = SF.HOLIDAYS.allDestinations.destinations[i];              
            if (tempDestArr.display == value) {
                destinationValue = tempDestArr.value;
            };
        };
        
        return String(destinationValue);
    },
	
	getDestinationFromUrl: function()
	{
		try
		{
			return decodeURI(window.location.href).match(/destination\+is\+"([a-zA-Z0-9%,\+ \.']+)"/)[1].replace(/%20|\+|,/g, ' ');
		}
		catch(e)
		{
			return '';
		}
	},
    
    
    /**
     * 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('SF.HOLIDAYS.COOKIE') == null)
		{
			$.cookie('SF.HOLIDAYS.COOKIE', JSON.stringify({}));
		}
			
            this.defaults = JSON.parse($.cookie('SF.HOLIDAYS.COOKIE'));
              
            if (typeof this.defaults.quickSearch != 'undefined') {
                $('#quickSearch').val(this.defaults.quickSearch);
                
            } else {
                $('#quickSearch').val('eg. Spain');
            };
                
            // Find and check the box that have been selected for the search
            $('#specificChk').find('input').each(function(key,val){

                if (typeof SF.HOLIDAYS.defaults[$(this).val()] != 'undefined') {
                    $(this).attr('checked', true);                    
                };
                  
            });
            
            //*
            // USED TO GET SELECTED CHECKEBOXES THEN DETERMINE THE OUT RESULTING TEXT PARAGRAPH
            //*
            var strSpecificSelected = '';
            var strListSpecificSelected = '';
            
            if ($('#specificChk').find('input:checked').length > 0) {
                
            };
            
            $('#specificChk').find('input:checked').each(function(key,val) {
                strSpecificSelected += $(this).val() + ', '; 
            });
                    
            strSpecificSelected = $.trim(strSpecificSelected);
            strSpecificSelected = strSpecificSelected.slice(0, -1);
            
            if (strSpecificSelected == '') {
                strSpecificSelected = null;
            };
                
            // Load information from search results into heading and text area
            var $headingEl = $('#main-panel').find('h1'); 
            var strDestinationText = '';
			
            var theMinPrice, theMaxPrice = '';
			
            if (SF.HOLIDAYS.submit() == true) {
                
                if (this.defaults.byContinent != '' ) {
                   strDestinationText = this.defaults.byContinent;
				   

                };
                
                if (this.defaults.byCountry != '') {
                   strDestinationText = this.defaults.byCountry;
				   
                                      
                }
                        
                if (this.defaults.byRegion != '') {
                   strDestinationText = this.defaults.byRegion;
				   
                   
                };
                
                // MUST OF SEARCH BY QUICK SEARCH IF THIS IS TRUE
                /*if (typeof this.defaults.quickSearch != 'undefined') {
                    strDestinationText = this.defaults.quickSearch;                    
                };

                if (typeof this.defaults.moreHolidays != 'undefined') {
                    strDestinationText = this.defaults.moreHolidays;                    
                };*/
				
				strDestinationText = SF.HOLIDAYS.getDestinationFromUrl();				
	
                /*if (strDestinationText.length == 0) 
                {
                   strDestinationText = 'Cheap'
                } else 
                {
                    $headingEl.text(strDestinationText + ' holidays')
                };*/
                
                if (typeof this.defaults.priceMin == 'undefined') 
                {
                    theMinPrice = null
                }
                else {
                    theMinPrice = this.defaults.priceMin.replace(/[.]/g, '').slice(0, -2)    
                };
                
                if (typeof this.defaults.priceMax == 'undefined') 
                {
                    theMaxPrice = null
                }
                else {
                    theMaxPrice = this.defaults.priceMax.replace(/[.]/g, '').slice(0, -2)    
                };                
                
                // CALL UP USER SEARCH TEXT                

                SF.HOLIDAYS.addSearchText(strDestinationText, theMinPrice, theMaxPrice, strSpecificSelected)
                
                // UPDATE PRICE SLIDER VALUES
                var minValue = '';
                var maxValue = '';        
                                        
                if (SF.HOLIDAYS.submit() == true) { 
                    if (typeof this.defaults.priceMin != 'undefined') {
        
                        minValue = this.defaults.priceMin.replace(/[,$.]/g, '').slice(0, -2);
                        maxValue = this.defaults.priceMax.replace(/[,$.]/g, '').slice(0, -2);
                                            
                        SF.HOLIDAYS.$priceSlider.slider('values', 0, minValue );
                        SF.HOLIDAYS.$priceSlider.slider('values', 1, maxValue );
                        
                        $('#priceMin').text(this.defaults.priceMin.replace(/[.]/g, '').slice(0, -2));
                        
                        if (maxValue == '10000') 
                        {
                            $('#priceMax').text('$10,000+')
                        }
                        else
                        {
                            $('#priceMax').text(this.defaults.priceMax.replace(/[.]/g, '').slice(0, -2));                             
                        }        
                        
                    };

                };
                
            };
            
                        
            //*
            // USED ADD DEFAULTS TO DROP DOWNS AND PRICE SLIDERS WHEN ON RESULTS PAGE
            //*          
            this.setSelectedIfDefault('byCategory');
            this.setSelectedIfDefault('byPrice');

            
        
    },

    /**
     * USED TO UPDATE THE SEARCH TEXT DESCRIPTION THAT USERS WILL SEE.
     * 
     */
    addSearchText: function(destination, priceMin, priceMax, interests) {

        var strDestination = 'The results below are based on holiday packages in ';
        var strCost = '';
        var strInterests = '';
        
        if (destination != null ) {
            strDestination =  strDestination + '<strong>' + destination + '</strong>';
            $('#main-panel').find('h1').text(destination + ' holidays'); 
        } 
        
        if (destination == 'Cheap') 
        {
            strDestination = 'The results below are based on holiday packages '
        };
        

        
        if (priceMin != null || priceMax != null) 
        {    
            if (priceMax == '$10,000') 
            {
                strCost = ' with a default price range starting from <strong>'+priceMin+'</strong>';
            }
            else
            {
                strCost = ' costing between <strong>'+priceMin+' and '+priceMax+'</strong>';                    
            }
        };
           
        if (interests != null) {
            strInterests = ' and is specifically interesed in <strong>'+ interests +'</strong>.';
        };
        
        $('#querySearch').append('<p>'+strDestination + strCost + strInterests+'</p>');
       
    },
    
    /**
     * JSON AJAX request to get all continents
     * We replace Oceania Australia with Australia & South Pacific for usability
     */
    setupContinents: function() 
    {
        var arrDisplay = [];
        var arrValue = [];
        var objContinents = SF.HOLIDAYS.destinations.continents;
        var options = '';
        
        for (var i=0; i < objContinents.length; i++) 
        {
            arrDisplay[i] = objContinents[i];
        };
        
        arrDisplay = arrDisplay.join(',');
        arrDisplay = arrDisplay.replace('Oceania Australia', 'Australia & South Pacific');
        arrDisplay = arrDisplay.split(',').sort();
        
        arrValue = arrDisplay;
        arrValue[2] = 'Oceania Australia'; 
                                
        for (var i=0; i < objContinents.length; i++) 
        {
            options += '<option value="'+arrValue[i]+'">'+arrDisplay[i]+'</option>'; 
        }
        
        $('#byContinent').append(options);
        $('#byContinent option:eq(3)').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)
            {
                $('#destinationDropDown').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
             $('#destinationDropDown').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/student-flights/global/destinations/"+strContinent+"?callback=";
        $.getJSON(JSON, function(data) 
        {
            if (data.countries.length > 0) 
            {
                SF.HOLIDAYS.destinations = data;
                var arrList = [];
                var objCountries = SF.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);  
                };
                
                SF.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 = SF.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');      
    },
    
    getPriceDifference: function() {
        var max = $('#priceSlider').slider('values', 1);
        var min = $('#priceSlider').slider('values', 0);
        
        if (max == 10000) 
        {   
            
            max = 30000
        };
                        
        return min + '~' + max;
    },
    
    getCategory: function() {
        $('#specificChk').find('input.category:checked');
    },
    
    getCheckedMoreOptions: function(classChecked) {

        var objList = $('#specificChk').find('input.'+classChecked+':checked');
        var strExp = '';
        
        if (objList.length > 1 ) {
            $.each(objList, function(key, val){
                strExp+= '"'+$(this).val()+'",'
            })
            
            strExp = jQuery.trim(strExp.slice(0, -1));

        } else {
            strExp = '"'+objList.val()+'"';
        };
        
        if (objList.length == 0) {
            strExp = '';
        }; 

        return strExp;
    },
    
    
    /**
     * Basically, we need at least one field filled out before we can search
     */
    validate: function() 
    {
        var byExperience = '';
        var byCategory = '';
        var bySelection = '';
        
        byExperience = this.getCheckedMoreOptions('experience');
        byCategory = this.getCheckedMoreOptions('category');
        bySelection = this.getCheckedMoreOptions('selection');
                    
        
        var byContinent = $('#byContinent').val();
        var byCountry = $('#byCountry').val();
        var byRegion = $('#byRegion').val();
        var byPrice = this.getPriceDifference();
        
        if (byContinent == '' && byCountry == '' && byRegion == '' && byPrice == '' && byExperience == '')
        {
            alert('Please select a holiday type or destination.');
            return false;
        };

        this.buildQueryString(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry, bySelection);	
    },
    
    /**
     * Based on a combination of field selections, build the search string
     */
    buildQueryString: function(byPrice, byExperience, byCategory, byRegion, byContinent, byCountry, bySelection) 
    {
        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(typeof byPrice != 'undefined') 
        {
            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 ;
            }
        };
        
        
        if(bySelection !=  '') 
        {
            if (query!='') query += "+and+";
            query += 'product_selection+is+' + bySelection;

        };
        
        
        var holidaysCookie = {};
        $('#destinationDropDown').find('select').each(function()
        {
            holidaysCookie[$(this).attr('name')] = $(this).val();
        });
        
        $('#specificChk').find('input:checked').each(function(){
            holidaysCookie[$(this).val()] = $(this).attr('name');
        });

        holidaysCookie.priceMin = SF.HOLIDAYS.formatCurrency($('#priceSlider').slider('values', 0));
        holidaysCookie.priceMax = SF.HOLIDAYS.formatCurrency($('#priceSlider').slider('values', 1)); 


        // Save field values so we can re-create its selections when next used
        $.cookie('SF.HOLIDAYS.COOKIE', JSON.stringify(holidaysCookie), { path: '/' });
        
        
        window.location.href="/cheap-trips/cheap-holidays-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();
            }
        });
    },
    
    seeMore: function() {
        
        $('#seeLess').bind('click', function(event) {
          event.preventDefault();
          $('#moreList').slideUp();
          $(this).hide().prev('a').show();
        });
        
        $('#seeMore').bind('click', function(event) {
          event.preventDefault();
          $('#moreList').slideDown();
          $(this).hide().next('a').show();
        });    
    },
    
    checkResults: function() {    
        var $results = $('#productListLong').find('li').length;
        
        
        if ($results == 0) {
            $('#prodSearchNoResults').show();
        } else {
            $('#prodSearchNoResults').hide();
        };
        
    },
    
    highlightMap: function() 
    {
        $('#worldMap').maphilight({strokeWidth: 4, strokeColor: 'FFD400'}); 
    }
};
SF.HOLIDAYS.init();