/*  Notes:
 *  pageViewHandler calls are embedded in each of the aspx.cs files. they get fired once for each page load.
 *  interaction handlers are attached to the onclick events of the dom elements. find them in the assignments of the 'onclick=' snippets
 *  to find all omniture calls, search for 'omn.'. 'omn' is out global ref to this namespace.
 */

/*
 *  Create Namespace
 */
ninemsn.mylocal.omniture = new OmnitureWrapper();
var omn = ninemsn.mylocal.omniture;

/*
 *  Public constants
 */
ninemsn.mylocal.omniture.SEARCHBUSINESSNAME = 1;
ninemsn.mylocal.omniture.SEARCHBUSINESSTYPE = 0;
ninemsn.mylocal.omniture.SEARCHLOCATION     = 2;

ninemsn.mylocal.omniture.EVENTSEARCH = "0";
ninemsn.mylocal.omniture.EVENTBROWSE = "1";
  
ninemsn.mylocal.omniture.INTERACTIONHEADLINE        = 0;
ninemsn.mylocal.omniture.INTERACTIONMOREINFO        = 1;
ninemsn.mylocal.omniture.INTERACTIONGETDIRECTIONS   = 2;
ninemsn.mylocal.omniture.INTERACTIONSENDTOMOBILE    = 3;
ninemsn.mylocal.omniture.INTERACTIONSCRATCHPAD      = 4;
ninemsn.mylocal.omniture.INTERACTIONSENDTOFRIEND    = 5;
ninemsn.mylocal.omniture.INTERACTIONEMAIL           = 6;
ninemsn.mylocal.omniture.INTERACTIONWEBSITE         = 7;
ninemsn.mylocal.omniture.INTERACTIONSENDTOMOBILESUCCESS = 8;

ninemsn.mylocal.omniture.SORTRELEVANCE = 0;
ninemsn.mylocal.omniture.SORTNAME = 1;
ninemsn.mylocal.omniture.SORTDISTANCE = 2;

/*
 *  Values relate to cookies array
 */
ninemsn.mylocal.omniture.COOKIEINDEXEVENT       = 0;            
ninemsn.mylocal.omniture.COOKIEINDEXPAGINATE    = 1;
ninemsn.mylocal.omniture.COOKIEINDEXREFINE      = 2;

/*
 *  OmnitureWrapper Object
 *  
 */
function OmnitureWrapper()
{
    /*
     *  Class instance reference
     *  Creates a reference to the OmnitureWrapper instance ('this')
     *  that will be accessible in closures as 'me'
     */
    var me = this;
    
    /*
     *  Configs
     */
    var siteID          = "mylocal";
    var source          = "mylocal";
    var cookies = [
        { name : "eventCookie",     id : "ML_Event"     },
        { name : "paginatedCookie", id : "ML_Paginated" },
        { name : "refinedCookie",   id : "ML_Refined"   }
    ];    
    
    /*
     *  ClearCookies
     *  description:
     *  clear all tracking cookies
     */
    function clearCookies()
    {
        try
        {
            /*
             *  Loop through cookie list and remove 
             */
            for (var pos in cookies)
            {
                var cookie = cookies[pos].id;
                utl.deleteCookie(cookie);
            }
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.clearCookies : {0}".format(ex.description));
        }
    }

    /*
     *  initialise
     *  description:
     *  clear any tracking cookies
     */
    this.initialise = function(eventType)
    {
        try
        {
            /*
             *  Clear all tracking cookies
             */
            clearCookies();
            
            /*
             *  If not event type passed in, do not create a cookie
             */
            if (utl.IsNullOrEmpty(eventType))
                eventType = ninemsn.mylocal.omniture.EVENTSEARCH;
                
            /*
             *  Create cookies
             */
            utl.writeCookie(cookies[ninemsn.mylocal.omniture.COOKIEINDEXEVENT].id, eventType);
            
            var deb = [];
            deb.push("** Initialise **");
            deb.push("cookie: " + cookies[ninemsn.mylocal.omniture.COOKIEINDEXEVENT].name);
            deb.push("value: " + eventType);
            utl.debout(deb.join("</br>"));
        }   
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.initialise : {0}".format(ex.description));
        }
    };       
   
    /*
     *  actionHandler 
     *  description:
     *  xxx
     */
    this.customActionHandler = function(cookieIndex, value)
    {
        try
        {
            /*
             *  default to "true"
             */
            if (utl.IsNullOrEmpty(value))
                value = "true";
                
            /*
             *  write cookie
             */    
            utl.writeCookie(cookies[cookieIndex].id, value);
            
            /*
             *  Display debug info
             */
            var deb = [];
            deb.push("** Custom Action Handler **");
            deb.push("cookie: " + cookies[cookieIndex].name);
            deb.push("value: " + value);
            utl.debout(deb.join("</br>"));
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.customActionHandler : {0}".format(ex.description));
        }
    }
           
    /*
     *  InteractionHandler 
     *  description:
     *  track individual interaction
     */
    this.interactionHandler = function(interactionType, recordID)
    {    
        try
        {
            var oType = me.getInterationType(interactionType);
            var oListing = me.getListing(recordID);
            var oSource = source;
            
            /*
             *  Display debug info
             */
            var deb = [];
            deb.push("** Interaction Handler **");
            deb.push("type id: " + interactionType);
            deb.push("type name: " + me.getInterationType(interactionType));
            deb.push("recordID: " + recordID);
            deb.push("listing: " + oListing);
            deb.push("source: " + oSource);
            utl.debout(deb.join("</br>"));
            
            /*
             *  Invoke omniture interaction tracking
             */
            omniture_interaction(oType,[oListing],oSource);
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.InteractionHandler : {0}".format(ex.description));
        }
    }
    
    /*
     *  detailsViewHandler
     *  description:
     *      Fires when a details page is viewed.
     */
    this.detailsViewHandler = function(recordID)
    {
        try
        {
            var oListing = me.getListing(recordID);
            
            /*
             *  Display debug info
             */
            var deb = [];
            deb.push("** Details View Handler **");
            deb.push("listing: " + oListing);
            utl.debout(deb.join("</br>"));
            
            /*
             *  Invoke omniture interaction tracking
             */
            omniture_detailview([oListing]);
        }
        catch (ex)
        {
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.detailsViewHandler : {0}".format(ex.descriptionn));
        }
    };
   
    this.pageViewHandler = function(pageName, sectionName, cookieID)
    {
        try
        {
            /*
             *  If needed get the page name from a cookie
             */
            var oSection = sectionName;                        
            var oPageName = pageName;
            var oSource = source;
            
            if (utl.IsNullOrEmpty(oSection) && !utl.IsNullOrEmpty(cookieID))
            {
                oSection = utl.readCookie(cookies[cookieID].id);
                oSection = oSection == ninemsn.mylocal.omniture.EVENTBROWSE ? "Browse" : "Search";  
            }                
            
            /*
             *  Display debug info
             */
            var deb = [];
            deb.push("** Page View Handler **");
            deb.push("Section: " + oSection);
            deb.push("Page: " + oPageName);
            deb.push("source: " + oSource);
            utl.debout(deb.join("</br>"));
            
            omniture_pageview(oSection, oPageName, oSource);
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.pageViewHandler : {0}".format(ex.description));
        }
    }
    
    /*
     *  SearchHandler 
     *  @param {integer} type : type of search that was performed
     *  @param {array} listings : business listings information returned by the query
     *  description:
     *  track a search event, occurs when a new search is performed.
     */
    this.searchHandler = function(eventType)
    {    
        try
        {
            /*
             *  Retrieve the type of event to track
             */
            if (utl.IsNullOrEmpty(eventType))
            {
                eventType = utl.readCookie(cookies[ninemsn.mylocal.omniture.COOKIEINDEXEVENT].id);
                if (utl.IsNullOrEmpty(eventType))
                    eventType = ninemsn.mylocal.omniture.EVENTSEARCH;
            }
            
            /*
             *  Determine Omni Variables
             */        
            var oType = !utl.IsNullOrEmpty(window.g_type) ? me.getSearchType(window.g_type) : me.getSearchType();
            var oTerm = !utl.IsNullOrEmpty(window.g_what) ? window.g_what : "";
            var oLocation = !utl.IsNullOrEmpty(window.g_where) ? window.g_where : "";
            
            /*
             *  Get state param from the QS
             */
            var oState = !utl.IsNullOrEmpty(window.g_state) ? window.g_state : "";
            var oPostcode = !utl.IsNullOrEmpty(window.g_postcode) ? window.g_postcode : "";
            var oMatchedCat = !utl.IsNullOrEmpty(window.g_categoryName) ? window.g_categoryName : "";
            var oCatID = !utl.IsNullOrEmpty(window.g_categoryID) ? window.g_categoryID : "";
            var oNumOfResults = !utl.IsNullOrEmpty(window.g_totalRecords) ? window.g_totalRecords : 0;
            
            var oShowSurrounding = me.getValueForCheckbox(window.g_surrounding);
            var oServicingArea = me.getValueForCheckbox(window.g_servicing);
            
            var oSource = source;
            var oListing = !utl.IsNullOrEmpty(window.g_listings) ? window.g_listings : [];            
            var oPaginated = utl.readCookie(cookies[ninemsn.mylocal.omniture.COOKIEINDEXPAGINATE].id);
            var oRefined = utl.readCookie(cookies[ninemsn.mylocal.omniture.COOKIEINDEXREFINE].id);
            
            var oSortType = !utl.IsNullOrEmpty(window.g_sortType) ? window.g_sortType : "";
                        
            /* 
             *  Debug output
             */
            var deb = [];
            deb.push("** Search Handler **");
            deb.push("event: " + eventType);
            deb.push("type: " + oType);
            deb.push("term: " + oTerm);
            deb.push("location: " + oLocation);
            deb.push("state: " + oState);
            deb.push("postcode: " + oPostcode);
            deb.push("catname: " + oMatchedCat);
            deb.push("catid: " + oCatID);               
            deb.push("count: " + oNumOfResults);               
            deb.push("surrounding: " + oShowSurrounding);               
            deb.push("servicing: " + oServicingArea);
            deb.push("source: " + oSource);
            deb.push("listings: " + oListing);
            deb.push("refined: " + oRefined);
            deb.push("paginated: " + oPaginated);
            deb.push("sort: " + oSortType);
            utl.debout(deb.join("</br>"));
                    
            switch (eventType)
            {
                case ninemsn.mylocal.omniture.EVENTSEARCH :
                    omniture_search(oType,oTerm,oLocation,oPostcode,oMatchedCat,oCatID,oNumOfResults,oShowSurrounding,oServicingArea,oSource,oListing,oPaginated,oRefined,oSortType);                                    
                                    
                    break;                   
                    
                case ninemsn.mylocal.omniture.EVENTBROWSE :
                    omniture_browse(oState,oLocation,oPostcode,oMatchedCat,oCatID,oNumOfResults,oShowSurrounding,oServicingArea,oSource,oListing,oPaginated,oRefined,oSortType);                                    
                    
                    break;
                    
                default :
                    /* report error */
                    utl.debout("** EXCEPTION ** SearchHandler - eventType Invalid : " + eventType);
                    
                    break;
            }                       
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.SearchHandler : {0}".format(ex.description));
        }
    };
   
    /*
     *  GetSearchType
     *  @param {string} searchType : code representing a search type
     *  description:
     *  returns the string representation of a search type code
     */
    this.getSearchType = function(searchType)
    {
        switch (searchType)
        {
            case ninemsn.mylocal.omniture.SEARCHBUSINESSNAME:
                return siteID + ":business name";
                
            case ninemsn.mylocal.omniture.SEARCHBUSINESSTYPE:
                return siteID + ":business type";                
                
            case ninemsn.mylocal.omniture.SEARCHLOCATION:
                return siteID + ":location";
            
            default:
                return siteID + ":business type";
        }
    };
    
    /*
     *  GetInterationType
     *  @param {string} interactionType : code representing a interaction type
     *  description:
     *  returns the string representation of a interaction type code
     */
    this.getInterationType = function(interactionType)
    {
        switch (interactionType)
        {
            case ninemsn.mylocal.omniture.INTERACTIONHEADLINE :
                return "Headline link";
                
            case ninemsn.mylocal.omniture.INTERACTIONMOREINFO :
                return "More info at Yellow";
                
            case ninemsn.mylocal.omniture.INTERACTIONGETDIRECTIONS :
                return "Get Directions";
                
            case ninemsn.mylocal.omniture.INTERACTIONSENDTOMOBILE :
                return "Send to Mobile";
                
            case ninemsn.mylocal.omniture.INTERACTIONSCRATCHPAD :
                return "Add to Scratch Pad";
            
            case ninemsn.mylocal.omniture.INTERACTIONSENDTOFRIEND :
                return "Send to a Friend";
            
            case ninemsn.mylocal.omniture.INTERACTIONEMAIL :
                return "Email";
            
            case ninemsn.mylocal.omniture.INTERACTIONWEBSITE :
                return "Website";
            
            case ninemsn.mylocal.omniture.INTERACTIONSENDTOMOBILESUCCESS :
                return "Mobile Success";
            
            default:
                return "";
        }
    };
    
    /*
     *  GetListing
     *  @param {string} recordID : record id of listing to return
     *  description:
     *  enumerate through listings collection, return the listing information related to the recordID paramter
     */
    this.getListing = function(recordID)
    {
        var listing = {};
        
        try
        {
            if (!window.g_listings)
                return listing;
                
            for (pos in window.g_listings)
            {
                if (window.g_listings[pos].recordID == recordID)
                {
                    listing = window.g_listings[pos];
                    break;                  
                }
            }
            
        }
        catch (ex)
        {
            /*
             *  Write out excetions to debug panel
             */
            utl.debout("** EXCEPTION ** ninemsn.mylocal.omniture.getListing : {0}".format(ex.description));
        }
    
        return listing;
    }
    
    /*
     *  getValueForCheckbox
     *  @param {string} stringBool : string representation of a boolean value
     *  description:
     *  converts a string representation of a boolean value into "Selected" or "Not Selected"
     *  "true" = "Selected"
     *  "false" = "Not Selected"
     */
    this.getValueForCheckbox = function(stringBool)
    {
        if (utl.IsNullOrEmpty(stringBool) || stringBool == "False")
            return false;
        else    
            return true;
    };
}
