;/**
 *  Filename:			fc.tracking.js
 *  Date Created:		01/06/2011	
 *  Date Modified:		22/06/2011
 *  @author:			frostk, rollsd
 *  Dependencies:		FCL.SIGNALS, FCL.UTIL, FCL.DATETIME
 *  Description:		This file controls the tracking behaviour.
 *  Documentation:      https://sites.google.com/a/flightcentre.com.au/web-services-wiki/web-solutions/development/tracking-code
 *  Usage:				Call FC.TRACKING.init() (not in document.ready()).
 *  Copyright:			© 2010, Flight Centre Ltd. All rights reserved.
 *                     
 *  NOTE:  For now this is only used for enquiry conversion, but has been left
 *         open to facilitate product views, page veiws etc in the future.
 *   
 *  USAGE - listen to 
 *
 *       FCL.SIGNALS.listen('FC.TRACKING', 'track', function( trackObj ){  // do something... });
 *              Use to fire off tracking codes eg campaign tracking codes.
 *
 *       See trackingDefaults object to get an idea of what info is passed through.
 */  

FC.TRACKING =
{
    name: 'FC.TRACKING',

    // This maps Procat categories to the categories the business wants.
    procatMap: {
        	"Air Transportation": "air",
			"Accomodation": "accommodation",
			"Ground Transportation": "transport", 
			"Cruise": "cruise",     
			"Insurance": "insurance",
			"Holiday Package": "holiday-package",
            "Hotel Packages": "hotel-packages",
            "Airfare Packages": "air-packages", 
			"Activities": "activities",
            "Tour": "tour",    
			"Other Categories": "other"
   },
    
	trackingDefaults: 
    {
		/*
		 * Parameters on all pages
		 */
        type: 'view', // 'view', 'enquiry', 'booking', 'search'
        pageTitle: document.title,
        date: new Date(),
        pageUrl: window.location.pathname,
		
        /*
		 * Category - refer to mapping  
         * https://sites.google.com/a/flightcentre.com.au/web-services-wiki/web-solutions/development/tracking-code/google-analytics/event-tracking
		 */        
        category: 'general',
        
		// eg altitude, fareinfo, procat
        platform: '',
		
        /*
		 * Parameters for successful enquiries and bookings
		 */
        conversion: 
        {
            type: '', // eg enquiry: 'email', 'clicktocall'     booking: 'paypal', 'creditcard', 'cba-rewards'
            price: 0,  // digits only eg 189.00 (2dp)
            units: 1,   // Usually 1.
            email: '',
            orderId: function() { d = new Date(); return d.getTime(); }()  // invoice number/booking id, or md5 of email and sku, or timestamp.
        },
		
		/*
		 * Parameters for product pages and product results pages
		 */
        product:
        {
             	
            name: '', // eg 'SYD to BNE',  
            sku: '', // eg '125632', or product name where no SKU eg 'SYD to BNE'
            selection: '',  //  eg 'Economy', 'Other', 'Coach/Escorted Tour'
            supplier: '',  // eg Virgin Blue
			destination: {
				tree: ''// eg 'Mackay,Mackay and Whitsunday Coast,Queensland,Australia'
			}
        },
		
		/*
		 * Parameters for searches - Fareinfo / Product Results Pages
		 */
		search:
		{
			results: 0, // eg number of search results found. ie '3' flights available
			type: '', // eg 'International' or 'Domestic'
			criteria: {
				to: '',
				from: ''
			}
        }
    },
   
    /*
     * @param object trackingObj - an optional tracking object that will overwrite/extend default tracking values above.
     *  Not tracking Obj must be defined if 
     */
    trackEvent: function( trackingObj )
    {

		// get the tracking object
        var trackingObject = this.createTrackingObject( trackingObj );
		
        /*
         * Fire off 'track' signal - plugins that fire off tracking should listen on this signal
         */
        $(document).ready(
            function()
            {
                FCL.SIGNALS.send('FC.TRACKING', 'track', trackingObject);
            }
        )
    },
	
    /*
     * This method creates the tracking object by adopting the defaults, adding any procat information (if available) and finally overwriting this
     * with the object passed in.
     * @param object (optional) the tracking object passed through - if it exists
     * @returns object trackingObject
     */
    createTrackingObject: function( trackingObj  )
    {
		var trackingObject = {};
        var $head = $('head');
        var sku = FC.UTIL.getSku() || '';
        var email = this.getCustomerEmail();
        var product = FC.UTIL.parseProductProperties();
        var metaTags = [];

        $head.find('meta').each(function( i, ele )
        {
            metaTags[$(ele).attr('name')] = $(ele).attr('content');
        });
		
		//International or Domestic (split destination.tree and search whole words for Australia)
		var destinationTreeArray = product['destination.tree'];
		var domesticOrInternational = 'international';
		if (destinationTreeArray) {
			destinationTreeArray = destinationTreeArray.split(',');
			$.each(destinationTreeArray, function(index, value) {
				  if (value == 'Australia') { domesticOrInternational = 'domestic'; }
			});
		}
		
        // Add product information if it exists
        if(product['sku'] && product['sku']!='')
        {
            trackingObject.title = product['title'];
			
            // Map the product category.
            trackingObject.category = this.procatMap[product['category']] || product['category'];
            trackingObject.platform = 'procat';
            
            trackingObject.product = 
            {
                brand: product['brand'],
                name: product['title'],   
                sku: product['sku'], 
                selection: product['productSelection'],  
                supplier: product['supplierName'],
				destination: {
					tree: product['destination.tree'],
                    name: product['destination']
				}
            }
			
            trackingObject.search = 
            {
				results: product['numResults'],
				type: domesticOrInternational,
				criteria: {
					from: product['airExPoints'],
					to: product['destination']
				}
            }
            
            // Add conversion properties
            trackingObject.conversion = 
            {
                type: '',
                price: product['price'].replace(/[$,]/g,''),
                units: 1,   // Usually 1.
                email: this.getCustomerEmail()
            }
        }

        return $.extend(true, {}, this.trackingDefaults, trackingObject, trackingObj );
        
    },
    
    /*
     *  Returns the cusomter's email (if found) or empty string.
     *  @return string
     */
    getCustomerEmail: function(){

        // Check if in an iFrame (selector for injected iframe '.inline-enquiry-ctn iframe')
		jQuery.fn.exists = function(){return jQuery(this).length>0;}
		if ($('.inline-enquiry-ctn iframe').exists()) {
			var iframeSrc = $('.inline-enquiry-ctn iframe').attr('src');
			var emailRegex= /[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i;
			customersEmail = iframeSrc.match(emailRegex);
		}else {
			customersEmail = FCL.UTIL.getUrlVar('email');
		}
        return customersEmail;

    }

};

/**
 * E-channel Yahoo Live and Yahoo Domestic
 * Importance: Critical
 * Purpose: Paid search conversion tracking
 * Conditions:  All enquiry and bookings
 * Contact: David Tait
 * Last updated: 19/10/2011
 */
    FCL.SIGNALS.listen('FC.TRACKING', 'track', function( trackObj )
    {
        
        try {
		
			// Only fire off Yahoo Live tracking for enquiry events.
			if(trackObj.type && trackObj.type=='enquiry')
			{
				// Yahoo Live
				window.ysm_customData =  {};
				window.ysm_customData.conversion = 'event=1,transId=,currency=AUD,amount=';
				window.ysm_accountid  = "1GJSSMRCGI3VORJQQ1RO0AHTB4S"; 
				$.ajax({
				  url: '//srv2.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid='+window.ysm_accountid,
				  dataType: 'script',
				  success: function(){
					  
					  //Fix Yahoo tracking so second tracking fires off (by this stage first script has fired off)
					  window.pm_hasScriptRun = undefined;
					  
					  // Yahoo Domestic  
					  window.ysm_customData = {};
					  window.ysm_customData.conversion = 'event=1,transId=,currency=AUD,amount=';
					  window.ysm_accountid  = "1PCGSOEAO04RHPQ7PP1H1F7R0LO"; 
					  $.ajax({
						url: '//srv2.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid='+window.ysm_accountid,
						dataType: 'script'
					  });
				 }
				});
			}
         }
         catch(e){ }
    });

/**
 * DGM Tracking on Used on Product Conversions
 * Importance: Low
 * Purpose: Track conversions via display advertising campaigns
 * Conditions:  All enquiry
 * Contact: Jordan Payne
 * Last updated: 19/10/2011
 */
    FCL.SIGNALS.listen('FC.TRACKING', 'track', function( trackObj )
    {
        if(trackObj.type == 'enquiry' && trackObj.category != 'general')
        {
            // Need to confirm if this is necessary.
            var x = trackObj.platform ==='fareinfo' ? 'r'  : 'sp';
            $('body').append('<img height="1" width="3" src="http://www.s2d6.com/x/?x='+ x +'&h=16628&o='+trackObj.conversion.orderId+'&g=313683428782&s=1.00&q=1" />');
        }                  
    });


/**
 * DoubleClick Floodlight Tag
 * Importance: Low
 * Purpose: Track conversions via display advertising campaigns
 * Conditions:  All enquiry
 * Contact: Jordan Payne
 * Last updated: 19/10/2011
 */
    FCL.SIGNALS.listen('FC.TRACKING', 'track', function(trackObj)
    {
        if(trackObj.type === 'enquiry')
        {
            $('body').append('<iframe src="https://fls.doubleclick.net/activityi;src=986775;type=fligh426;cat=fc-al303;ord=' + trackObj.conversion.orderId + '?" width="1" height="1" frameborder="0"></iframe>');
        }
    });


/**
 * ClixGalore
 * Importance: Intermediate
 * Purpose: Track conversions through Affiliates
 * Conditions:  All enquiry
 * Contact: Jordan Payne
 * Last updated: 19/10/2011
 */
    FCL.SIGNALS.listen('FC.TRACKING', 'track', function(trackObj)
    {
        if(trackObj.type === 'enquiry')
        {
            var clixGaloreImg = '<img src="https://www.clixGalore.com/AdvTransaction.aspx?AdID=8907&OID=' + trackObj.conversion.orderId + '" height="0" width="0" border="0">';
            $('body').append(clixGaloreImg);
        }
    });


/**
 * E-channel Google ad campiagn tracking
 * Importance: Critical
 * Purpose: Paid search conversion tracking
 * Conditions:  All enquiry
 * Contact: David Tait
 * Last updated: 19/10/2011
 */
    FCL.SIGNALS.listen('FC.TRACKING', 'track', function(trackObj)
    {
        
        try 
        {
            var  gaImg = '<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/';
            
            /*
             *   Add tracking for product email enquiry
             */
            if(trackObj.type === 'enquiry' && trackObj.category != 'general' && trackObj.conversion.type==='email')
            {
             $('body').append( gaImg + '1039978287/?label=tZr6CInqpAEQr57z7wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1031898246/?label=IUJLCLyAlwEQhomG7AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997233312/?label=7AutCNCNhQIQoKXC2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1005948284/?label=NKJ3CITe9QEQ_JrW3wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997733583/?label=FHPiCPHP8wEQz-ng2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '996785340/?label=67NJCJzl-wEQvPmm2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '998925907/?label=ZcczCI2r6gEQ08yp3AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1002204763/?label=RtX9CMWV_wEQ29zx3QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1035401958/?label=1KToCKjYrAEQ5vXb7QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1030351407/?label=spZwCKH5ngEQr9Sn6wM&amp;guid=ON&amp;script=0"/>')
            }

            /*
             *   Add tracking for general email enquiry
             */
            else if(trackObj.type === 'enquiry' && trackObj.category === 'general' && trackObj.conversion.type==='email')
            {
        
             $('body').append( gaImg + '1039978287/?label=qR1XCP_upAEQr57z7wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1031898246/?label=RdIYCP6DlwEQhomG7AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997233312/?label=3RpxCJiUhQIQoKXC2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1005948284/?label=fPdFCMzk9QEQ_JrW3wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997733583/?label=uOa1CLnW8wEQz-ng2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '996785340/?label=E7KlCOTr-wEQvPmm2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '998925907/?label=gMoVCNWx6gEQ08yp3AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1002204763/?label=0Om8CI2c_wEQ29zx3QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1035401958/?label=xU7MCJDbrAEQ5vXb7QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1030351407/?label=9lZOCIn8ngEQr9Sn6wM&amp;guid=ON&amp;script=0"/>')
            }
            
            /*
             *  Add click-to-call tracking 
             */
             else if (trackObj.type === 'enquiry' && trackObj.conversion.type=='clicktocall')
            {
              
             $('body').append( gaImg + '1039978287/?label=znu0CInSpwEQr57z7wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1031898246/?label=2uhOCKrfmQEQhomG7AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997233312/?label=GxScCJCVhQIQoKXC2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1005948284/?label=CivpCMTl9QEQ_JrW3wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '997733583/?label=8pAbCLHX8wEQz-ng2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '996785340/?label=xHwACNzs-wEQvPmm2wM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '998925907/?label=Y5rcCM2y6gEQ08yp3AM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1002204763/?label=wNkNCIWd_wEQ29zx3QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1035401958/?label=oyuJCPLRrwEQ5vXb7QM&amp;guid=ON&amp;script=0"/>' +
                               gaImg + '1030351407/?label=8aeSCI2RoQEQr9Sn6wM&amp;guid=ON&amp;script=0"/>')
            }
       }
       catch(e) {}
        
    });


/**
 * Google Event tracking
 * Importance: Critical
 * Purpose: General tracking analytics
 * Conditions:  All searches, enquiries and bookings.
 * Contact: Jordan Payne
 * Last updated: 19/10/2011
 */
	FCL.SIGNALS.listen('FC.TRACKING', 'track', function( trackObj ) {
        
		try {
			
			// if there is an equiry type defined (we are processing an enquiry)
			if (trackObj.conversion.type) {
			
                // If its a tour about product change the category to "tour-ta"
                var category = trackObj.category;
                if( trackObj.product.brand == 'Tour About loaded products')
                {
                     category = 'tour-ta'; 
                }

				// Enquiry tracking
				if(trackObj.type === 'enquiry') 
                {
                    
     

                    // Fareinfo enquiries
                    if(trackObj.platform === 'fareinfo')
                    {
                        _gaq.push(['_setCustomVar',1,'product',trackObj.product.name]);
                        _gaq.push(['_setCustomVar',2,'supplier',trackObj.product.supplier]);
                        _gaq.push(['_setCustomVar',3,'selection',trackObj.product.selection]);
                        _gaq.push(['_setCustomVar',4,'sku',trackObj.product.sku]);
                        _gaq.push(['_setCustomVar',5,'price',trackObj.conversion.price]);
                    }
                    
                    // Procat enquiries
                    else if (trackObj.platform === 'procat')
                    {
                        

                        _gaq.push(['_setCustomVar',1,'product',trackObj.product.name]);
                        _gaq.push(['_setCustomVar',2,'destination',trackObj.product.destination.name]);
                        _gaq.push(['_setCustomVar',3,'selection',trackObj.product.selection]);
                        _gaq.push(['_setCustomVar',4,'sku',trackObj.product.sku]);
                        _gaq.push(['_setCustomVar',5,'price',trackObj.conversion.price]);
                    }
                    
                     // Track the enquiry   
                    _gaq.push(['_trackEvent', category, trackObj.type, trackObj.conversion.type]);

				}
                
                // Search tracking
				if(trackObj.type === 'search') 
                {
                     if(trackObj.platform === 'fareinfo')
                    {
                        _gaq.push(['_setCustomVar',1,'search', trackObj.search.criteria.from + ' to ' + trackObj.search.criteria.to]);
                        _gaq.push(['_setCustomVar',2,'class', trackObj.search.criteria.cabinClass]);
                        _gaq.push(['_setCustomVar',3,'route-type', trackObj.search.criteria.routeType]);
                        _gaq.push(['_setCustomVar',4,'type', trackObj.search.type]);
                        _gaq.push(['_setCustomVar',5,'results', trackObj.search.results]);
                        _gaq.push(['_trackEvent', category, trackObj.type, trackObj.search.criteria.from + ' to ' + trackObj.search.criteria.to ]);
                    }
                }
				
			}
			
		}
		catch(e){ console.log(e)}
	});

