var aod_kmart_sessionKey;

function getSessionCookie()
{
    return readCookie("aod_kmart_sessionKey");
}

function setSessionCookie(sessionKey)
{
	// 30 minutes cart session timeout (in fractions of a day)
	var searsSessionTimeoutDays = 30/(60*24);
	
	if (sessionKey != null)
	{
        createCookie("aod_kmart_sessionKey", sessionKey, searsSessionTimeoutDays);
	}
	else
	{
		eraseCookie("aod_kmart_sessionKey");
	}
	
	// try a workaround for cookie-fearing browsers
	aod_kmart_sessionKey = sessionKey;
}


// Cookie handling code from: http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++)
    {
        var c = ca[i];
        while (c.charAt(0) == ' ')
        {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) == 0)
        {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}

function eraseCookie(name)
{
    createCookie(name, "", -1);
}


<!-- BEGIN ALLURENT APPLICATION EVENT HANDLING -->

var aodEvents = new Array(0);
var aodInterval = 0;
var aodQueuePurged = false;
var aodDelayElapsed = false;
 
if (typeof arc != "undefined")
{
    aodSetDelayTimeout();
    arc.addEventListener(arc.Event.APPLICATION, function(event)
    {
        var slot = event.sourceClientId;
        switch (event.data.kind)
        {
          case 'displayShown':
            aodFireTag(event, '', '');
            break;
          case 'addedToCart':
            aodFireTag(event, 'scAdd', '', event.data.category + ";" + aodGetProdSkuId(event));
            // for non-video widgets
            if (document.getElementById("btnCheckout")) {
            	document.getElementById("btnCheckout").style.display = "block";
            }
            break;
          case 'itemSelected':
            aodFireTag(event, 'prodView', '', aodGetProdSkuId(event));
            break;
          case 'interaction':
            switch (event.data.action)
            {
              case 'playVideo':
                 // User has initiated play of video.
                 aodFireTag(event, event.data.action, '');
                 break;
              case 'cuePointJump':
                 // User has jumped to cue point in the video.
                 aodFireTag(event, event.data.action, '');
                 break;
              case 'cuePointView':
                 // User has viewed the hotspotted image for a cue point.
                 aodFireTag(event, event.data.action, '');
                 break;
              case 'productPreview':
                 // User has moused over a hotspot.
                 aodFireTag(event, event.data.action, '');
                 break;
              default:
                 aodFireTag(event, event.data.action, '');
                 break;
            }
            break;
         case 'checkout':
            // Respond to user navigation request for cart/checkout page
            aodFireTag(event, '', '');
            if (getSessionCookie() == null)
            {
				// The session cookie has expired -- this redirects to an empty cart page
                // window.location.href = "http://www.sears.com/shc/s/OrderItemDisplay?trackingID=intcmp|" + referralString + "&storeId=10151&catalogId=10104&orderId=.";
            	self.parent.location.href = "http://www.sears.com/shc/s/OrderItemDisplay?trackingID=intcmp|" + referralString + "&storeId=10151&catalogId=10104&orderId=.";
            	// alert("Missing cookie info");
            	
            	// get session value from page variable, if it exists
            	if (aod_kmart_sessionKey != null) {
            		self.parent.location.href = "http://webservices.sears.com/shcapi/Checkout?trackingID=intcmp|" + referralString + "&store=Kmart&catalogId=10104&appID=allurent_shc&authID=abcdefg$$$$$$$$123456711&sessionKey=" + aod_kmart_sessionKey;
            	} else {
            		// this is probably not going to work well
            		self.parent.location.href = "http://webservices.sears.com/shcapi/Checkout?trackingID=intcmp|" + referralString + "&store=Kmart&catalogId=10104&appID=allurent_shc&authID=abcdefg$$$$$$$$123456711&sessionKey=";
            	}
            }
            else
            {
                // window.location.href = "http://webservices.sears.com/shcapi/Checkout?trackingID=intcmp|" + referralString + "&store=Kmart&catalogId=10104&appID=allurent_shc&authID=abcdefg$$$$$$$$123456711&sessionKey=" + getSessionCookie();
            	self.parent.location.href = "http://webservices.sears.com/shcapi/Checkout?trackingID=intcmp|" + referralString + "&store=Kmart&catalogId=10104&appID=allurent_shc&authID=abcdefg$$$$$$$$123456711&sessionKey=" + getSessionCookie();
            }
            break;
         case 'productInfo':
            aodFireTag(event, 'prodView', '', '');
            // redirect to details page.
            var target = "";
            if(event.data.info && event.data.info == "reviews")
            {
                target = "#reviewsWrap";
            }
            var constructedUrl = "http://www.kmart.com/shc/s/p_10151_10104_" + event.data.productId + target + "?trackingID=intcmp|" + referralString;
            window.open(constructedUrl);
            break;

         case 'navigateToUrl':
            aodFireTag(event, event.data.url, '');
            window.open(event.data.url);
            break;
       }
    });
}


/**
 * Maps handler functions to analytics event kinds.
 * Customise the information being sent to analytics vendor in the function definitions below.
 * 
 * The syntax is:
 * key: [analytics_vendor_function, an anonymous function that returns an array of position arguments to the analytics vendor function]
 */
aod_analytics_eventFunctionMap = { 'displayShown': ["pageTracker._trackPageview", function(event){return aod_ga_tracking+"/displayShown";}],
                               'addedToCart': ["pageTracker._trackPageview", function(event){return aod_ga_tracking+"/addedToCart/"+event.data.productId+"/"+event.data.skuId+"/"+event.data.quantity;}],
                               'itemSelected': ["pageTracker._trackPageview", function(event){ return aod_ga_tracking+"/itemSelected/"+event.data.productId;}],
                               'interaction': ["pageTracker._trackPageview", function(event){return aod_ga_tracking+"/"+event.data.action+"/"+event.data.info;}],
                               'checkout': ["pageTracker._trackPageview", function(event){ return aod_ga_tracking+"/checkout";}],
                               'productInfo': ["pageTracker._trackPageview", function(event){ return aod_ga_tracking+"/productInfo/"+event.data.productId;}],
                               'navigateToUrl': ["pageTracker._trackPageview", function(event){ return aod_ga_tracking+"/navigateToUrl/"+event.data.url;}]
                               }


// Testing helper method to set a timeout that must elapse before events
// will be purged/fired to Google Analytics
function aodSetDelayTimeout()
{
    if (document.location.href.indexOf("aoddelay=")>0)
    {
        var aodSplit = document.location.href.split("aoddelay=");
        var aodtimeout = aodSplit[1];
        aodDebug("Setting queue delay: " + aodtimeout);
        setTimeout(aodClearDelay,aodtimeout);
    }
    else
    {
        aodClearDelay();
    }
}
 
function aodClearDelay()
{
    aodDebug("Clearing event delay...");
    aodDelayElapsed = true;
}
 
// Constructs and fires a Google Analytics tag
function aodFireTag(theEvent,thisEvents,thisEVar,thisProducts)
{
    if (pageTracker == undefined || ! aodDelayElapsed )  // Google Analytics library not yet loaded; queue the event
    {
        aodDebug("Analytics library not yet loaded.  Queuing event: " + theEvent.data.kind);

        // stick the event in the queue
        aodEvents.push(new AoDEvent(theEvent,thisEvents,thisEVar,thisProducts));

        // if interval is not active, start it now so the queued events
        // are fired as soon as analytics library becomes defined
        if (aodInterval == 0 )
        {
            aodInterval = setInterval(aodFireQueuedEvents,250);
        }
    }
    else
    {
        aodFireAndPurgeEvent(theEvent,thisEvents,thisEVar,thisProducts);
    }
}
 
function aodFireQueuedEvents()
{
       if (pageTracker != undefined && aodDelayElapsed )
       {
           clearInterval(aodInterval);
           for (var i=0; i< aodEvents.length; i++)
           {
               if (aodEvents[i].fired == "false")
               {
               aodDebug("Firing from queue: " + aodEvents[i].event.data.kind);
               aodEvents[i].fired = "true";
                       aodFireEvent(aodEvents[i].event, aodEvents[i].eventNames, aodEvents[i].eVar, aodEvents[i].productInfo);
               }
           }
           aodQueuePurged = true;
       }
}
 
function aodFireAndPurgeEvent(theEvent,thisEvents,thisEVar,thisProducts)
{
    if (! aodQueuePurged ) { aodFireQueuedEvents() }
    aodFireEvent(theEvent,thisEvents,thisEVar,thisProducts);
}

// Look up the analytics vendor function in eventFunctionMap and call it to record analytics.
function aodFireEvent(theEvent,thisEvents,thisEVar,thisProducts)
{
    var handlerTuple = aod_analytics_eventFunctionMap[theEvent.data.kind];
    if (handlerTuple != undefined){
        var handler = eval(handlerTuple[0]);
        var args = handlerTuple[1](theEvent, thisEVar);
        handler(args);
    }
}
 
// Helper function for debugging
function aodDebug(msg)
{
    if (document.location.href.indexOf("aodtest=true") > 0 )
    {
        alert(msg);
    }
}
 
// Helper function to build products string for different events
function aodGetProdSkuId(event)
{
    var uri = new String(event.data.product);
    return uri.split("/").pop();
}
 
// Object representation of AoD events
function AoDEvent(theEvent,thisEvents,thisEVar,thisProducts)
{
    this.event = theEvent;
    this.eventNames = thisEvents;
    this.eVar = thisEVar;
    this.productInfo = thisProducts;
    this.fired = "false";
}