﻿// The "fireEventManually" arg is optional, the default is true.
function linkCode(obj,vars,events,code,type,name,fireEventManually) {
    var s = s_gi(s_account);

    if (fireEventManually === undefined) 
        fireEventManually = true;

    if(vars != '')
        s.linkTrackVars=vars;
    if(events!='')
        s.linkTrackEvents=events;
    eval(code);
    
    if (fireEventManually)
        s.tl(obj,type,name);
}


//TODO: move this server side
function initWeather(selectId,locationFormatString,event)
{
    if(s !== undefined)
    {
        $('#'+selectId).unbind('change').bind('change',function(){
            var location = String.format(locationFormatString,$(this).children('option:selected').text());
            var code = location;
            linkCode(this,'eVar29','',code,'o','Location Set');
        });
    }
}

function tescoRegisterClick(linkId) {
    if (s !== undefined) {
        $('#' + linkId).click(function() {
            linkCode(this, 'events', 'event31', 's.events="event31";', 'o', 'Tesco_Register_Link_Click', false);
        }
        );
    }
}

function setOmnitureMealSnackRatingEvent(rating, senderName)
{
    if(s !== undefined)
    {
        var mealName = $("input[name='" + senderName + "']").parent().parent().find(".hiddenOmnitureData").text();
        linkCode($('#'+senderName),'eVar20,products','','s.eVar20=\"'+rating+'\";s.products=\"'+mealName+'\";','o','Meal Rated');
    }
}

function setTescoOmnitureEvent(senderName) 
{
    if (s !== undefined) {
        linkCode(this, 'events', 'event30', 's.events="event30";', 'o', 'Meal sent to Tesco');
    }
}

function makeOmnitureSignUpCall(data) {
    if (s !== undefined) {
        $.ajax({
            type: "POST",
            url: omnitureSignUpTagsUrl,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                var code = msg.Data;
                var variables = 'events,eVar4,eVar8,eVar9,eVar10,eVar11,eVar12,eVar13,eVar14,eVar15,eVar16,eVar17,eVar18,prop9';
                
                if(code.match('event13'))
                    variables += ',event13';
                
                eval(code);
                    
                linkCode(this, variables, s.events, code, 'o', 'Sign Up New');
            }
        });
    }
}

// Removes leading whitespaces
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));	
}

function setOmnitureHierarchyVariables()
{
	var USE_NEW_PAGE_NAMES = false;
    var maxProp = 7;
    var count = 1;
    //Set the first site section
    s.prop1 = 'Special K';
    
    //Initialise the string we use to keep the site sections
    var lastString =  s.prop1;
    

    //Set each site section based on the url
    // E.g. for http://local.specialk.co.uk/about-the-plans/choosing-a-plan.aspx
    // We want  s.prop1 = Special K
    //          s.prop2 = Special K:about-the-plans
    //          s.prop3 = Special K:about-the-plans
    //          s.propn = Special K:about-the-plans
    //          s.prop7 = Special K:about-the-plans
    var uri = parseUri(document.URL);
    var split = uri.directory.split('/');
    for (var i = 0;i<split.length;i++)
    {
        if(split[i] !== undefined && split[i] !== "")
        {
            lastString += ":" + split[i];
            eval("s.prop" + (count) + "='" + lastString + "'");
            count++;
        }
    }

    //Set pagename
    // E.g. for http://local.specialk.co.uk/about-the-plans/choosing-a-plan.aspx
    //  s.pageName = Special K:about-the-plans:choosing-a-plan
	//TODO: This won't work for questions and could break reports..
	if(USE_NEW_PAGE_NAMES)
	{
		if (uri.file != "") {
			s.pageName = lastString + ":" + uri.file.split('.')[0];
		}
		else {
			//Assumes we have no
			s.pageName = "Special K:home";
		}
    }
	
    //fill up the remaining site sections
    count--;
    while(count <= maxProp)
    {
        eval("s.prop" + (count) + "='" + lastString + "'");            
        count++;
    }
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
