/*
    STUDENT FLIGHTS: Namespacing for global functions
    VERSION: 1.0
    
*/

SF = {
    
    init: function() {
            
        $(document).ready(function(){

            SF.printVersion();
            SF.menu();
            SF.flightTabs();
            SF.remove133133();
            //SF.tabDatePicker();
            SF.slider();
            SF.newsTicker();
            SF.taxFlashHover();
            SF.taxFlashOut();
            SF.enquireToolTip();
            SF.searchCookie();
            SF.col3LongText();
            SF.col1TruncateText();
            SF.checkkampLink();
            SF.setupHpExPoints();
            SF.openModalFromUrl();
            SF.refUrlToPageUrl();
        });
        
    },
    
    GENERALVARS: {
          url: window.location.href
    },
    
    DEFAULTFLASHVARS: {
        expressInstall: 'flash/expressInstall.swf',
        minVersion: '9.0.0'
    },
    
    datePicker:
    {
        showOn: 'both', // Show date picker if field or calendar image is clicked
        buttonImage: '/images/sf-mini-cali.png', // Image to use for calendar image
        dateFormat: 'dd\/mm\/yy', // Custom Australian date format
        buttonText: 'Choose date', // Alt and title text for calendar image
        buttonImageOnly: true // Don't set calendar image to display on button, use image only
    },

    clickToCall:
    {
        brandName: 'Student Flights',
        statesPlid:
        {
            '0': 'HzyCndz', // NSW, ACT, NT
            '1': 'HzyCndz', // NSW, ACT, NT
            '2': 'HzyCndz', // NSW, ACT, NT
            '3': 'Y9AKA68', // VIC, TAS
            '4': 'vuTyDDV', // QLD (Seems to be the default)
            '5': 'V2kxqu', // SA
            '6': 'XmgM7pJ', // WA
            '7': 'Y9AKA68', // VIC, TAS
            '8': 'HzyCndz', // NSW, ACT, NT
            'default': 'vuTyDDV'
        },
        displayMessages:
        {
            callInProgress: '<span>Call in progress...</span>',
            areaCodeMissing: '<span>Please enter your area code before your telephone number</span>',
            postCodeMissing: '<span class="hghlghterr">Please enter your postcode</span>',
            postCodeInvalid: 'Australian postcodes are 3 or 4 digit numbers between 200-300\nor 800-9999.',
            connectingNow: '<span><div class="ctc-status"><img src="http://www.studentflights.com.au/images/ctc-connecting.gif"></span>',
            dialing: '<div class="ctc-status"><img src="http://www.studentflights.com.au/images/ctc-connecting.gif">',
            connected: '<div class="ctc-status"><img src="http://www.studentflights.com.au/images/ctc-connected.gif">',
            ringing: '<div class="ctc-status"><img src="http://www.studentflights.com.au/images/ctc-ringing.gif">'
        },
        errorMessages:
        {
            standard: '<span>Student Flights consultants have gone home for the day! Try us again between 9am-5pm Mon-Fri.</span>',
            emptyStandard: '<span>{2}</span>',
            noCredit: '<span>{2}</span>',
            maximumFreeCalls: '<span>You have used all your free calls.<br>Please join to continue using Pep-Talk</span>',
            numberInvalid: '<span>The number you have entered is invalid. Please enter your full number including area code.</span>',
            outOfHours: '<span>Student Flights consultants have gone home for the day! Try us again between 9am-5pm Mon-Fri.</span>',
            busy: '<span>Are you on another call? We&#39;re trying to call but can&#39;t get through.</span>',
            consultantsBusy: '<span>Student Flights phone is ringing hot! Try us again in a tick.</span>',
            noAnswer: '<span>We just missed you! Try us again and have your phone ready in your hot little hands.</span>',
            noConsultantAnswer: '<span>Student Flights are flat out with your awesome enquiries! Try us again in a tick.</span>',
            hangUp: '<span>Ouch! Think you just hung up on us! Try us again if you&#39;re keen for a chat. </span>'
        },
        setup: function() {
            FCL.SIGNALS.listen('FCL.CTC','connected',function() {
                // Google Code for Click to Call Conversion Page
                var google_conversion_id = 1035570271;
                var google_conversion_language = "en_AU";
                var google_conversion_format = "3";
                var google_conversion_color = "ffffff";
                var google_conversion_label = "2Zl4CI-mmwEQ35jm7QM";
                var google_conversion_value = 0;
                var googleAdImage = '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/{1}/?label={2}&amp;guid=ON&amp;script=0"/>'.fclFormat(google_conversion_id,google_conversion_label);
                $('body').append(googleAdImage);
            },$);
            $('#ctcForm .jordansButtonEnquire a').bind('click',function(e) {
                e.preventDefault();

                SF.TRACKING.trackEvent = {
                'action': 'enquiry',
                'type': 'clicktocall'
                };
                SF.TRACKING.eventTracking();
                
                $(this).parents('form').submit();
            });
        }
    },
    
    printVersion: function() {
        $('#main-panel').find('.printVersion, .productPrintVersion').bind('click', function (e) {
            e.preventDefault();
            $("link[media*='print']").attr('media', 'screen');
            
        });
        $('#main-panel').find('.screenVersion, .productScreenVersion').bind('click', function () {

            $("link[media*='screen']").attr('disabled', '');
            $("link[href*='print']").attr('media', 'print');
        });
    },
    
    getUrlVars: function(strUrl, param) {
            var queryString='', urlVars='', urlObj={};
            
            if (strUrl == '' || typeof strUrl == 'undefined') 
            {
                queryString = window.location.search;
            }
            else
            {
                queryString = strUrl;
            }
            
        	if (queryString == '') {
			    return '';
		    }      
         
            // remove '?'
            urlVars = queryString.substring(1).split('&');
         
            for(var i=0; i<urlVars.length; i++)
            {
                var urlVar = urlVars[i].split('=');
                urlObj[urlVar[0]] = decodeURIComponent(urlVar[1]);
            }
            
            if(typeof param != 'undefined')
            {
                if(typeof urlObj[param] != 'undefined')
                {
                    return urlObj[param];
                }
                else
                {
                    return '';
                }
            }
         
            return urlObj;
    },

        // Used to access data in metadata tags on product pages
    parseProductProperties: function()
    {
    var _this = this;
    var productProperties = Array();
        $('head').find('meta[name^="product."]').each(function()
        {
            var key = $(this).attr('name').match(/\.(.*)$/)[1];
            var value = $(this).attr('content');
            productProperties[key] = value;
        });
    return productProperties;
    },
    
    getQueryVariable:function(key) 
    { 
        return this.getUrlVars('', key);
    },
    
    menu: function() {	
		try{
			var hoverIntentOptions = {
				sensitivity: 7,
				interval: 30,
				over: hoverOverMenu,
				timeout: 100,
				out: hoverOutMenu		
			};
            $('#megamenu').children('li').hoverIntent(hoverIntentOptions);    
			$('#megamenu ul').bgiframe();
        } catch(e){
        }
		function hoverOverMenu(e) {
			$(this).addClass('open');
		}
		
		function hoverOutMenu(e) {
			
			$(this).removeClass('open');
		} 
    },
   
    flightTabs: function() {
        try {
            if (SF.GENERALVARS.url.indexOf('domestic-flights') > -1) 
            {
                $('#tabSearch').quickTabs({startPosition: 1});
            }
            else
            {
                $('#tabSearch').quickTabs({startPosition: 0});
            }
            
        } catch(e) {
            
        }
       
    },
   
    tabDatePicker: function() {
       $('.datepickerInt').datepicker({
           minDate: new Date(),
           dateFormat: 'dd/mm/yy'
       });
       
        $('.datepickerDom').datepicker({
           minDate: new Date(),
           dateFormat: 'dd/mm/yy'
       });
       
    },
    
    slider: function() {
        try {
            $('#slider').easySlider({
                auto: true,
                continuous: true
            });
        } catch(e) {
            
        }
    },
   
    newsTicker: function() {
        try {
            $('#newsTicker').liScroll({travelocity: 0.01}); 
        } catch(e) {
            
        }
	
    },
   
    taxFlashHover: function() {
        $('#taxBoxContainer').css('z-index', 40);
    },
    
    taxFlashOut: function() {
        $('#taxBoxContainer').css('z-index', 20);
    },
    
    productListHover: function(colour){
        var DEFAULTCOLOUR = '#E7E7E7';
        
        if (colour == undefined) {
            colour = DEFAULTCOLOUR;
        }
        
        $('#productListLong .rollOver').hover(
            function(){
                $(this).css('background-color', colour);
            },
            function() {
                $(this).css('background-color', '#FFFFFF');
            }
        )
    },
    
    enquireToolTip: function () {
        
        $('#ctaPanel .tip').hover(
            function() {
                $(this).find('p').show();
            },
            function() {
                $(this).find('p').hide();
            });
    },
    
    microSiteNav: function() {
        var arrNavHref = $('#microNav').find('li a');
        var strPath = window.location.pathname;
        var tmpValue = '';
        
        $.each(arrNavHref, function(){
            tmpValue = strPath.indexOf($(this).attr('href'));
            if(tmpValue > -1) {
                $(this).addClass('active');
            }
        });
    },
    
    format: function(string) {
        var args = arguments;
        var pattern = new RegExp('{([1-' + arguments.length + '])}','g');
        return String(string).replace(pattern, function(match, index) { return args[index]; });
    },
    
    automateWebTrendsVars: function()
    {
        var template = '<meta name="{1}" content="{2}" />';
        var $head = $('head');
        var metaKeys = ['WT.ti', 'WT.cg_n', 'WT.cg_s'];
        var metaProps  = window.location.pathname.split('/');
        metaProps[0] = $.trim(document.title.replace('- Student Flights', ''));
        
        for(var i=0; i<metaKeys.length; i++)
        {
            if($head.find('meta[name="'+ metaKeys[i] +'"]').length == 0 && typeof metaProps[i] != 'undefined')
            {
                $head.append(SF.format(template, metaKeys[i], metaProps[i]));
            }
        }
    },
    
    popup: function(url, name, width, height)
    {
        var name = (typeof name == 'undefined') ? 'popup' : name;
        var width = (typeof width == 'undefined') ? 380 : width;
        var height = (typeof height == 'undefined') ? 220 : height;
        window.open(url, name, 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+width+',height='+height);
    },
    
    getEnv: function() {
        var host = window.location.host.substring(0, window.location.host.indexOf('.'));
        var env = '';
     
        switch(host)
        {
            case 'int':
                env = 'development';
                break;
     
            case 'stage':
                env = 'staging';
                break;
     
            case 'newstage':
                env = 'staging';
                break;
     
            case 'www':
                env = 'production';
                break;
     
            default:
                env = 'production';
                break;
        }
        
        return env;
    },
    
    inputTextShowHide: function(element)
    {

        if(element.length === 0)
        {
            return;
        }
        
        try
        {
            element.attr('itext', element.val());
            element.bind('focus', function(e)
            {
                if($(this).val() === $(this).attr('itext'))
                {
                    $(this).val('');
                }
            });
            
            element.bind('blur', function(e)
            {
                if($(this).val() == '')
                {
                    $(this).val($(this).attr('itext'));
                }
            });
        }
        catch(e){}
    },
    
    JOBSLOC: {
        'recruitment': 0,
        'about-us': 1,
        'benefits': 2,
        'working-with-us': 3,
        'overview': 0
    },
    
    jobNav: function() {
        var activeTab = window.location.pathname.split('/');
        var activeState = 1;
        
        activeState = SF.JOBSLOC[activeTab[3]];           
    
        if (typeof activeState == 'undefined' && window.location.pathname.indexOf('about-us')) 
        {
            activeState = 1    
        };
                
        var $jobsAccordion = $('#jobsAccordion');
        
        $jobsAccordion.accordion({active: activeState, autoHeight: false});
        
    },
    
    col1TruncateText: function()
    {
        var intLength = 350;
        
        if (window.location.href.indexOf('cheap-holidays-results') >-1) 
        {
            intLength = 250
        };
        
        this.truncateText($('#productListLong div.includes'),{len:intLength});
        
    },
    
    col3LongText: function()
    {
        var $flightsPanel = $('#flightsPanel');
        $('.scrollBox', $flightsPanel).mouseover(function() 
        {
            var boxWidth = $(this).width();
            var textWidth = $('.deal-name', $(this)).width();
        
            if (textWidth > boxWidth) 
            {    
                var animSpeed = textWidth - boxWidth; // 50 pix per sec
                $('.deal-name', $(this)).animate({textIndent: -animSpeed}, 2000);
            }
                    
         }).mouseout(function() {
            $('.deal-name', $(this)).stop().css({textIndent: 0});     
         })
  
    },
    
    searchCookie: function()
    {
        
        var $searchLinks = $('a', '#main-panel').filter('a','#prodResults');
        
        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: '/' });
                            var getQuery = $(this).attr('href');
                            var moreCookie = {};
                            getQuery = getQuery.split('+');
                            var getQueryDestination = unescape(getQuery[2]);
                            queryDestination = getQueryDestination.replace(/["']{1}/gi,'');
                            
                            moreCookie.moreHolidays = queryDestination;

                            $.cookie('SF.HOLIDAYS.COOKIE', JSON.stringify(moreCookie), { path: '/' });  
                           })
                    };    
                } catch(e) 
                {}
            })           
        };
    },
    
    registerGAPageView: function(settings)
    {
        try
        {
            var defaults = 
            {
                basePath: '/on-page-event/enquiry/',
                path: 'general-enquiry',
                item: ''
            }
            settings = (typeof settings != 'undefined') ? $.extend(defaults, settings) : defaults;
            _gaq.push(['_trackPageview', settings.basePath + settings.path + settings.item]);
        }
        catch(e){/* Will Fail if GA script is not on this page */}
    },

    isPageNotFound: function()
    {
        try 
        {
            if( $('#main-panel h1:first').html() == 'Don\'t Give Up') 
            {
                return true;
            }
        } catch(e){}
        
        return false;
        
    },

    embedGoogleAnalytics: function()
    {
        if(window.location.href.indexOf('.html') > -1 )
        {
            return false;
        }
        return true;
    },
    
    embedYahooTracking: function()
    {
        if(window.location.href.indexOf('.html') > -1 || window.location.href.indexOf('product') >-1 || window.location.href.indexOf('international-enquiry') >-1 || window.location.href.indexOf('flights-enquiry') >-1 || window.location.href.indexOf('general-enquiry') >-1)
        {
            return false;
        }
        return true;
    },

    googleTrackPageEvent: function(category, eventType, enquiryType)
    {
        _gaq.push(['_trackEvent', category, eventType, enquiryType ]);
    },
    
    checkkampLink: function()
    {
        if (window.location.href.indexOf('.html') >-1) 
        {
            $('#kampylink, #k_slogan').hide();
        };  
    },
    
    truncateText: function($e, settings)
    {
        if($e.length == 0)
        {
            return false;
        }
        
        var defaults = 
        {
            len: 180,
            finish: '&hellip;',
            stopChar: '.',
            ignoreStopChar: false
        };

        settings = (typeof settings != 'undefined') ? $.extend(defaults, settings) : defaults;
            
        $e.each(function()
        {
            var text = $.trim($(this).text());
            var position = settings.len;
            var prevStrPos = 0;
            var search = true;
            var count = 0;
            
            while(search)
            {       
                // Find position of stop character
                var strPos = prevStrPos + text.substring(prevStrPos).indexOf(settings.stopChar);
                
                // If the prev stop char position and the new position are the same, then we're not finding anything new so break
                if(strPos >= settings.len || (prevStrPos - 1) == strPos || count > 10)
                {
                    search = false;
                    break;
                }
                
                // If position of stop char is less than max length (len), then change position
                if(strPos < settings.len) 
                { 
                    position = strPos;
                    prevStrPos = position + 1;
                }
            }
            
            var truncatedString = (settings.ignoreStopChar) ? text.substring(0, position).replace('&hellip;', '').replace('…', '') : text.substring(0, position);
            
            // If stop position is found before max length, display truncated string without finish as it's a complete sentence
            // unless ignoreStopChar is set to true
            if(position != settings.len)
            {
                $(this).html(truncatedString + settings.stopChar);
                
                if(settings.ignoreStopChar)
                {
                    $(this).html($(this).html().substring(0, $(this).html().length-1) + settings.finish);
                }
            }
            else
            {
                // if stop char not found and length of text is less than max length, append finish to truncated string
                if(truncatedString.indexOf(settings.stopChar) == -1 && text.length < settings.len)
                {
                    $(this).html(truncatedString + settings.finish);
                }
                // We're stuck most likely in the middle of a word so back track until we find the first space char, append finish to truncated string
                else
                {
                    var spaceCharPos = truncatedString.lastIndexOf(' ');
                    $(this).html(truncatedString.substring(0, spaceCharPos) + settings.finish);
                }
            }
        });
    },
    
    cleanUpExPoints: function()
    {   
        try
        {
            var $expointList = $('#main-panel').find('.exitPointsList')
            var strExpointHtml = $expointList.parent().html();
            $expointList.parent().parent().before(strExpointHtml).remove()
        } catch(e)
        {
            
        }

    },

    getExpointCities: function($element, selection)
    {
        try {
            var strCity = '';
            if (typeof selection == 'undefined')
            {
                selection = 'Student'
            };

            $element.change(function()
            {
                strCity = $(this).val();
                if (strCity != '')
                {
                   $.post('/ajax/sitecat', { content: '<securequery template="ausf/tag/landingPage-1col">product_category is "Air Transportation" and product_selection is "'+selection+'" and air_ex_point is "'+strCity+'" and sort price+</securequery>'},
                    function(data)
                    {
                        if (data.length > 0)
                        {
                            $('#productListLong').html(data)
                        }
                        else
                        {
                            $('#productListLong').html('<h2>Sorry, there are no flights departing from '+strCity+'</h2>')
                        }

                    },"html");
                };
            })
        }catch(e)
        {

        }

    },

    getExpointDestinations: function($element, destinations)
    {
        try {
            var strCity = '';
            var arrDestinationList = [];
            var strResults = '';

            arrDestinationList = destinations;

            if (typeof selection == 'undefined') 
            {
                selection = 'Student';
            }
            
            $element.change(function()
            {
                $('#productListLong').find('ul').html('');

                strCity = $(this).val();

                if (strCity != '')
                {
                    for(i=0; i < arrDestinationList.length; i++)
                    {
                        $.ajax({
                            type: 'POST',
                            url: '/ajax/sitecat',
                            data: { content: '<securequery template="ausf/tag/landingPage-1col">first 1 product_category is "Air Transportation" and destination is "' + arrDestinationList[i] + '" and campaign_medium is "15","16" and air_ex_point is "'+strCity+'" and sort price+</securequery>'},
                            dataType: 'html',
                            async: false,
                            success: function(data)
                            {
                                if (data.length > 0)
                                {
                                    strResults = data;
                                    $('#productListLong').find('ul:first').append(strResults);
                                }
                            }
                        });
                    }

                    SF.fixBrokenProductImages($('#productListLong'));

                    if($('#productListLong').find('ul:first').html().length == 0)
                    {
                        $('#productListLong').html('<h2>Sorry, there are no flights departing from '+strCity+'</h2>')                       
                    }
                }
            })
        }catch(e)
        {

        }
 
    },

    fixBrokenProductImages: function($element) {
        $element.find('img').each(function()
        {
			//if(FCL.UTIL.isImageBroken(this))	
			if($(this).fclIsImageBroken() === true)			
            {			
                $(this).attr('src', '/cms_images/Product_Images/image-coming-soon.jpg');
            }
        })
	},
    
    remove133133: function() {
        try {
            $('#productInfoWrapper ul li').each(function() {
                if ($(this).text().indexOf('3000 consultants on 133 133')>0) {
                    $(this).parent().remove();
                }
            });
        }
        catch (e) {
        
        }
	},

    getTodaysTopThree:function(destinations) 
    {
        var _this = this;
        $(function(){
                
            try 
            {
                if( $('#main-panel h1:first').html() == "Don't Give Up")
                {
                            
                    $('#db-top-three').find('ul').html('');
                    
                    if (typeof destinations == 'undefined') {
                        return false
                    }

                    var queryDestinations = destinations.replace(/([^,]*)/gi, '"$1');
                    var exPoint = '"Sydney", "Adelaide", "Brisbane", "Cairns", "Darwin", "Melbourne", "Perth"';
                    $.ajax({
                       type: 'POST',
                       url: '/ajax/sitecat',
                       async: false,
                       data: { content: '<securequery template="ausf/tag/todayTopThree" engine="fm">first 100 destination is '+queryDestinations+' product_category is "Air Transportation" air_ex_point is "'+exPoint+'" and product_selection is "Economy" and product_inclusions like "Return" sort price+</securequery>'},
                       success: function(data){
                           $('#db-top-three').find('ul').append(data);
                           _this.setupHpExPoints();
                       }
                     });
                }
                return false
                
            } catch(e){}
            
            return false;
        })

    },

    /**
     * on page load set the expoint if there is one
     */
    setupHpExPoints: function() {
        var _this = this,
            exPoint = '';

        if($.cookie('SF.exPoint')) {
            $('.sf-expoint').val($.cookie('SF.exPoint'));
        } else {
            $.cookie('SF.exPoint', 'Sydney', { path: '/' });
        }
        exPoint = $('.sf-expoint').val();
        this.setupTopThree(exPoint);
        this.setupHpLeaderBoard(exPoint);
        this.setupFlightsPages(exPoint);
        $('.sf-expoint').bind('change', function(){
            _this.setupTopThree($(this).val());
            _this.setupHpLeaderBoard($(this).val());
            _this.setupFlightsPages($(this).val());
            $('.sf-expoint').val($(this).val());
            $.cookie('SF.exPoint', $(this).val(), { path: '/' });
            //$(function() { FCL.SIGNALS.send('SF','sortSelect'); });
        });
    },

    /**
     * Change the top three flights details at the top of the page
     * 
     * @param exPoint
     */
    setupTopThree: function(exPoint)
    {
        var _this = this;
        $('.top-three-flight').each(function(){
            $(this).slideUp('fast', function(){
                var titles = JSON.parse($(this).find('.db-deal').first().attr("data-top3-titles")),
                    urls = JSON.parse($(this).find('.db-deal').first().attr("data-top3-urls")),
                    prices = JSON.parse($(this).find('.db-price').first().attr("data-top3-prices"));
                if(typeof urls[exPoint]!='undefined') {
                    $(this).find('.db-deal a').attr({href: urls[exPoint], title: titles[exPoint]});
                    $(this).find('.db-price strong').html(prices[exPoint]);
                    $(this).slideDown();
                }
            });
        });
    },

        /**
     * Change the top three flights details at the top of the page
     *
     * @param exPoint
     */
    setupHpLeaderBoard: function(exPoint)
    {
        var _this = this;
        $('.flightBoardPrice').each(function(){
            $(this).slideUp('fast', function(){
                var titles = JSON.parse($(this).attr("data-flight-board-titles")),
                    urls = JSON.parse($(this).attr("data-flight-board-urls")),
                    prices = JSON.parse($(this).attr("data-flight-board-prices")),
                    $priceLink = $(this).find('a');
                if(typeof urls!='undefined' && typeof urls[exPoint]!='undefined') {
                    $priceLink.attr({href: urls[exPoint], title: titles[exPoint]});
                    $priceLink.html(prices[exPoint]);
                } else {
                    $priceLink.attr({href: "", title: ""});
                    $priceLink.html('&ndash;&nbsp;&ndash;&nbsp;&ndash;&nbsp;&ndash;');
                }
                $(this).slideDown();
            });
        });
    },

    sortFlightExpoints: function()
    {
        var select = $('select[name="sf-sortSelect"]');
        var listItem = $('.sortableList li');

        checkList();

        FCL.SIGNALS.listen('SF','sortSelect',function() {
            checkList();
        });

        select.bind('change', function(){
            checkList();
        })

        function checkList(){
            var selectVal = select.val();
            $.each(listItem, function(i, thisItem){
                var title= $(thisItem).find('.leftContent .title');

                if(title.length > 0){
                    var fullTitle = title.html();
                    if(fullTitle.indexOf(selectVal) > -1){
                        $(thisItem).fadeIn();
                    }
                    else
                    {
                        $(thisItem).fadeOut();
                    }
                }
            })
        }
    },


    setupFlightsPages: function(exPoint) {
        // make sure it doesn't effect hotels page
        if(window.location.pathname.indexOf('/accommodation/hotels')>-1){
            // Hides div because it's included in the Presentation template
            $('.exPointWrapper').hide();
            return;
        }
        var elements = $('#main-panel .deal-row'),
            finalCallback = function() {
                var updateElements = $('ul:has(.deal-row)');
                updateElements.each(function(t) {
                    var allItems = $(this).find('li');
                    allItems.sort(function(a,b) {
                        var aPrice = $(a).find('.deal-price').text().replace(/[\$\*,]/gi,''),
                            bPrice = $(b).find('.deal-price').text().replace(/[\$\*,]/gi,'');

                        if(parseFloat(aPrice) > parseFloat(bPrice)) {
                            return 1;
                        } else if(parseFloat(aPrice) < parseFloat(bPrice)) {
                            return -1;
                        } else {
                            return 0;
                        }
                    });
                    $(this).html(allItems);
                    $(this).find('li .deal-row').slideDown(function() {
                        if(t+1 == updateElements.length && $(this).get(0) === $(updateElements[t]).find('li .deal-row:last').get(0)) {
                            loadingIndicator.fadeOut();
                        }
                    });
                });
            },
            loadingIndicator = $('img.loadingIndicator');

        loadingIndicator.fadeIn();

        $.each(elements,function(i) {
            $(this).slideUp('fast', function() {
                if($(this).attr("data-flight-board-titles")) {
                    var titles = JSON.parse($(this).attr("data-flight-board-titles")),
                            urls = JSON.parse($(this).attr("data-flight-board-urls")),
                            prices = JSON.parse($(this).attr("data-flight-board-prices")),
                            $priceLink = $(this).find('.deal-price');
                    if(typeof urls!='undefined' && typeof urls[exPoint]!='undefined') {
                        $(this).attr({href: urls[exPoint], title: titles[exPoint]});
                        $priceLink.html(prices[exPoint]);
                    } else {
                        $(this).attr({href: "", title: ""});
                        $priceLink.html('&ndash;&nbsp;&ndash;&nbsp;&ndash;&nbsp;&ndash;');
                    }
                }
                if((i + 1) == elements.length) {
                    finalCallback();
                }
            });
        });
        //reorder list dependent on price
    },
    
    displayTourWarning: function()
    {
        if($.cookie('tourWarning') != 'true') 
        {
            $.cookie('tourWarning', 'true', { path: '/' }); 
            $.prettyPhoto.open('/wps/wcm/myconnect/student-flights/global/forms/terms-conditions.html?iframe=true&height=200&width=400','','');					
        }
    },
    
    /**
     * If a product has expired, change page to reflect
     */
    checkExpiredProductPage: function()
    {
        $(function()
        {
            if(($('#hiddenProductName').text() == '')&&($('#hiddenProductSku').text() == ''))
            {
                $('#main-panel').prepend('<div class="title-with-bar"><h1>This product has expired</h1></div>');
                $('#expired-product').show();
                $('#right-side-panel').hide();
                
                $('#expired-product').after('<div id="enqFormContainer"></div>');
                
                $('#enqFormContainer').load('/wps/wcm/myconnect/student-flights/global/forms/product-enquiry-form.html #productEnquireForm', function() {
                    $('#productEnquireForm #titleRowProduct').hide();
                    $('#productEnquireForm').css('background','#FFFFFF');
                    SF.PRODUCTENQ.init();
                });
                
                //$.get('/wps/wcm/myconnect/student-flights/global/forms/product-enquiry-form.html', function(data) {
                //    $('#expired-product').after(data);
                //});
                
                //$('#productFormEnquiryWrapper div.form-title').html('Make an enquiry');
                //$('#productFormEnquiryWrapper').next().hide(); // Hide terms and conditions
            }
        });
    },

    /**
     * Simple. To trigger the enquire form modal window when a link with ?enquire=now is present - Waz
    */
    openModalFromUrl: function()
    {
         if(FCL.UTIL.getUrlVar('enquire') === 'now'){
            $('.headerEnquire').trigger('click');
        }
    },

    makeTabs: function(ulTabs, tabContent)
    {

        //Default Action
        $(tabContent).hide(); //Hide all content
        $(ulTabs+' li:first').addClass("active").show(); //Activate first tab
        $(tabContent+':first').show(); //Show first tab content        

        //On Click Event
        $(ulTabs+' li').click(function() {
            $(ulTabs+' li').removeClass("active"); //Remove any "active" class
            $(this).addClass("active"); //Add "active" class to selected tab
            $(tabContent).hide(); //Hide all tab content
            var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
            $(activeTab).fadeIn(); //Fade in the active content
            return false;
        });
    },

    /**
     * Adds <br> tag to raw product inclusions - Dowdy
    */
    fixProductInclusionFormat: function(){
        $('#productInfoWrapper a').next().before('</br>');
    },

    /**
     * Shows live chat in specific site areas/pages and excludes from some page
    */
    showLiveChat: function(){

        $('#sideTabsContainer').delay(1500).fadeIn('slow', function(){
            $('#oggchat').find('.chat').bind('click', function(){
                $('#oggwindowholder').find('img[src*="close-circle.png"]').attr('src','/images/menu/minimize.png');
            })
        });

        var showOnPages = [
        '/travel-tours/',
        '/product/London',
        '/product/bali',
        '/product/fiji',
        '/cheap-flights/thailand/phuket',
        '/cheap-flights/united-states/los-angeles',
        '/cheap-flights/united-kingdom/london'
        ];

        var leaveOffPages = [
        '/travel-tours/tour-results'
        ];

        // Get current pathname
        var location = window.location.pathname.toLowerCase();

        // Show the live chat in these site areas
        $.each(showOnPages, function(i,allowpage){
            var allowpage = allowpage.toLowerCase();
            if(location.indexOf(allowpage)>-1){
                // Exclude the live chat from these pages
                $.each(leaveOffPages, function(i, excludepage){
                    var excludepage = excludepage.toLowerCase();
                    if(location.indexOf(excludepage)!=0){
                        $('#oggchat').show();
                    }
                })
            }
        })
    },

    changeEnquiryFormTitle: function(){
        $('#titleRowGeneral .general').html('Enquire on '+$('.title-with-bar h1').html());
    },

    topFiveToursClone: function(){
        $.ajax({
          url: "/travel-tours/overview",
          success: function(data){
            var list = $(data).find('.mainTopFiveTours').html();
            $('.cloneTopFiveTours').html(list);
            var listItem = $('.cloneTopFiveTours li');
            $.each(listItem, function(){
                var priceBlock = $(this).find('.priceBlock').detach();
                $(this).find('.clearing').after(priceBlock);
            });
          }
        });
    },

    // Changes refUrl to pageUrl in on all forms where refUrl exists - added because of Xcomm changes
    refUrlToPageUrl: function(){
        $('form').find('input[name="refUrl"]').after('<input name="pageUrl" type="hidden" value="" />').remove();
    },

    /**
    *  Scrolls the page with animation to the top element of the product tabs div.
    *  @param (tab) CSS selector
    */
    scrollTo: function(element){
        $('html, body').animate(
        {
            scrollTop: (element.offset().top - 10)
        }, 1200);
    },

    widthHeightClassResizer: function(){

        clasSizer("height-", "width-",true);
        
        function clasSizer(heightPrefix, widthPrefix, absolute) {
            if (absolute) {
                $("div[class*=" + heightPrefix + "]").each(function() {
                    classHeight = $(this).attr('class');
                    boxHeight = parseInt(classHeight.split(heightPrefix)[1], 10);
                    $(this).css('height', boxHeight);
                    absHeight = parseInt(classHeight.split(heightPrefix)[1], 10) - $(this).outerHeight() + parseInt(classHeight.split(heightPrefix)[1], 10);
                    // $(this).css('height', absHeight).html("Height: " + absHeight + " " + $(this).outerHeight() + "px<br>");
                });
                $("div[class*=" + widthPrefix + "]").each(function() {
                    classWidth = $(this).attr('class');
                    boxWidth = parseInt(classWidth.split(widthPrefix)[1], 10);
                    $(this).css('width', boxWidth);
                    absWidth = parseInt(classWidth.split(widthPrefix)[1], 10) - $(this).outerWidth() + parseInt(classWidth.split(widthPrefix)[1], 10);
                    // $(this).css('width', absWidth).append("Width: " + absWidth + " " + $(this).outerWidth() + "px");
                });
            } else {
                $("div[class*=" + heightPrefix + "]").each(function() {
                    classHeight = $(this).attr('class');
                    boxHeight = parseInt(classHeight.split(heightPrefix)[1], 10);
                    // $(this).css('height', boxHeight).html("Height: " + boxHeight + "px<br>");
                });
                $("div[class*=" + widthPrefix + "]").each(function() {
                    classWidth = $(this).attr('class');
                    boxWidth = parseInt(classWidth.split(widthPrefix)[1], 10);
                    // $(this).css('width', boxWidth).append("Width: " + boxWidth + "px");
                });
            }
        }
    }
}

/* END NAMESPACE */

SF.init();

/**
 * Helper for getting results of product queries via AJAX
 * @param {String} query
 * @param {Sring} template
 * @param {Function} [callback=function(){}]
 * @param {String} type Default is html, other supported type is "json"
 * @param {Object} [context=Window] The context the callback will be called in. Default is window.
 * @param {String} [engine=stringtemplate] While current default is "stringtemplate", specify "freemarker" to use Freemarker templates
 */

FCL.UTIL.ajaxQuery = function(query, template, callback, type, context, engine)

{
    var context = context || window;
    var type = type || 'html';
    var engine = engine || 'stringtemplate';
    var query = '<securequery template="{1}" engine="{2}">{3}</securequery>'.fclFormat(template, engine, query);

    $.post('/ajax/sitecat', { content: query }, function(data)
    {
        if(type == 'json')
        {
            data = (new Function('return ' + data))();
        }
        callback.call(context, data);
    }, 'html');
};


