﻿/*  
Summary: Provides numerous helper functions to simplify the construction and issuing of WebTrends tracking
calls. Handles JSON parsing, parameter construction and event handler hookup.
*/

// Pull JSON object out of the element's attribute
function RetrieveJson(item, attribute) {

    // Get the string from the element attribute
    var jsonString = $(item).attr(attribute);
    //alert(jsonString);
    if (jsonString != undefined) {

        // Unwrap the CDATA and parse as JSON
        jsonString = jsonString.replace("<![CDATA[", "").replace("]]>", ""); 
        return jQuery.parseJSON(jsonString);        
    }
}

// Return an element if it has a type attribute of "hidden", otherwise return nothing
function IsHiddenField(field) {

    if(!($(field).attr("type") == "hidden")) {
        field = null;
    }
    return field;
}

function GetLinkTracker(link, attribute) {
    if (attribute == undefined)
        attribute = "data-tracker";

    return RetrieveJson(link, attribute);
}

function MakeTrackingCall(data) {
    if (data != null) {
        //alert("Making call using:   " + GetTrackingArgs(data));
        dcsMultiTrack.apply(null, GetTrackingArgs(data));
    }
}

// Builds up multitrack parameters for the Add/Remove
// links in Offers, based on whether we're adding or removing.
function TagAddOfferClick(isAdding, offerId) {
    var str = "a[data-offerid='" + offerId + "']";
    var addStr;
    if (isAdding == "a")
    {
        addStr = "Added";
    }
    else
    { 
        addStr = "Removed";
    }

    var data = GetLinkTracker(str);
    if (data != null) {
        data.ProductAddRemove = isAdding;
        data.Uri = data.Uri + "_" + addStr;
        data.TagTitle = data.TagTitle + " " + addStr;
        data.ExtensionParameters[1].Value = data.ExtensionParameters[1].Value + " " + addStr;
        // change the name of the data.ExtensionParameters[2].Key if it's removing
        if(isAdding != "a") {
            $(data.ExtensionParameters).each(function (index, ep) {
                if (ep.Key == "DCSext.offerprodadd") {
                    ep.Value = "";
                }
                else if (ep.Key == "DCSext.offerprodrem") {
                    ep.Value = "1";
                }
            });
        }
        MakeTrackingCall(data);
    }
}

// Handles tracking for the provided link
function TagLinkClick(str) {    
    var data = GetLinkTracker(str);
    MakeTrackingCall(data);    
}

// Handles tracking for input fields within the provided form
// Looks for the tracker data within the hidden field, using the
// supplied attribute
function AttachFormEvents(formName, attrName) {
    
    // Take any form field and tag any change events
    $(formName).find('input[type=text],textarea,select,input[type=radio],input[type=checkbox],input[type=password]').change(function () {       
        HandleFormFieldEvent($(this), attrName);
    });

    // Attach to the form submit too
    //$(formName).parents('form:first').submit(function () {
    //HandleFormFieldEvent($(formName).find('input[type=submit]'), attrName);
    //}
    // no, attach it to the click event instead
    $(formName).find('input[type=submit], a').mousedown(function () {         
        HandleFormFieldEvent($(this), attrName);
    });
}

// Searches for the correct hidden tracker data field and attribute
// and attempts to extract JSON tracker data
function HandleFormFieldEvent(field, attrName) {
    var hidden = null;

    // Exceptions to the rule 
    var sharedId = $(field).attr("data-sharedTrackerid");
    if (sharedId != undefined) {

        // If it's denoted as having a shared tracker, look up the id of the tracker
        hidden = $(sharedId);       

    } else if ($(field).parent().hasClass("radioList") || $(field).parent().hasClass("checkboxList")) {

        // If a radiolist item is hit, a common hidden field is outside the parent span        
        hidden = IsHiddenField($(field).parent().next());
    } else {

        // All other relevant fields have a hidden field immediately after the form field
        hidden = IsHiddenField($(field).next());        
    }
    if (hidden != null) {

        if (attrName == undefined)
            data = RetrieveJson(hidden, "data-tracker");
        else
            data = RetrieveJson(hidden, attrName);

        // Call the WebTrends ap alert(data);
        MakeTrackingCall(data);
    }
}

// Add arguments to arg list only if they're populated in the returned JSON
function GetTrackingArgs(data) {

    var args = ['DCS.dcsuri',data.Uri,'WT.ti',data.TagTitle,'WT.dl',data.EventType];
    if (data.FormScenarioName != null)
    {
        args.push('WT.si_n');
        args.push(data.FormScenarioName);
    }
    if (data.FormScenarioNumber != null)
    {
        args.push('WT.si_x');
        args.push(data.FormScenarioNumber);
    }

    // Add product tracking details if we have any
    if (data.ProductSKU != null)
    {
        args.push('WT.pn_sku');
        args.push(data.ProductSKU);
    }
    if (data.ProductAddRemove != null)
    {
        args.push('WT.tx_e');
        args.push(data.ProductAddRemove);
    }
    if (data.ProductQuantity != null)
    {
        args.push('WT.tx_u');
        args.push(data.ProductQuantity);
    }

    // Add any params in the extensions array
    for(var i=0; i < data.ExtensionParameters.length; i++)
    {
        args.push(data.ExtensionParameters[i].Key);
        args.push(data.ExtensionParameters[i].Value)
    }
    return args;
}

// Specific tracking call for an increment/decrement event
// within the Butcher Portion Calculator.
function TrackPortionChange(adults, children)
{
    dcsMultiTrack("DCS.dcsuri","/Market-Street/Butcher/PortionCalculatorSize_Button",
        "WT.ti","Market Street - Portion Calculator Size - Next Button",
        "DCSext.portioncalc","Adult - " + adults + ";Children - " + children,
        "DCSext.portioncalcamt", "1;1",
        "WT.dl", "101");
}

function TrackPlanRouteStoreFinderButton() {
    dcsMultiTrack("DCS.dcsuri", "/Store-finder/PlanRoute_Button",
        "WT.ti", "Store Finder – Plan Route Button", "DCSext.planroutebtn",
        "Plan Route Button Selected", "DCSext.planroutebtnslct", "1",
            "DCSext.commondim", "Plan Route Button", "WT.dl", "101");
}

function TrackVideoCompletion(url) {
    dcsMultiTrack("DCS.dcsuri", url + "/Video_Completion",
        "WT.ti", "Video Completion - " + url, "DCSext.videoview",
        url, "DCSext.vidview", "1", "WT.dl", "101");
}

function EnableExternalLinkTracking() {
//    $('a[href^="http://"]').not($('a[href*=www.morrisons.co.uk]')).click(function (e) {

//        e.preventDefault();
//        var url = $(this).attr("href");

//        var result = confirm("You are about to leave Morrisons, and are headed towards: \"" + (url) + "\".  Are you sure you want to proceed?");
//        if (result == true) {
//            document.location = url;
//        }

//    });
}
