;TA.PF = {

    timer: {},

    init: function() {
        TA.PF.initToggleCategories();
        this.ieArray();
        this.getJSON();
    },

    checkPage: function() {
        if (window.location.href.indexOf('query') >-1) {
            return true;
        } else {
            return false;
        };
    },

    ieArray: function() {
        if (!Array.prototype.indexOf){
            Array.prototype.indexOf = function(elt /*, from*/){
                var len = this.length >>> 0;

                var from = Number(arguments[1]) || 0;
                from = (from < 0)
                     ? Math.ceil(from)
                     : Math.floor(from);
                if (from < 0)
                  from += len;

                for (; from < len; from++){
                  if (from in this &&
                      this[from] === elt)
                    return from;
                };
            return -1;
            };
        };
    },


    getJSON: function(){
        var JSON = "/wps/wcm/myconnect/travel-associates/global/destinations/alldestinations";

        $.getJSON(JSON, function(data) {
            TA.PF.destData = data;
            $(TA.PF).trigger('jsonDataReady');

        });
    },

    jsonDataReady: function() {
        jQuery(document).ready(function($) {
            TA.PF.initSlider();
            TA.PF.initAutoComplete();
            TA.PF.initCategories();
            TA.PF.initTooltip();

            if (!TA.PF.checkPage()) {
                $('#searchHoliday').bind('click', function(event) {
                    $('#holidaysearch').find('.holidayLoading').show();
                    TA.PF.doAjax(this.id);
                    event.preventDefault();
                });
            } else {
                $('#searchHoliday').hide();
                TA.PF.formatSearchResults();
            };

        });
    },

    initSlider: function() {

        var queryPrice = [];
        var hasPrice;
        var minPrice = 0;
        var maxPrice = 41000;
        var maxPriceText;

        queryPrice = location.href.indexOf('+');
        if (queryPrice >-1) {
            queryPrice = unescape(location.href).split('+');
            hasPrice = queryPrice.indexOf("between");
        };

        if (hasPrice >-1) {

            priceRange = queryPrice[hasPrice + 1].split('~');
            minPrice = parseInt(priceRange[0]);
            maxPrice = parseInt(priceRange[1]);

            if (maxPrice > 40000) {
                maxPriceText = '$'+40000+'+';
                maxPrice = 999999;
            } else {
                maxPriceText = '$'+maxPrice
            };

            $("#min").text(' $'+minPrice).next('span').text(maxPriceText);

        } else {

            $("#min").text(' $0').next('span').text('$40,000+');

        };

        var priceSlider = $('#slider');
        $('#slider').slider({
            step: 1000,
            range: true,
            min: 0,
            max: 41000,
            values: [minPrice, maxPrice],
            slide: function(event, ui){
                    var maxNum = '$'+ui.values[1];

                    if (maxNum > 40000) {
                        maxNum = '$40,000+';
                    }

                    $("#min").text(' $' + ui.values[0]);
                    $('#max').text(maxNum);

                    if (TA.PF.checkPage()) {
                      clearTimeout(TA.PF.timer);
                      TA.PF.timer = setTimeout(function() {
                        TA.PF.doAjax();
                       }, 500);
                    }
            }
        });
    },

    initAutoComplete: function() {
        this.setAutoComplete();

        var data = [];

        for (var i = 0; i < TA.PF.destData.destinations.length; i++) {
            data[i] = TA.PF.destData.destinations[i].display;
        };

        $('#location').autocomplete(data,{
             matchContains: true,
             width: 210
        }).result(function(event, item) {

            if (TA.PF.checkPage()) {
                TA.PF.doAjax();
            };
        });


    },

    setAutoComplete: function() {
        var getQuery = [];
        var locationURL = location.href;
        var searchResults = locationURL.indexOf('search-results');

        if (searchResults >-1) {
            getQuery = locationURL.split('+');
            getQueryDestination = unescape(getQuery[2]);
            queryDestination = getQueryDestination.replace(/["']{1}/gi,"");

            strDestination = this.getDestDisplay(queryDestination);

            $('#location').val(strDestination);

        } else {
            return false;
        };
    },

    initCategories: function() {
        var tempArr = '';
        var intProdCat = window.location.pathname.indexOf('product_category');
        var arrProdCat = [];
        var arrHolExp = [];
        var catRel = '';
        var intHolExp = window.location.pathname.indexOf('holiday_experience');
        var intProdSel = window.location.pathname.indexOf('product_selection');
        var intDestination = window.location.pathname.indexOf('Arctic');
        var $catselection = $('#Categories a');

        if (intProdCat > -1) {
            tempArr = window.location.pathname.substring(intProdCat).split('+is+');
            tempArr = tempArr.join(',').split('+and+');
            tempArr = tempArr[0].split(',');

            for (var i=1; i < tempArr.length; i++) {
                arrProdCat[i-1] = tempArr[i].slice(3, -3);
            };

            for (var i=0; i < arrProdCat.length; i++) {
                $('#Categories a[rel="'+arrProdCat[i]+'"]').addClass('checked');
            };

        };

        if (intHolExp > -1) {

            tempArr = window.location.pathname.substring(intHolExp).split('+like+');
            tempArr = tempArr.join(',').split('+and+');
            tempArr = tempArr[0].split(',');

            for (var i=1; i < tempArr.length; i++) {
                arrHolExp[i-1] = tempArr[i].slice(3, -3);
            };

            for (var i=0; i < arrHolExp.length; i++) {
                $('#Categories a[rel="'+arrHolExp[i]+'"]').addClass('checked');
            };
        };

        if (intProdSel > -1 ) {
            $('#Categories a[rel="Rail"]').addClass('checked');
        };

        if (intDestination > -1 ) {
            $('#Categories a[rel="Polar+Adventures"]').addClass('checked');
        };

        $('#Categories a').live('click', function(e){

            if($(this).parent().parent().parent().attr('class') == 'redTicks'){
                if($(this).attr('class').indexOf('checked') > -1){
                  $(this).css('background-image','url(/images/interface/icons-holiday-search.png)');
                  $(this).removeClass('checked');
                } else {
                  $(this).css('background-image','url(/images/interface/icons-holiday-search-rollover.png)');
                  $(this).addClass('checked');
                }
            } else {
                if($(this).attr('class') == 'checked'){
                  $(this).fadeTo('fast', 0.9);
                  $(this).removeClass('checked');
                } else {
                  $(this).fadeTo('fast', 0.5);
                  $(this).addClass('checked');
                } 
            }

            if (TA.PF.checkPage()) {
                TA.PF.doAjax();
            };

        });
    },

    initTooltip: function() {
        $('#Categories a').tooltip({
             delay: 100,
             showURL: false,
             top: -50,
             left: 20,
             showBody: "-"
         });
    },

    filterText: function(sText) {
         var testToRemove = /<br>|<p>|<br\/>|<br \/>|<p\/>|<a .*?>|<\/a>|^[ \t]+/gi;
         return sText.replace(testToRemove, function (sMatch) {
            return sMatch.replace(/./g, " ");
         });
    },

    getDestValue: function(value) {
        var destinationValue = '';
        var tempDestArr;

        for (var i = 0; i < TA.PF.destData.destinations.length; i++) {
            tempDestArr = TA.PF.destData.destinations[i];
            if (tempDestArr.display == value) {
                destinationValue = tempDestArr.value;
            };
        };

        return String(destinationValue);
    },

    getDestDisplay: function(display) {
        var destinationDisplay = '';
        var tempDestArr;

        for (var i = 0; i < TA.PF.destData.destinations.length; i++) {
            tempDestArr = TA.PF.destData.destinations[i];
            if (tempDestArr.value == display) {
                destinationDisplay = tempDestArr.display;
            };
        };

        return String(destinationDisplay);
    },

    getPriceDifference: function() {
        var max = $('#slider').slider('values', 1);
        var min = $('#slider').slider('values', 0);

	    return min + '~' + max;

    },

    formatSearchResults: function() {
        var $el = $('.prodDescription');

        if ($el.length <= 0) {
            $('#noResults').fadeIn('fast');
            return false;
        };

        for (i=0;i<$el.length;i++) {
            tempStr = $el[i].innerHTML;
            filterStr=this.filterText(tempStr);
            $el[i].innerHTML=filterStr;
        };

        $el.expander({
            slicePoint: 210,
            expandText: '',
            userCollapseText: '[^]'
        });
    },

    getCategoryQuery: function(args) {
        var strFields = args.split(',');
        var arrFields = [];
        var strCategory = '';


        for (var i=0; i < strFields.length; i++) {
            if (strFields[i] == 'Air+Transportation' || strFields[i] == 'Cruise' || strFields[i] == 'Accommodation' || strFields[i] == 'Tour' || strFields[i] == 'Holiday+Package' ) {
                strCategory += '"'+strFields[i]+'",';
            };
        };

        return strCategory;

    },

    getHolExpQuery: function(args) {
        var strFields = args.split(',');
        var arrFields = [];
        var strHolExp = '';

        for (var i=0; i < strFields.length; i++) {
            if (
                strFields[i] == 'Walking' || 
                strFields[i] == 'Honeymoon' || 
                strFields[i] == 'Food+Tours' || 
                strFields[i] == 'Skiing' || 
                strFields[i] == 'Cycling' || 
                strFields[i] == 'Overwater+Bungalows' || 
                strFields[i] == 'Women' ||
                strFields[i] == 'Spa' ||
                strFields[i] == 'Walking+Cycling' || 
                strFields[i] == 'Battlefield' ||
                strFields[i] == 'Food' ||
                strFields[i] == 'Private+Island'
            ) {
                if (strFields[i] == 'Walking+Cycling'){
                    strHolExp += '"Walking","Cycling",';
                } else {
                strHolExp += '"'+strFields[i]+'",';
                }
            };
        };

        return strHolExp;
    },

    getProdSelect: function(args) {
        var strFields = args.split(',');
        var strProdSel = '';

        for (var i=0; i < strFields.length; i++) {
            if (strFields[i] == 'Rail' ) {
                strProdSel += '"'+strFields[i]+'",';
            };
        };

        return strProdSel;

    },

    getByPolar: function(args) {
        var strFields = args.split(',');
        var strByPolar = '';

        for (var i=0; i < strFields.length; i++) {
            if (strFields[i] == 'Polar+Adventures' ) {
                strByPolar = '"Antarctica","Arctic","Greenland"';
            };
        };

        return strByPolar;

    },

    doAjax: function(button) {

       //Prevent ENTER from reloading page
       $(window).keydown(function(event){
           if(event.keyCode == 13) {
             event.preventDefault();
             return false;
           }
       });

        var ajaxQuery = '';
        var getChecked = '';
        var query = '';
        var extra = '';
        var sort = '+sort+weighting+price+';
        var byRegion = $('#location').val();
        var bySelection = '';
        var byPolar = '';
        var byPrice = this.getPriceDifference();
        var byCategory = '';
        var byExperience = '';
        var catSelected = '';
        var byRegion = this.getDestValue(byRegion);
        var getChecked = $('#Categories a');

        //** GET LIST OF ALL CATEGORIES CHECKED
        getChecked.each(function(){
            if ($(this).hasClass('checked')) {
                catSelected += $(this).attr('rel') + ',';
            };
        });

        catSelected = jQuery.trim(catSelected.slice(0, -1));

        byCategory = this.getCategoryQuery(catSelected);
        byExperience = this.getHolExpQuery(catSelected);
        bySelection = this.getProdSelect(catSelected);
        byPolar = this.getByPolar(catSelected);

        byCategory = jQuery.trim(byCategory.slice(0, -1));
        byExperience = jQuery.trim(byExperience.slice(0, -1));
        bySelection = jQuery.trim(bySelection.slice(0, -1));

        if (byRegion != '' && byPolar != '') {
            query = 'destination+is+"' + byRegion + '",' + byPolar;
        };

        if (byRegion != '' && query == '') {
            query = 'destination+is+"' + byRegion + '"';
        };

        if (byPolar != '' && byRegion == '') {
            query = 'destination+is+' + byPolar;
        };

        if (byCategory != '') {
            if (query != '') query = query + "+and+";
            query = query + 'product_category+is+' + byCategory;
        };

        if (bySelection != '') {
            if (query != '') query = query + "+and+";
            query = query + 'product_selection+is+' + bySelection;
        };

        if (byExperience!='') {
            if (query!='') query=query+"+and+";
            query=query+'holiday_experience+like+' + byExperience;
        };


        if(byPrice == '0~41000'){
        }
        else if (byPrice != '') {
             if (query != '') query = query + "+and+";
             query = query + 'price+between+' + byPrice;
         };

        if (byRegion == '' && byCategory == '' && byPrice == '' && byExperience == '') {
            alert('Please enter a selection before searching');
            return false;
        };

        ajaxQuery = '/packages/search/search-results&query=' + query + sort + extra;

        if (button == 'searchHoliday') {
            if (byRegion == '') {
                window.location.href = '/packages/search/search-results&query=' +query;
            } else {
                window.location.href = ajaxQuery;
            };

        } else {

            $('#noResults').hide();
            $('#resultSet').hide();
            $('.loadingHolidayMsg').fadeIn('fast');


             $.ajax({
                 url:ajaxQuery,
                 success: function(data){
                     var result = '';
                     result = $(data).find("#resultSet").html();
                     // CHECK RESULTS
                     TA.PF.showSearchResults(result);
                 }
            });
        }
    },

    showSearchResults: function(result) {
        
        if (result != "")
        {
            $('#noResults').hide();
            $('#resultSet').html(result)
            $('.loadingHolidayMsg').hide(function(){
                $('#resultSet').fadeIn('fast');
            });

            TA.PF.formatSearchResults();
        }
        else
        {
            $('.loadingHolidayMsg').hide();
            $('#noResults').fadeIn('fast');
        }
    },

    initToggleCategories: function()
    {
        $('#productSelector .moreSearchOptions').bind('click',function()
        {
            $('#Categories').slideToggle();
            $('#productSelector h3 .moreSearchOptions').hide();
            $('#productSelector h3 .fewerSearchOptions').show();
        });
        $('#productSelector .fewerSearchOptions').bind('click',function()
        {
            $('#Categories').slideToggle();
            $('#productSelector h3 .moreSearchOptions').show();
            $('#productSelector h3 .fewerSearchOptions').hide();
        });
    }
};

TA.PF.init();



