/* MS Store site-wide OT-related codes.
 *
 * Table of contents:
 * 1. OTGlobalCode.js (include json cookie plugin, and ptomodule codes.  Mostly minified)
 * 2. jQuery Json cookie related plugins.  (one of the cookies is not minified b/c it fails when it is)
 * 3. drso library  (minified)
 * 4. custom personilization scripts.
 *
 * With each update, create a new file with an updated version number.
 *
 * Version History:
 * 1.0.1 (aboyer 2010/11/11) -- Removed cookies that are created via jQuery.cookie plugin. Namely, op_os, op_browserHigh, RefURL, and op_browser. These are no longer needed.
 *
*/

/*
 *
 * SECTION 1: OTGlobalCode.js (include json cookie plugin, browser detection and cookie setting, and ptomodule codes.  Mostly minified)
 *
 *
*/

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/*** ptomodule object ***/
var ptomodule={A:{},C:{},D:document,L:document.location,M:[],Q:{},T:new Date(),U:'',V:'2.7',Enabled:true,ST:"script",SA:
{"type":"text/javascript"},I:function(){var s=this.L.search;var c=this.D.cookie;if(s.length>3){for(var a=s.substring(1)
.split("&"),i=0,l=a.length;i<l;i++){var p=a[i].indexOf("=");if(p>0)this.Q[a[i].substring(0,p)]=unescape(a[i].substring(
p+1));}}if(c.length>3){for(var a=c.split(";"),i=0,b=a.length;i<b;i++){var v=a[i].split("=");while(v[0].substring(0,
1)==" ")v[0]=v[0].substring(1,v[0].length);if(v.length==2)this.C[v[0]]=unescape(v[1]);}}},B:function(){var n;this.A={
};var _o=this;this.A.D_ts=Math.round(_o.T.getTime()/1000);this.A.D_tzo=_o.T.getTimezoneOffset();this.A.D_loc=_o.L.protocol+
"//"+_o.L.hostname+_o.L.pathname;this.A.D_ckl=_o.D.cookie.length;this.A.D_ref=_o.D.referrer;if(typeof optrial=="object")
for(n in optrial)this.A[n]=optrial[n];for(n in this.Q)this.A[n]=this.Q[n];for(n in this.C)if(n.substring(0,2)=="op")this.A[n]=
this.C[n];},S:function(){var q='';for(var n in this.A)if(this.A[n]!=null && this.A[n]!="")q+=(q.length>0?"&":(this.U.indexOf(
"?")>0?"&":"?"))+n+"="+escape(this.A[n]);return this.U+q;},SC:function(n,v,e,d){var de=new Date();de.setTime(
de.getTime()+e * 1000);this.D.cookie=n+"="+escape(v)+((e==null)?"":("; expires="+de.toGMTString()))+"; path=/"+((d==
null)?"":(";domain="+d));},SLD:function(){var sld=this.D.domain;var dp=sld.split(".");var l=dp.length;if(l<2)sld=null;
else if(!isNaN(dp[l-1])&&!isNaN(dp[l-2]))sld=null;else sld="."+dp[l-2]+"."+dp[l-1];return sld;},R:function(r,c,d,
e){if(this.Enabled){var b=true;if(r<1000){b=(Math.floor(Math.random()*1000)<r);if(c!=null){if(this.C[c]!=null)b=(this.C[c]!=
"mvt-no");else this.SC(c,b?"mvt-yes":"mvt-no",e,d);}}if(b){var t='<'+this.ST+' src="'+this.S()+'"';for(n in this.SA)
t+=(" "+n+'="'+this.SA[n]+'"');t+='><\/'+this.ST+'>';this.D.write(t);}}},addModule:function(s,f){this.M[s]=f;
},displayModule:function(s){if(typeof this.M[s]=="function")this.M[s]();},hasModules:function(){return count(this.M)>0;
}};ptomodule.I();


/*
 *
 * SECTION 2: jQuery Json cookie related plugins.
 *
 *
*/

//used for jquery extjasoncookie plugin.  http://projects.exvoto.org/jquery-extjsoncookie/
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);

//jquery extended json cookie plugin.  plugin home page: http://projects.exvoto.org/jquery-extjsoncookie/  There are several edits by Ari Koinuma.  see the regular version: //dri1.img.digitalrivercontent.net/Storefront/Site/msstore/cm/multimedia/personalization/jquery.extjasoncookie-0.3.js  This portion is non-minified because minifying caused errors.
/* plugin home page: http://projects.exvoto.org/jquery-extjsoncookie/
 * There were some edits!  Look for "AK" in comments
 *
 * jQuery Extended JSon Cookie Plugin
 * relese 2010-01-11
 *
 * It is licensed as free software under the terms of the GNU General Public License (GPL)
 * http://www.gnu.org/licenses/gpl.html
 *
 * This plugin is based on Jquery Cookie plugin http://plugins.jquery.com/project/cookie
 *
 * Work by Rodolphe Franceschi
 */


// Class definition
function jQueryextendedjsoncookieUtils()
{

}

/* Fonction de compatibilite avec la librairie initiale */
jQueryextendedjsoncookieUtils.corewritefunction = function(argss)
{
  var name = argss[0];
  var value = argss[1];
  var options = argss[2];


  options = options || {};
  var expires = '';
  if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
      var date;
      if (typeof options.expires == 'number') {
          date = new Date();
          date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
      } else {
          date = options.expires;
      }
      expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
  }
  var path = options.path ? '; path=' + (options.path) : '';
  var domain = options.domain ? '; domain=' + (options.domain) : '';
  var secure = options.secure ? '; secure' : '';
  var cookievalue = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  document.cookie = cookievalue;
}






/* Simple deletion of the cookie */
jQueryextendedjsoncookieUtils.removeCookie = function(argss)
{
  var cookiename = argss[0];

  varcookievalue = jQueryextendedjsoncookieUtils.getCookieValueDecoded( argss )
  if ( varcookievalue != undefined )
  {
    document.cookie = cookiename +'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
  }
}

/* Simple write of all the cookie content with an empty value */
jQueryextendedjsoncookieUtils.writeEmptyCookie = function(argss)
{
  var cookiename = argss[0];

  document.cookie = cookiename + '=';
}

/* Simple write of all the cookie content */
jQueryextendedjsoncookieUtils.writeCookie = function(argss)
{
  jQueryextendedjsoncookieUtils.corewritefunction(argss);
}


/* Get the cookie value encoded */
jQueryextendedjsoncookieUtils.getCookieValue = function(argss)
{
  var cookiename =  argss[0];

  var fullcookievalue = jQueryextendedjsoncookieUtils.getFullCookie(argss);
  if (fullcookievalue == undefined)
  {
    return undefined;
  }
  return fullcookievalue.substring(cookiename.length + 1);
}

/* get The cookie valude decoded */
jQueryextendedjsoncookieUtils.getCookieValueDecoded = function(argss)
{
  var cookievalue = jQueryextendedjsoncookieUtils.getCookieValue(argss);
  if (cookievalue == undefined) {return undefined; };
  return decodeURIComponent(cookievalue);
}

/* get The cookie valude json-ed.  added by AK */
jQueryextendedjsoncookieUtils.getCookieValueJsoned = function(argss){
  return jQuery.evalJSON(jQueryextendedjsoncookieUtils.getCookieValueDecoded(argss));
}

/* Get the value of a cookie by cookie name*/
jQueryextendedjsoncookieUtils.getFullCookie = function(argss)
{
  var cookiename = argss[0];

  var cookieValue = undefined;
  var componentValueOutput = undefined;

  if (document.cookie && document.cookie != '')
  {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++)
    {
      var cookie = jQuery.trim(cookies[i]);

      if (cookie.substring(0, cookiename.length + 1) == (cookiename + '='))
      {
        componentValueOutput = cookie;
        break;
      }
    }
  }
  return componentValueOutput;
}

/*
 * Advanced function thar stores Extended attributes (not value).
 * Warning, This function must be called AT THE END OF THE CALLS
 */
jQueryextendedjsoncookieUtils.setExtendedAttributes = function(argss)
{
  var cookiename = argss[0];
  var extendedattributesarray = argss[1];

  var cookvalue = jQueryextendedjsoncookieUtils.getCookieValueDecoded(argss);
  var argstopass = Array(cookiename, cookvalue, extendedattributesarray);

  jQueryextendedjsoncookieUtils.corewritefunction(argstopass);
}

/*
 * Function that gets a variale Value from a cookie
 */
jQueryextendedjsoncookieUtils.getCookieVariable = function(argss)
{
  var cookiename = argss[0];
  var variablename = argss[1];

  var cookvalue = jQueryextendedjsoncookieUtils.getCookieValueDecoded(argss);
  if (cookvalue != '' && cookvalue != undefined)
  {
    jsonoutput_eval = $.evalJSON(cookvalue);
    return jsonoutput_eval[variablename];
  }

  return undefined;
}


/*
 * Advanced function that stores a variable in the value of the cookie in Json data exchange format
 */
jQueryextendedjsoncookieUtils.setCookieVariable = function(argss)
{
  var cookiename = argss[0];
  var variablename = argss[1];
  var variablevalue = argss[2];
  var options = argss[3];// added so that we can target the cookie with specific extended attributes AK

  var jsonoutput = undefined;

  // First, get the cookie value
  var cookvalue = jQueryextendedjsoncookieUtils.getCookieValueDecoded(Array(cookiename));

  // if cookie value is undefined, write empty cookie then set the variable
  if ( (cookvalue == undefined) || (cookvalue == '') )
  {
    jQueryextendedjsoncookieUtils.writeEmptyCookie(Array(cookiename));

    var variableunique = new Object();
    variableunique[variablename] = variablevalue;

    var chainejsonencoded = $.toJSON(variableunique);

    var argstopass = new Array();
    argstopass.push(cookiename);
    argstopass.push(chainejsonencoded);

    jQueryextendedjsoncookieUtils.writeCookie(argstopass);
  }
  else
  {
    // else, add the variable to the cookie
    jsonoutput_eval = $.evalJSON(cookvalue);
    jsonoutput_eval[variablename] = variablevalue;
    var chainejsonencoded = $.toJSON(jsonoutput_eval);

    var argstopass = new Array();
    argstopass.push(cookiename);
    argstopass.push(chainejsonencoded);
    argstopass.push(options);// added so that we can target the cookie with specific extended attributes. AK

    jQueryextendedjsoncookieUtils.writeCookie(argstopass);
  }
}





// JQuery Interface
// We assume that first argument is method name....
jQuery.extendedjsoncookie = function()
{
  // We forge dynamic call chain
  var chain = "jQueryextendedjsoncookieUtils.";
  var internalargs = new Array();
  for (var i=0; i < arguments.length; i++)
  {
     var thisarg = arguments[i];
     if (i == 0)
     {
       chain = chain + thisarg;
     }
     else
     {
       internalargs.push(thisarg);
     }
  }

  // We make an eval on it
  return eval(chain) ( internalargs );
};


/*
 *
 * SECTION 3: drso library
 *
 *
*/


//http://atl.img.digitalriver.com/drso/drso-1.6.2.min.js
var drso={version:'1.6.2',url:location.href.toLowerCase(),setCookie:function(n,v,d,e){var de=new Date();de.setTime(de.getTime()+e*24*60*60*1000);document.cookie=n+'='+escape(v)+((e===null)?'':('; expires='+de.toGMTString()))+'; path=/'+((d===null)?'':(';domain='+d))},getDomain:function(){var sld=document.domain,dp=sld.split("."),l=dp.length;if(l<2){sld=null}else if(!isNaN(dp[l-1])&&!isNaN(dp[l-2])){sld=null}else{sld="."+dp[l-2]+"."+dp[l-1]}return sld},getCookie:function(c_name){if(document.cookie.length>0){var c_start=document.cookie.indexOf(c_name+'='),c_end;if(c_start!==-1){c_start=c_start+c_name.length+1;c_end=document.cookie.indexOf(';',c_start);if(c_end===-1){c_end=document.cookie.length}return unescape(document.cookie.substring(c_start,c_end))}}return""},deleteCookie:function(name){this.setCookie(name,'',this.getDomain(),-1)},getRefUrl:function(domain,exp){if(!drso.getCookie('op_refUrl')){exp=(typeof(exp)==='undefined')?null:exp;domain=(typeof(domain)==='undefined')?this.getDomain():domain;var refUrl=(document.referrer)?document.referrer.toLowerCase():'none';this.setCookie('op_refUrl',refUrl,domain,exp)}return this.getCookie('op_refUrl')},getQsPval:function(pname,strShort){var pval='',nvnames={n:(typeof(strShort)==='undefined')?'n':'p_name',v:(typeof(strShort)==='undefined')?'v':'p_val'},nvpattern=new RegExp(nvnames.n+'='+pname+'&'+nvnames.v+'=([^&]*)','i'),param=location.search.match(nvpattern);if(param){pval=decodeURIComponent(param[1])}return pval},clickthruRedirect:function(href,clickthru,clickthruUrlArg,extraParams){var hrefParams='',hrefPrefix='',extraParams=(typeof(extraParams)==='undefined')?'':extraParams,loc=location.href;loc=loc.substring(0,loc.lastIndexOf('/'));if(href.indexOf('//')===0){hrefPrefix=location.protocol}else if(href.indexOf('/')===0){hrefPrefix=location.protocol+'//'+location.hostname}else if(href.substring(0,4)!=='http'&&href.substring(0,5)!=='https'){while(/^\.\./.test(href)){loc=loc.substring(0,loc.lastIndexOf('/'));href=href.substring(3)}href=loc+'/'+href}if(href.indexOf('?')!==-1){hrefParams='&'+href.split('?')[1];href=href.split('?')[0]}window.location=clickthru+'?'+clickthruUrlArg+'='+hrefPrefix+href+hrefParams+extraParams},setSessionVar:function(k,v){var w=window.name;v=escape(v);if(w.indexOf(k)!==-1){w=w.replace(w.split(k+'=')[1].split('&')[0],v)}else if(w.length){w=w+'&'+k+'='+v}else{w=k+'='+v}window.name=w},getSessionVar:function(k){var w=window.name;if(w.indexOf(k)!==-1){return unescape(w.split(k+'=')[1].split('&')[0])}else{return''}},log:function(s){if(typeof(console)==='object'){console.log(s)}},getSerializedParam:function(argName,argDelimStart,argDelimEnd,argHaystack,caseInsens){var argHaystack=(typeof(argHaystack)==='undefined')?window.location.href:argHaystack;if(caseInsens){argHaystack=argHaystack.toLowerCase();argName=argName.toLowerCase()}if(argHaystack.indexOf(argName)!==-1){var argPos=argHaystack.indexOf(argName);if(!argDelimStart){argDelimStart=argHaystack.substring(argPos-1,argPos)}if(!argDelimEnd){argDelimEnd=argHaystack.substring(argPos+argName.length,argPos+argName.length+1)}var sPattern=(argHaystack.indexOf(argName)==0)?'':'['+argDelimStart+']';sPattern=sPattern+argName+argDelimEnd+'([^'+argDelimStart+'#?&]*)';var oRegEx=new RegExp(sPattern),aResults=oRegEx.exec(argHaystack);if(!aResults){return false}else{return aResults[1]}}else{return false}},getUrlParam:function(argName,argDelimStart,argDelimEnd,argHaystack,caseInsens){return this.getSerializedParam(argName,argDelimStart,argDelimEnd,argHaystack,caseInsens)},getURLparam:function(argName,argDelimStart,argDelimEnd,argHaystack,caseInsens){return this.getSerializedParam(argName,argDelimStart,argDelimEnd,argHaystack,caseInsens)}};


/*
 *
 * SECTION 4: MS Store custom personilization scripts
 *
 *
*/

/* To store personalization data, we encode all the paramters into json and then store it in ot_personal cookie.  Each parameter has 4 properties: name, value, last modified date, expiration.  The cookie itself will live one year.  date info will be stored in "dateString" format == yyyymmdd, to be readable.  "dateObj" will be used to refer to JS date object.  Expiration will be simply a number of days from the last modified date. */


//defining "personal" object and its properties/methods
drso.personal = {};
drso.personal.cookieName = 'op_personal';
drso.oneDay = 1000*60*60*24;
drso.today = new Date();


//set the date in a string format YYYYMMDD.  If no argument, it'll use today
drso.setDateString = function(dateObj){
  if (typeof dateObj === 'undefined'){
    var dateObj = drso.today;
  }
  var year =  dateObj.getFullYear();
  var month = dateObj.getMonth()+1; //month goes from 0-11, so it's confusing
  if (month < 10) { //make it two digit
    month = '0' + month.toString();
  }
  var date = dateObj.getDate();
  if (date < 10){
    date = '0' + date.toString();
  }

  return year.toString()+month.toString()+date.toString();
}

//decode the date string in format YYYYMMDD and turn it into JS date object
drso.setDateObj = function(dateString){

  var year = dateString.substr(0,4);
  var month = dateString.substr(4, 2);
  month = Number(month)-1; //month are 0-11
  var date = dateString.substr(6,2);
  return new Date(year, month, date);

}


//personalization data object
drso.personal.param = function(paramValue, modDate, expInDays){
  this.value = paramValue;
  this.modDate = modDate;
  this.expInDays = expInDays;
}


//find the value of data stored in the personalization cookie
drso.personal.getData = function(pName){

  //find the cookie and look for the data
  var pData = $.extendedjsoncookie('getCookieVariable',drso.personal.cookieName, pName);
  if (pData) {
    return pData;
  } else {
    return false;
  }

}

//get all the data stored in the cookie as json.
drso.personal.getAllData = function(){
  return $.extendedjsoncookie('getCookieValueJsoned', drso.personal.cookieName);
}

//check to see if a parameter is expired.
drso.personal.isExpired = function(pName){
  var pData = drso.personal.getData(pName);
  if (!pData){
    return true;  // data is not there, so it's the same as being expired
  } else if (drso.today.getTime() > (drso.setDateObj(pData.modDate).getTime()+(pData.expInDays*drso.oneDay))) {
    return true;
  } else {
    return false;
  }
}


//store the value with the last modified date and expiration date in cookie.  futureDate is the number of days in the future from today.  I don't know if it's needed, but just in case.
drso.personal.storeData = function(pName, value, expInDays, forceOverwrite, futureDate){

  //if the cookie & parameter is there and the value's not expired and forceOverwrite is not true, then do nothing.
  if (!drso.personal.isExpired(pName) && !forceOverwrite){
    drso.log('the parameter is not expired or forceOverwrite is off')
    return;
  } else {
    //otherwise, store the data in the cookie
    var modDate = futureDate ? drso.setDateString(new Date(drso.today.getTime()+futureDate*drso.oneDay)) : drso.setDateString(drso.today);
    var pParam = {
      value:value,
      modDate: modDate,
      expInDays: expInDays};
    //if cookie's not there, I'm going to set it using drso -- because the json cookie plugin sets it first with whole domain and full path. I should rewrite the writeEmptyCookie method in the plugin.
    if (!drso.getCookie(drso.personal.cookieName)){
      //it can't be an empty cookie, it has to have some value or the next plugin function will write a new cookie at the specific path
      drso.setCookie(drso.personal.cookieName, '{}', drso.getDomain(), 366);
    }

    $.extendedjsoncookie('setCookieVariable', drso.personal.cookieName, pName, pParam, {domain: drso.getDomain(), path: '/', expires: 366});
    //modify the cookie's expiration date so it will be one year from this day.  The domain and path have to be specified each time or otherwise the script will set a new cookie at whole domain and specific path name
    //$.extendedjsoncookie('setExtendedAttributes', drso.personal.cookieName, {domain: drso.getDomain(), path: '/', expires: 366});
  }

}

//OS detection
drso.uAgent = navigator.userAgent.toLowerCase();
drso.detectOS = function(){
  //for now we only need to detect versions of Windows.
  if (drso.uAgent.indexOf('windows nt 5.1') !== -1) {
    return 'xp';
  }
  else
    if (drso.uAgent.indexOf('windows nt 6.0') !== -1) {
      return 'vista';
    }
    else
      if (drso.uAgent.indexOf('windows nt 6.1') !== -1) {
        return 'win7';
      }
      else
        if (drso.uAgent.indexOf('xbox') !== -1) {
          return 'xbox';
        } else {
          return false;
        }

}



