/*
    STUDENT FLIGHTS: Namespacing for global functions
    VERSION: 1.0
    
*/

SF = {
    
    init: function() {
            
        $(document).ready(function(){
            SF.printVersion();
            SF.menu();
            SF.flightTabs();
            //SF.tabDatePicker();
            SF.slider();
            SF.newsTicker();
            SF.taxFlashHover();
            SF.taxFlashOut();
            SF.enquireToolTip();
            SF.searchCookie();
            SF.col3LongText();
            SF.col1TruncateText();
            SF.checkkampLink();

        });
        
        $(window).load(function(){
            SF.fixBrokenImage();
        });
    },
    
    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
    },
    
    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;
    },
    
    getQueryVariable:function(key) 
    { 
        return this.getUrlVars('', key);
    },
    
    menu: function() {
        try{
            $("ul#nav").superfish({
                autoArrows:  false,
                animation:   {opacity:'show',height:'show'},
                speed:       'fast' 
            })
            .find('ul').bgIframe();        
        } catch(e){
            
        }
    },
   
    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,
                continous: 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.fixBrokenImage();

                    if($('#productListLong').find('ul:first').html().length == 0)
                    {
                        $('#productListLong').html('<h2>Sorry, there are no flights departing from '+strCity+'</h2>')                       
                    }
                }
            })
        }catch(e)
        {

        }
 
    },

    fixBrokenImage: function()
    {
        $('img','#productListLong').each(function()
        {
            if((typeof this.naturalWidth != "undefined" &&
                this.naturalWidth == 0 )
                || this.readyState == 'uninitialized' )
            {
                $(this).attr('src', '/cms_images/Product_Images/image-coming-soon.jpg');
            }

        })
    },

    getTodaysTopThree:function(destinations) 
    {  
        $(function(){
                
            try 
            {
                if( $('#main-panel h1:first').html() == "Don't Give Up") 
                {
                            
                    $('#db-top-three').find('ul').html('');
                    
                    if (typeof destinations == 'undefined') {
                        return false
                    };
                    
                    destinations = destinations.split(',')
                         
                    arrDest = [];
                    
                    arrDest.push(destinations[0], destinations[1], destinations[2]);
    
                    for (var i=0; i < arrDest.length; i++) 
                    {
                        $.ajax({
                           type: 'POST',
                           url: '/ajax/sitecat',
                           async: false,
                           data: { content: '<securequery template="ausf/tag/todayTopThree">first 1 destination is "'+arrDest[i]+'" product_category is "Air Transportation"  and campaign_medium is "17" sort price+</securequery>'},
                           success: function(data){
                            $('#db-top-three').find('ul').append(data)
                           }
                         });
                    };    
                }
                return false
                
            } catch(e){}
            
            return false;
        })

    },
    
    setHpLeaderBoardLinks: function()
    {
        var $objFlights = jQuery('#hpFlightBoard').find('.flightBoardPrice');
        var strLink = '';
        
        $.each($objFlights, function(k,i)
        {
            strLink = $(this).find('a').attr('href');
            $(this).bind('click', function()
            {
                window.location.href = strLink;
            })
        })
    },
    
    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','','');					
        }
    }
    
}

/* END NAMESPACE */

SF.init();


