/**
 * Functions for tracking of events (such as enquiry forms, booking forms, fareinfo, etc)
 *
 * @author          Scott Warren
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * requires        standard.js - specifically the SF.parseProductProperties() function
 */

;SF.TRACKING =
{
    name: 'SF.TRACKING',

    eventTracking:function()
    {

        /*
         * this function needs an object (which needs to be called SF.TRACKING.trackEvent) setup on the success event for tracking (i.e. if the enquiry was successful)
         * for example:
         *  SF.TRACKING.trackEvent = {
         *     'action': 'enquiry',
         *     'type': 'email'
         *  };
         * -------------
         * type is the opt_label - what type of form or event - normal values: (email | clicktocall | tundra-dom | ezires | travel-shop | quickbeds | fareinfo | covermore)
         * action what is the form doing - normal values: (enquiry | booking | search)
         * note: it needs to be called SF.TRACKING.trackEvent for this function to work
         * after the object has been setup, call this function
        */ 
        // map the actual meta tag result with what we want to send to GA
        // note: add categories to this object when there are categories that aren't listed
        try
        {
            var procatMap = {
                'Air Transportation': 'air',
                'Accommodation': 'accommodation',
                'Accomodation': 'accomodation',
                'Land Transport': 'transport',
                'Ground Transportation':'transport',
                'Cruise': 'cruise',
                'Insurance': 'insurance',
                'Holiday Package': 'packages',
                'Hotel Package': 'packages',
                'Airfare Package': 'packages',
                'Holiday Packages': 'packages',
                'Hotel Packages': 'packages',
                'Airfare Packages': 'packages',
                'Activities': 'activities',
                'Tour': 'tour',
                'none': 'general'
            };
            // if there is product category is set then set prodCategory with its' value otherwise use none to signify a general enquiry
            var prodCategory = SF.parseProductProperties().category ? SF.parseProductProperties().category : 'none';
            // if there is no matching result in the procatMap object then set category to other as there is no matching category and it's not a general enquiry

            var category = procatMap[prodCategory] ? procatMap[prodCategory] : 'other';
            // if enquiry came from fareinfo set fareinfo key:value values otherwise use the normal set

            if (SF.TRACKING.trackEvent.type == 'email')
            {

                // If general enquiry
                if (category == 'general')
                {
                    //If enquiry is coming from inside the product-enquiry-form.html
                    if(window.location.pathname.indexOf('product-enquiry-form.html')>-1){
                        var customVars = {
                            'product': FCL.UTIL.getUrlVar('packageName'),
                            'destination': FCL.UTIL.getUrlVar('destinationName'),
                            'supplier': FCL.UTIL.getUrlVar('supplierName'),
                            'sku': FCL.UTIL.getUrlVar('sku'),
                            'price': FCL.UTIL.getUrlVar('packagePrice')
                        }
                    }

                    //If enquiry is coming from inside the product-enquiry-form.html
                    if(window.location.pathname.indexOf('general-enquiry-form.html')>-1){
                        prodCategory = FCL.UTIL.getUrlVar('productCategory');
                        category = procatMap[prodCategory] ? procatMap[prodCategory] : 'general';

                        if(category == 'general'){
                            // update nothing
                        }

                        else{
                                // Add product details
                                var customVars = {
                                'pageUrl': FCL.UTIL.getUrlVar('pageUrl'),
                                'enquireLocation': FCL.UTIL.getUrlVar('productEnquiryType')
                            }
                        }
                    }
                    
                }
                else if (category == 'other')
                {
                    var customVars = {
                        'product': SF.parseProductProperties().packageName,
                        'destination': SF.parseProductProperties().destination,
                        'supplier': SF.parseProductProperties().supplierName,
                        'sku': SF.parseProductProperties().sku,
                        'price': SF.parseProductProperties().price
                    }
                }
                
            }
            else if (SF.TRACKING.trackEvent.type == 'clicktocall')
            {
                if (SF.TRACKING.getSku() == "null")
                {
                    category = "general";

                    // Check if CTC is in modal & on product page
                    if(window.location.pathname.indexOf('ctc-form-modal.html')>-1){

                        prodCategory = FCL.UTIL.getUrlVar('productCategory');
                        category = procatMap[prodCategory] ? procatMap[prodCategory] : 'other';

                        var customVars = {
                            'pageUrl': FCL.UTIL.getUrlVar('pageUrl'),
                            'ctcLocation': FCL.UTIL.getUrlVar('ctcLocation')
                        }
                        
                    }
                }
                else
                {
                    var customVars = {
                        'product': SF.parseProductProperties().packageName,
                        'destination': SF.parseProductProperties().destination,
                        'supplier': SF.parseProductProperties().supplierName,
                        'sku': SF.TRACKING.getSku(),
                        'price': SF.parseProductProperties().price
                    }
                }
            }
            else if (SF.TRACKING.trackEvent.type == 'fareinfo')
            {
                var customVars = {
                    'product': SF.getUrlVars().depStr+' to '+SF.getUrlVars().destStr,
                    'engine': 'fareinfo',
                    'supplier': $('.fare-selected .airline-name').html(),
                    'route-type': FAREINFO.modelJson.routeType,
                    'price': $('.fare-selected .gross-price .pricevalue').html()
                };
                // set category to be air-fareinfo
                category = 'air-fareinfo';
                // resets email as it's type
                SF.TRACKING.trackEvent.type = 'email';
            }
            else if (SF.TRACKING.trackEvent.type == 'search')
            {

                var customVars = {
                    'results': (FAREINFO.modelJson.responseJson.fares.length).toString(),
                    'search': FAREINFO.modelJson.responseJson.journey.departureCity.code + ' to ' + FAREINFO.modelJson.responseJson.journey.arrivalCity.code,
                    'class': FAREINFO.modelJson.responseJson.cabinClass,
                    'route-type': FAREINFO.modelJson.responseJson.journey.journeyType,
                    'type': 'international'
                };
                
                // Set category as fareinfo
                category = 'fareinfo';
            }
            // try fire the tracking off otherwise catch the error(s)
            // if customVars exists and if the action is enquiry push customVars through _gaq.push)[.. ]); etc
            if (typeof customVars != "undefined" && SF.TRACKING.trackEvent.action == "enquiry")
            {
                var count = 1;
                $.each(customVars, function(key, value)
                {
                    if (key == 'price') { customVars[key] = customVars[key].replace(/[^\d.]/g, ""); }
                    // alert("_gaq.push(['_setCustomVar',"+count+", '" + key + "', '" + customVars[key] + "']);");
                    _gaq.push(['_setCustomVar', count, key, customVars[key]]);
                    count++;
                })
            }
            // alert("_gaq.push(['_trackEvent', '" + category + "', '" + SF.TRACKING.trackEvent.action + "', '" + SF.TRACKING.trackEvent.type + "']);");
            _gaq.push(['_trackEvent', category, SF.TRACKING.trackEvent.action, SF.TRACKING.trackEvent.type]);
        }
        catch (err)
        {
            FCL.UTIL.log(err);
        }
    },
    getSku: function()
    {
        var url, sku;
        
        sku = $('#productSku');
        if($('#productSku').length > 0)
        {
            return sku.text(); 
        }
        try
        {
            url = window.location.pathname;
            sku = url.substring( url.lastIndexOf('-') ).match(/\d+/);
            if(sku == null)
            {
                return 'null';
            }
            return sku[0];
        }
        catch(e)
        {
            return 'null';
        }
    }
};
