/**
 * @class FC.PT
 * @parent FC
 * @tag fc, page tracker
 *
 * Page visit tracker
 *
 * @author          Ryan Blunden
 * @modifiedby      $LastChangedBy: deerings $
 * @copyright       Copyright Flight Centre Ltd. All rights reserved.
 * @version         $Revision: 11221 $
 * @lastmodified    $Date: 2011-07-27 11:15:00 +1000 (Wed, 27 Jul 2011) $
 */

(function($)
{
    // Bail if jQuery or the cookie plugin is undefined
    if(typeof $ === 'undefined' || typeof $.cookie === 'undefined')
    {
        return;
    }

    // Setup FC namespace if it hasn't been setup already
    window.FC = window.FC || {};

    FC.PT =
    {
        name: 'FC.PT',

        pages: [],

        pageTrackLimit: 10,

        pageUrl: '',
        
        init: function()
        {
            this.setup();
            this.trackPage();
        },

        /**
         * Setup the tracking cookie and split apart its current value, assigning result to pages for potential later
         * use
         */
        setup: function()
        {
            if($.cookie('FC.PT.tracker') === null)
            {
                $.cookie('FC.PT.tracker', ' ', { path: '/' });
            }

            this.pages = $.cookie('FC.PT.tracker').split(',');
        },

        /**
         * Track the current page, adding it to the pages array. Check page track limit and remove first tracked page
         * in array if over limit.
         */
        trackPage: function(force)
        {
            if(this.getUrlVar('iframe_embed') === 'true' && force == false)
            {
                return;
            }
			
			/*Update 26/07/2011 - Restrict the page url to only base name with no query string as it was breaking GIMP forms*/
            this.pageUrl = window.location.pathname;
			
			//catch special cases where ampersand (&) is used for query strings
			this.pageUrl = (this.pageUrl.indexOf('&') > 0) ? this.pageUrl.substring(0,this.pageUrl.indexOf('&')) : this.pageUrl;
			
			//catch special cases where Question Mark (?) is used for query strings
			this.pageUrl = (this.pageUrl.indexOf('?') > 0) ? this.pageUrl.substring(0,this.pageUrl.indexOf('?')) : this.pageUrl;
			
			//cap at 100 characters (10 pages x 100 = 1000) any more than this and GIMP breaks.
			this.pageUrl = (this.pageUrl.length > 100) ? this.pageUrl.substring(0,100) : this.pageUrl;
			
			//add to array of pages
			this.pages.push(this.pageUrl); 
			
			//record the last 10 pages (shift the first one off)
			if(this.pages.length > this.pageTrackLimit)  {
				this.pages.shift();
            }
			
			this.save();
        },
        
        /**
         * Save pages information to cookie as comma separated list
         */
        save: function()
        {
            var buildCookie = this.pages.join(',');
            $.cookie('FC.PT.tracker', buildCookie, { path: '/' });
        },
        
        /**
         * Clear cookie info
         */
        reset: function()
        {
            this.pages = [];
            this.save();
        },

        /**
         * Apply the current page values to the $form
         * @param {Object} $form jQuery enquiry form instance
         * @return {Object} jQuery enquiry form instance
         */
        applyTrackedPagesToForm: function(form)
        {                   
            var $form = $(form),
                input = '<input type="hidden" name="pageUrl{1}" value="{2}" />',
                pageUrl,
                pages = [];
                
            // Issue with GET request strings preventing some enquiries getting through, bail until further notice 
            return $form;
                
            if(this.getUrlVar('iframe_embed') === 'true')
            {
                this.trackPage(true);
                this.save();
            }
            
            pages = this.pages.reverse();
            
            for(var i=0; i<pages.length; i++)
            {
                pageUrl = pages[i] || '';
                
                // Add test to see if this param already exists, if so, just replace the value
                $form.append(input.replace('{1}', i+1).replace('{2}', pageUrl));
            }

            return $form;
        },

        /**
         * Return object with query string variables as object properties
         * @param {String} [strUrl=window.location.search]
         * @param {Stsring} [param="getVariable"] Use if you're only after one specific query string variable (Use FCL.UTIL.getUrlVar if this is the case)
         * @returns {Object or String} What gets returned depends on whether entire collection is returned or just one variable.
         * Returns an empty string if no query string variables are found.
         */
        getUrlVars: function(strUrl, param)
        {
            var queryString='', urlVars='', urlObj={};

            if (strUrl == '' || typeof strUrl == 'undefined')
            {
                queryString = window.location.search;
            }
            else
            {
                queryString = strUrl;
            }

            // if no URL parameters exist, return null
            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;
        },

        /**
         * Get a single query string variable
         * @param {String} key Query string variable name
         * @returns {String} Query string variable if exists or empty string if not
         */
        getUrlVar: function(key)
        {
            return this.getUrlVars('', key);
        }
    };
    FC.PT.init();
})(jQuery)


