;/**
  * Functions that are used in various areas across the site that don't belong to a specific namespace or
  * unit of functionality
  */
ET = 
{
    /**
     * printLinks, prettyPhoto and Add This are the only calls executed on nearly every page
     */ 
    init: function()
    {         
        $(document).ready(function() 
        {
            try
            {
                ET.enquiryPageLink();
                ET.printLinks();
                ET.prettyPhoto();
                ET.setupAddThis();
                ET.customPageBackground();
            }
            catch(e){}
        });
    },
    
    /**
     * If Tourism Media page was accessed within 3 clicks or less from a content page, change
     * phone number to be Tourism Media enquiry line for ET
     * This needs to be done in the header and in content areas
     */
    setPhoneNumber: function()
    {
        /*___ SET PHONE NUMBER IN HEADER ___*/
        var img = '<img width="318" height="30" alt="Escape Travel - Call {1}" src="{2}">';
                
        // Defaults (Standard ET phone details)
        var defaultPhoneNumber = '1300 556 855';
        var defaultPhoneImgSrc = '/images/general/et-phone-number.gif';
        var tourismMediaPhoneNumber = '1300 640 413';
        var tourismMediaPhoneImgSrc = '/images/general/et-tm-phone-number.gif';
        
        // this code changes the phone number on the Vietnam specials page Delete once special is over
        if(window.location.href.indexOf('vietnam-special') >= 0)
        {
            $('#phoneNumberCell').html(ET.UTIL.format(img, '1300 788 748', '/cms_images/Product_Images/vietnam-specials/phone-number-1300-788-748.gif'));
            $(document).ready(function()
            {
                $('#productLeftColumn #enquireContainer span, #expiredProduct p, #subscribeNewsletterBottom .ulLinks li, #fullContentCell p').each(function()
                {
                    $(this).html($(this).html().replace(defaultPhoneNumber, '1300 788 748'));   
                });
            }); 
            return;
        }
        
        if(ET.TM.isWithinThreeClicks())
        {
            $('#phoneNumberCell').html(ET.UTIL.format(img, tourismMediaPhoneNumber, tourismMediaPhoneImgSrc));
        }
        else
        {
            $('#phoneNumberCell').html(ET.UTIL.format(img, defaultPhoneNumber, defaultPhoneImgSrc));
        }
        
        /*___ SEARCH FOR PAGE CONTENT WHERE ET PHONE NUMBER EXISTS ___*/
        if(ET.TM.isWithinThreeClicks())
        {
            $(document).ready(function()
            {
                $('#productLeftColumn #enquireContainer span, #expiredProduct p, #subscribeNewsletterBottom .ulLinks li, #fullContentCell p').each(function()
                {
                    $(this).html($(this).html().replace(defaultPhoneNumber, tourismMediaPhoneNumber));   
                }) 
            });
        }
    },
    
    enquiryPageLink: function()
    {
        // Prepend referring url so portable enquiry form can report on what page the user was on when generating this enquiry
        var referringURLParam = '?referringUrl='+ window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.search;
        $('#navbarEmail a').attr('href', $('#navbarEmail a').attr('href') + referringURLParam);
    },

    setupAddThis: function()
    {
        window.addthis_pub = 'escapetravelau';
        $('#addThisLink').bind('mouseenter', function()
        {
            return addthis_open(this, '', '[URL]', '[TITLE]');
        })
        .bind('mouseleave', function() { addthis_close(); })
        .bind('click', function(e) 
        { 
            e.preventDefault();
            return addthis_sendto();
        });
        $('body').append('<script type="text/javascript" src="http://s7.addthis.com/js/200/addthis_widget.js"></script');
    },
    
    /**
     * Add print functionality to matching links
     */
    printLinks: function()
    {
        $('.print').bind('click', function(e)
        {
            e.preventDefault(); 
            try{
                pageTracker._trackPageview('/on-page-event/print?page=' + document.location.pathname + document.location.search);
            }catch(e){}
            window.print();
        });  
    },    
    
    /**
     * Attach prettoPhoto (lightbox) functionality to matching links
     */
    prettyPhoto: function()
    {
        // Initialise Pretty Photo
        $('a[rel="prettyPhoto"]').prettyPhoto();
        
        /*___ Setup portable enquiry form url for iframe ___*/
        
        var portableEnquiryForm = '/wps/wcm/myconnect/escape-travel/global/forms/portable-enquiry-form.html?{1}iframe=true&height=378&width=796';

        // Prepend referring url so portable enquiry form can report on what page the user was on when generating this enquiry
        var prependUrl = 'referringUrl='+ window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.search + '&';
        
        /**
         * If we're on a page and we're less than or equal to 3 clicks away from a Tourism Media page, we need
         * to embed the tourismMediaTracking=true in the url for the ET.ENQUIRY script to pickup in the modal iframe
         * as if this current page load is the 3rd click, the loading of the iframe will technically be the 4th click.
         *
         * However because the user hasn't navigated to another page, we need to force the issue that enquiry in the
         * modal is still valid, hence the embedding of the variable.
         */
        if(ET.TM.isWithinThreeClicks())
        {
            prependUrl += 'tourismMediaTracking=true&';
        }
        
        // Set new value of pretty Photo url
        $('#leftColumn a.portableEnquiryForm').attr('href', ET.UTIL.format(portableEnquiryForm, prependUrl));
                
        // Capture on click and trigger Pretty Photo manually
        $('#leftColumn a.portableEnquiryForm').bind('click', function(e)
        {
            e.preventDefault();
            // Pretty Photo is not necessarily embedded on every page, hence try, catch
            try { $.prettyPhoto.open($(this).attr('href'), '', 'Online Enquiry'); }
            catch(e) { /* Will fail if prettyPhoto is not available */ }
        });
    },
    
    /** 
     * Randomly display an image in the footer 
     */ 
    loadRandomFooterImage: function()
    {
        var randomNum = Math.floor(Math.random() * ET.SETTINGS.numFooterImages + 1);
        $('#footerMainCell img').attr('width','344').attr('src', ET.SETTINGS.footerImageBaseUrl + 'consultant'+ randomNum + '.png').show();
    },
            
    /**
     * Launch subcsirbe form in a Pretty Photo box
     */
    subscribeFormLauncher: function()
    {
        var form_path = '/wps/wcm/connect/escape-travel/global/forms/email-subscribe-form.html?email=email&iframe=true&width=400&height=380';
        $('#subscriptionCell form, #subscribeNewsletterBottom form').bind('submit', function(e)
        {
            e.preventDefault();
            
            // Replace email to path so email subscribe form can get it and insert it in form
            var email = $(this).find('#sub_email').val();
            form_path = form_path.replace('email=email', 'email='+ email);
            $.prettyPhoto.open(form_path, '', $('#subscribe-to-newsletter').attr('title'));
        });
        
        // Removes default value text when field receives focus
        ET.FORMS.inputTextShowHide($('#sub_email, #ft_email'));
    },
    
    /**
     * Make sub level navigation in left menus work in IE6
     */
    sideLinksFlyOut: function()
    {
        if(window.attachEvent)
        {
            $('.sideLinksColumn ul > li').each(function()
            {
                $(this).css('display', 'inline');
            });

            $('.sideLinksColumn ul > li').bind('mouseenter', function()
            {
                $(this).addClass('iehover');
            });
            
            $('.sideLinksColumn  ul > li').bind('mouseleave', function()
            {
                $(this).removeClass('iehover');
            });
        }
    },
    
    /**
     * Provide defaults for required GIMP values if they are missing in a form
     */
    gimpCheckRequiredFields: function($form, urlStr)
    {
        return ET.GIMP.checkRequiredFields($form, urlStr);
    },
    
    /*
     * Take the supplied jQuery form referrence, collect all relevant form data, build a GIMP URL string and return it
     */
    gimpProcessForm: function($form)
    {
        return ET.GIMP.processForm($form);
    },
    
    /**
     * Take an object of MAILER settings, build a URL string and return it
     */
    getMailerUrl: function(mailerSettings)
    {
        var mailer = $.extend(ET.SETTINGS.MAILER, mailerSettings);
        var mailerUrl = ET.SETTINGS.MAILER.baseUrl;
        
        $.each(mailer, function(key, val)
        {
            if(val != '' && key != 'baseUrl')
            {
                mailerUrl += key + '=' + ET.UTIL.filterInputText(val) + '&';
            }
        });
        
        return mailerUrl.substring(0, mailerUrl.length-1);
    },
    
    /**
     * Grab the title and break url down into segments to fill out the rest of the variables
     */
    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('- Escape Travel', ''));
        
        for(var i=0; i<metaKeys.length; i++)
        {
            if($head.find('meta[name="'+ metaKeys[i] +'"]').length == 0 && typeof metaProps[i] != 'undefined')
            {
                $head.append(ET.UTIL.format(template, metaKeys[i], metaProps[i]));
            }
        }
    },
    
    registerGAPageView: function(settings)
    {
        try
        {
            var defaults = 
            {
                basePath: '/on-page-event/enquiry/',
                path: 'general-enquiry'
            }
            settings = (typeof settings != 'undefined') ? $.extend(defaults, settings) : defaults;
            pageTracker._trackPageview(settings.basePath + settings.path);
        }
        catch(e){/* Will Fail if GA script is not on this page */}
    },
    
    cleanProductInclusionContent: function($elements)
    {
        $('div.singleColumnShortPackage').each(function()
        {
            var a = $('<div>').append($(this).find('a.readMore').clone()).remove().html();
            $(this).find('a.readMore').remove();
            ET.UTIL.truncateText($(this).find('p.packageDescription'), { len: 150, finish: '&hellip;' + a, ignoreStopChar: true });
            ET.UTIL.truncateText($(this).find('div.includesContent'), { len: 150, ignoreStopChar: true });
        });
    },
    
    embedGoogleAnalytics: function()
    {
        if(window.location.href.indexOf('.html') > -1 && window.location.href.indexOf('portable-enquiry-form') < 0 )
        {
            return false;
        }
        
        return true;
    },
    
    isPageNotFound: function()
    {
        if( $('#contentRight h1:first').html() == 'Page Not Found' )
        {
            return true;
        }
        
        return false;
    },
    
    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;
    },

    customPageBackground: function()
    {
        $(function()
        {
            $('body').append('<div id="pageBackgrounds">'+
                                 '<div id="pageBackgroundLeft"></div>'+
                                 '<div id="pageBackgroundRight"></div>'+
                             '</div>');
            $('#pageBackgrounds').css({opacity: 0, display: 'block'}).animate({opacity: 1}, 2000);
        });
    }
};
ET.init();