// catalystPath is set prior to the include of this file
// It is of the form "Site:Home:Folder:Folder:Page"
var PATH_SEP = ":";
var HIER_SEP = "|";
var SEARCH_PAGE = PATH_SEP + 'search';
var FORM_NAME = 'FormBuilder';  // Standard form used in Tridion sites

// This list contains the name of the form and a description
var OTHER_FORMS = new Array(new NameValue('frmRegisterDetails', 'OOS'));
OTHER_FORMS.push(new NameValue('addUser', 'Ideas'));
OTHER_FORMS.push(new NameValue('frmRegisterOTB', 'OTB'));
OTHER_FORMS.push(new NameValue('frmFreeCallback', 'Click'));

if (catalystPath != "")
{
    // Add default page if not explicitly named
    if (catalystPath.substring(catalystPath.length - 1) == ':')
        catalystPath += "default";
	
    if (s_account.toLowerCase() == 'sdldev')
        s.trackingServer = "sdlinternational.122.2o7.net";
    else if (location.protocol == 'https:')
    {
        // Add the secure prefix to the tracking server
        s.trackingServer = 's' + s.trackingServer;
    }

    scSetHierarchy();

    // Check for a feedback form
    if (document.forms[FORM_NAME] != null)
    {
        s.events = "event1";        // Start of a lead
        if (document.forms[FORM_NAME].elements['WebActivityType'] != null)
            s.eVar1 = document.forms[FORM_NAME].WebActivityType.value;
        else
            s.eVar1 = 'Unknown lead type';

        // Set internal campaign ID
        if (document.forms[FORM_NAME].elements['CampaignID'] != null)
        {
            var tempCampaign = document.forms[FORM_NAME].CampaignID.value;

            // Trim pipe characters from start and end of campaign ID
            var pipeReg = new RegExp(/\|*(.*[^\|])\|*/);
            if (tempCampaign.match(pipeReg))
                tempCampaign = tempCampaign.match(pipeReg)[1];
            s.eVar4 = tempCampaign;
        }
    }

    // Check for other registration forms
    var formItem;
    for (formNo = 0; formNo < OTHER_FORMS.length; formNo++)
    {
        formItem = OTHER_FORMS[formNo];
        // Append this form to the list (if not already there)
        s.formList = s.apl(s.formList, formItem.Name, ',', 1);
        if (document.forms[formItem.Name] != null)
        {
            s.events = "event1";
            s.eVar1 = formItem.Value + " Registration";
        }
    }

    if (s.pageName.length >= SEARCH_PAGE.length && s.pageName.toLowerCase().substring(s.pageName.length - SEARCH_PAGE.length) == SEARCH_PAGE)
    {
        // Track search request
        s.events = "event5";
        s.prop5 = s.getQueryParam('q').toLowerCase();
        s.eVar5 = s.prop5;
    }

    // Set external campaign ID
    var extCampaign = s.getValOnce(s.getQueryParam('campaignid'), 'gvo_cmpid', 0);
    if (extCampaign)
    {
        // Dont duplicate this ID in eVar4 (remove it from start or end)
        s.eVar4 = s.eVar4.replace(new RegExp("^" + extCampaign + "\\|"), "");
        s.eVar4 = s.eVar4.replace(new RegExp("\\|" + extCampaign + "$"), "");

        s.campaign = extCampaign;
    }

    s.t()
}

/*
s.prop5="" // Search terms
s.prop6=""
s.prop7="" // Download file
s.prop8="" // download page
s.prop9=""
s.prop10="" // Form abandonment
s.prop11="" // Search origination

s.pageType="" // Set only for error pages
*/

function scSetHierarchy()
{
    var scVals = catalystPath.split(PATH_SEP);

    // Remove a file extension from the page name
    var dotPosition = scVals[scVals.length-1].lastIndexOf('.');
    if (dotPosition != -1 && dotPosition >= scVals[scVals.length-1].length -5)
        scVals[scVals.length-1] = scVals[scVals.length-1].substring(0, dotPosition);

    /* You may give each page an identifying name, server, and channel on the next lines. */

    // Remove site and home from page name
    if (scVals.length > 2)
    {
        // Remove the Home element of the array
        scVals.splice(1, 1);
        s.pageName = scVals.join(PATH_SEP);
    }
    else
        s.pageName = catalystPath;

    // Set the sections (last part of path is page so don't inlcude that)
    if (scVals.length > 2)
        s.channel = scVals[1];
    if (scVals.length > 3)
        s.prop1 = scVals[2];
    if (scVals.length > 4)
        s.prop2 = scVals[3];
    if (scVals.length > 5)
        s.prop3 = scVals[4];
    if (scVals.length > 6)
        s.prop4 = scVals[5];

    // Set the hierarchy (last value is the page name so we don't need that, second val is Home)
    s.hier1 = scVals.slice(0, scVals.length - 1).join(HIER_SEP);

    if (scVals[scVals.length - 1] == '404')
    {
        s.pageName = '';
        s.pageType = 'errorPage';
    }
}

function scTrackDownload(linkObj)
{
    scTrackFileLink(linkObj, linkObj.href);
}

function scTrackFileLink(fileName, linkObj)
{
    s.linkTrackVars = 'eVar7,prop7,prop8,events';  // Filename, 'events', Download page, Filename
    s.linkTrackEvents='event4';                            // File downloads
    s.events='event4';
    s.eVar7=fileName;
    s.prop8=s.pageName;
    s.prop7=s.eVar7;
    s.tl(linkObj,'d',fileName);
}

function scSubmitForm()
{
    scFormSuccess(FORM_NAME);
}

function scFormSuccess(formName)
{
    if (catalystPath != "")
    {
        s.sendFormEvent('s', s.pageName, formName);

        s.pageName += "Submit";
        s.events = "event2"        // End of a lead
        
        if (document.forms[formName].elements['WebActivityType'] != null)
            s.eVar1 = document.forms[formName].WebActivityType.value;
        else
            s.eVar1 = 'Unknown lead type';

        // Check for other registration forms
        var formItem;
        for (formNo = 0; formNo < OTHER_FORMS.length; formNo++)
        {
            formItem = OTHER_FORMS[formNo];
            if (formName == formItem.Name)
                s.eVar1 = formItem.Value + ' Registration';
        }
        
        s.t();
    }
}

function scErrorForm()
{
    if (catalystPath != "")
    {

        // Form had validation errors, report the fields causing the problem
        var divCount = 1;
        var divElem = document.getElementById('HighLightDiv' + divCount);
        var tempElem;
        var scVals = catalystPath.split(PATH_SEP);
        var errorMessage;

        // Need to discover divs with class set to ErrorOn
        while (divElem != null)
        {
            if (divElem.className == 'ErrorOn')
            {
                errorMessage = '';

                // Find if the div contains a filled text box (i.e. value is invalid)
                tempElem = findChildElement(divElem, 'INPUT', 'text');
                if (tempElem != null && tempElem.value.length > 0)
                    errorMessage = 'Invalid: ';
                else
                    errorMessage = 'Not set: ';


                // Get their label if they have one, otherwise previous element should be a Heading
                tempElem = findChildElement(divElem, 'LABEL', '');
                if (tempElem != null)
                    errorMessage += tempElem.innerText;
                else
                {
                    if (divElem.previousSibling.tagName == 'DIV' && divElem.previousSibling.className.search('HeadingText') == 0)
                    {
                        errorMessage += divElem.previousSibling.innerText;
                    }
                }

                scFormError(FORM_NAME, errorMessage);
            }

            divCount++;
            divElem = document.getElementById('HighLightDiv' + divCount);
        }
    }
}

function scFormError(formName, errorMessage)
{
    s.sendFormEvent('e', s.pageName, formName, errorMessage);
}

function findChildElement(parentElement, elementType, inputType)
{
    var returnElem = parentElement.firstChild;
    while (returnElem.tagName != 'elementType' && !(inputType == '' || returnElem.type == inputType))
    {
        if (returnElem == parentElement.lastChild)
            return null;
        returnElem = returnElem.nextSibling;
    }
    
    return returnElem;
}


function NameValue(itemName, itemValue)
{
    this.Name = itemName;
    this.Value = itemValue;

    return this;
}

// Shopping cart functions for OOS
function scProduct(productName, quantity, cost, currency)
{
    this.ProductName = productName;
    this.Quantity = quantity;
    this.Cost = cost;

    return this;
}
scProduct.prototype.toString = function() {return ';' + this.ProductName + ';' + this.Quantity + ';' + this.Cost;}


function scAddToBasket(productName)
{
    s.events = 'scAdd';
    s.products = ';' + productName;
    s.t();
}

function scStartCheckout(productArray, currency)
{
    s.events = 'scCheckout';
    s.products = scProductString(productArray);
    if (typeof currency != 'undefined')
        s.currencyCode = currency;

    s.t();
}

function scPurchase(productArray, purchaseID, currency)
{
    s.events = 'purchase';
    s.products = scProductString(productArray);
    s.purchaseID = purchaseID;
    if (typeof currency != 'undefined')
        s.currencyCode = currency;

    s.t();
}

function scProductString(productArray)
{
    return productArray.join(',');
}

