Path: blob/master/phs/google-otp/index_files/gr_reco5.min.js.download
996 views
(function(){var TrimPath;var multiline;var grJSON3;var privatescope={};var module=undefined;var define=undefined;window.undefined=window.undefined;var GravityRD={config:{},apply:function(obj,conf,overwrite){if(obj&&conf&&typeof conf=="object"){for(var k in conf){if(overwrite===undefined||overwrite===true){obj[k]=conf[k]}else{if(obj[k]===undefined){obj[k]=conf[k]}}}}return obj},override:function(origclass,override){GravityRD.apply(origclass.prototype,override)},extend:function(sp,overrides){var sb=overrides.constructor!=Object.prototype.constructor?overrides.constructor:function(){sp.apply(this,arguments)};var F=function(){},sbp,spp=sp.prototype;F.prototype=spp;sbp=sb.prototype=new F();sbp.constructor=sb;sb.superclass=spp;if(spp.constructor==Object.prototype.constructor){spp.constructor=sp}sb.override=function(o){GravityRD.override(sb,o)};sbp.superclass=(function(){return spp});sbp.override=function(o){for(var m in o){this[m]=o[m]}};GravityRD.override(sb,overrides);sb.extend=function(o){return GravityRD.extend(sb,o)};if(overrides.__public__!=undefined||spp.__public__!=undefined){var _public=[];if(overrides.__public__!=undefined){var remove={};for(var i=0;i<overrides.__public__.length;i++){name=overrides.__public__[i];if(name.charAt(0)==="-"){name=name.substring(1);remove[name]=true}else{_public.push(name);remove[name]=true}}if(spp.__public__!=undefined){for(var i=0;i<spp.__public__.length;i++){name=spp.__public__[i];if(!remove[name]){_public.push(name)}}}}else{_public=spp.__public__}sbp.__public__=_public}return sb},bind:function(func,scope){return function(){return func.apply(scope,arguments)}},namespace:function(ns){var domains=ns.split(".");var p=eval(domains[0])||{};for(var i=1;i<domains.length;i++){p[domains[i]]=p[domains[i]]||{};p=p[domains[i]]}return p},register:function(ns,name,module){ns=this.namespace(ns);if(typeof(module.__interface__)=="function"){ns[name]=module.__interface__()}else{ns[name]=module}},isObject:function(o){if(o==null){return false}return Object.prototype.toString.apply(o)==="[object Object]"},isArray:function(o){if(o==null){return false}return Object.prototype.toString.apply(o)==="[object Array]"},isFunction:function(o){if(o==null){return false}return typeof(o)==="function"},isString:function(o){return typeof(o)==="string"},isNull:function(o){return o===null},isUndefined:function(o){return o===undefined},each:function(input,fn,scope){if(!input){return}if(!this.isString(input)&&typeof input.length=="number"){for(var i=0;i<input.length;i++){fn.call(scope||this,input[i],i)}}else{fn.call(scope||this,input)}},map:function(obj,iterator,scope){var results=[];if(obj==null){return results}this.each(obj,function(value,index,list){results[results.length]=iterator.call(scope,value,index,list)});return results},obj:function(list,values){if(list==null){return{}}var result={};for(var i=0,l=list.length;i<l;i++){if(values){result[list[i]]=values[i]}else{result[list[i][0]]=list[i][1]}}return result},keys:function(object){var ret=[];for(k in object){if(object.hasOwnProperty(k)){ret.push(k)}}return ret},hash:function(nv){var na=GravityRD.keys(nv);na.sort(function(a,b){return a<b?-1:(a>b?+1:0)});var input="";for(var i=0;i<na.length;i++){var val=nv[na[i]];input+=na[i]+":"+(GravityRD.isArray(val)?val.join(","):val)+";"}hash=(function(e){for(var r=0,i=0;i<e.length;i++){r=(r<<5)-r+e.charCodeAt(i),r&=r}return r})(input);return hash},init:function(conf,buildSHA){GravityRD.Typecheck.argumentChecker("GravityRD.init",arguments).notNull(0).notUndefined(0).isObject(0);conf.buildSHA=buildSHA;GravityRD.Core.setServer(conf)},start:function(){GravityRD.Log.timeStamp("GR:start()");if(GravityRD.Worker.start()){if(GravityRD.Core.getConfig()["mode"]==="DEVELOP"){GravityRD.Log.info("Develop mode enabled. Please don't forget to turn it off.")}if(GravityRD.Core.debug("api")){window.GR=this;window.GR.sd=function(){console.log("click",unescape(window.localStorage.getItem("gr_click")));console.log("click_ts",unescape(window.localStorage.getItem("gr_click_ts")));console.log("recmap",unescape(window.localStorage.getItem("gr_recmap")));console.log("recmap_ts",unescape(window.localStorage.getItem("gr_recmap_ts")));console.log("recmapkeys",unescape(window.localStorage.getItem("gr_recmapkeys")));console.log("recmapkeys_ts",unescape(window.localStorage.getItem("gr_recmapkeys_ts")));console.log("event",unescape(window.localStorage.getItem("gr_event")));console.log("track",unescape(window.localStorage.getItem("gr_track")));console.log("cart",unescape(window.localStorage.getItem("gr_cart")))};window.GR.sr=function(){window.localStorage.removeItem("gr_click");window.localStorage.removeItem("gr_click_ts");window.localStorage.removeItem("gr_recmap");window.localStorage.removeItem("gr_recmap_ts");window.localStorage.removeItem("gr_recmapkeys");window.localStorage.removeItem("gr_recmapkeys_ts");window.localStorage.removeItem("gr_event");window.localStorage.removeItem("gr_track");window.localStorage.removeItem("gr_cart");return window.localStorage}}window.GravityRD={validationError:function(o){GravityRD.Log.validationError(o)},setGeneratedCookie:function(cid){GravityRD.Core.Cookie.setGeneratedCookie(cid)},responseCallback:function(result){GravityRD.Core.useResultCB(result)},searchCallback:function(name,data){if(GravityRD.Search!=undefined){GravityRD.Search.callback(name,data)}},multiline:function(){return multiline.apply(this,arguments)}}}}};GravityRD.Base=GravityRD.extend(Object,{__public__:[],__interface__:function(){var _private=this;var ret={};for(var idx=0;idx<this.__public__.length;idx++){var name=this.__public__[idx];ret[name]=(function(name){return function(){return _private[name].apply(_private,arguments)}})(name)}return ret}});GravityRD.Exc=GravityRD.extend(Object,{APIUSAGE:1,VALIDATION:2,constructor:function(type,msg){this.type=type;this.msg=msg},toString:function(){return this.msg}});(function(){var javascriptEscape=function(s){return String(s).replace(/\\/g,"\\\\").replace(/\0/g,"\\x00").replace(/"/g,"\\x22").replace(/'/g,"\\x27").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/&/g,"\\x26").replace(/</g,"\\x3c").replace(/>/g,"\\x3e").replace(/-/g,"\\x2d")};var modifiers={html:function(s){return String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")},javascript:javascriptEscape,js:javascriptEscape,truncate:function(s,l,d){var ret=s;if(s.length>l){ret=s.substring(0,l)+d}return ret}};var GravityRD_Core=GravityRD.Base.extend({__public__:["process","set","setServer","useResultCB","errorCB","saveParams","addListener","getConfig","getRequestNumber","setRecId","debug","debugMask","setGlobalNameValue","addGlobalNameValue","getGlobalNameValue","search","onUsageError"],serverConfigDefault:{disabled:false,buildSHA:"notset",targetServer:"saas.gravityrd.com",retargetingTrack:false,retargetingServer:"api.worldgravity.com",partnerId:null,mode:"PROD",debug:{api:true,perf:true,tracking:true,postrender:true,log:true,hud:true,routing:true,callback:true},trackEvents:false,trackEventsMaxSize:20,trackEventsFilter:{VIEW:[]},trackCart:false,trackPageLeaveEvent:false,trackReferrer:false,trackLocation:false,trackSession:false,trackPage:false,sessionStorage:true,logExceptions:true,enableRegisterRecId:false,cookiePath:"/",cookieDomain:null,addRandomSeed:false,randomSeedExpire:10,deferEvents:true,deferEventsTime:15000,recClickExpire:0,recClickTrackMax:10,nullStrings:["null","NULL","nil","0"],wrongNameValues:["userId","cookieId"],allowOverride:["mode","sessionStorage"],customConfig:"enabled",customConfigDemoKey:"F8",routingGlobal:{useUser:false},forceProtocol:false,persistUserId:false,nameValueMaxSize:1024},serverConfig:null,globalConfig:{userId:null,cookieName:"gr_reco",cookieId:null,retargeting:false,useJsGeneratedCookie:true},requestNumber:0,parmsHistory:[],params:null,handle:null,firstCall:true,globalNameValues:{},listeners:[],addGlobalNameValue:function(key,val,overwrite,persist){if(key==="userId"){this.set({userId:""+val});return}if(this.globalNameValues[key]===undefined||overwrite===true){this.globalNameValues[key]=[]}else{if(!GravityRD.isArray(this.globalNameValues[key])){var tmp=this.globalNameValues[key];this.globalNameValues[key]=[];if(tmp!==undefined&&tmp!==null){this.globalNameValues[key].push(tmp)}}}GravityRD.each(val,function(item){if(item!==null&&item!==undefined){var ms=this.getConfig()["nameValueMaxSize"];var v=""+item;if(v!==undefined&&v!==null&&v.length>ms){v=v.substring(0,ms);GravityRD.Log.debug("Truncating namevalue '"+key+"', because it exceeds size limit "+ms)}this.globalNameValues[key].push(v)}},this);if(this.globalNameValues[key].length==1){this.globalNameValues[key]=this.globalNameValues[key][0]}else{if(this.globalNameValues[key].length==0){delete this.globalNameValues[key]}}GravityRD.Log.debug("Adding global nameValue '"+key+"':'"+val+"', overwrite="+overwrite+", persist="+persist,this.globalNameValues[key]);if(persist==="session"){GravityRD.Core.Cookie.addSessionNameValue(key,this.globalNameValues[key])}else{if(!!persist){GravityRD.Core.Cookie.addPersistentNameValue(key,this.globalNameValues[key])}}},setGlobalNameValue:function(key,val,persist){this.addGlobalNameValue(key,val,true,persist)},getGlobalNameValue:function(key){return this.globalNameValues[key]},addListener:function(listener){this.listeners.push(listener)},constructor:function(){this.initParams()},setServer:function(rd){if(this.serverConfig==null){this.serverConfig={};GravityRD.apply(this.serverConfig,this.serverConfigDefault);GravityRD.apply(this.serverConfig,rd);var scriptTags=document.getElementsByTagName("script");for(var k=0;k<scriptTags.length;k++){var mt=(scriptTags[k].src||"").match(/\/([^/]*)\/gr_reco.(.min)?\.js/);if(mt){var src=scriptTags[k].src;var match=src.match(/:\/\/([^/]*)/);var m=match[1].replace(/local\./,"");var kk=GravityRD.keys(rd.overlays||{});for(var i=0;i<kk.length;i++){var key=kk[i];if(m.match(new RegExp(".*"+key+".*"))){GravityRD.apply(this.serverConfig,rd.overlays[key])}}if(!rd.partnerId){this.serverConfig.partnerId=mt[1]}if(!rd.targetServer){this.serverConfig.targetServer=m}if(!rd.retargetingServer){this.serverConfig.retargetingServer=mt[1]+".worldgravity.com"}break}}}},set:function(rd){var ao=this.getConfig()["allowOverride"]||[];for(var k in rd){if(!rd.hasOwnProperty(k)){continue}if(k==="type"){continue}if(k==="mode"&&GravityRD.Core.debug("log")){this.globalConfig.mode="DEVELOP";this.serverConfig.mode="DEVELOP";continue}if(this.globalConfig[k]!==undefined){if(!GravityRD.isUndefined(rd.userId)&&rd.userId!==this.globalConfig.userId&&this.parmsHistory.length!=0){GravityRD.Log.debug("The userId has changed: emptying buffers.");this.scheduleRequest(-1);this.request()}this.globalConfig[k]=rd[k];if(k=="userId"){var persist=this.getConfig()["persistUserId"];if("session"===persist){GravityRD.Core.Cookie.addSessionNameValue(k,this.globalConfig[k])}else{if(!!persist){GravityRD.Core.Cookie.addPersistentNameValue(k,this.globalConfig[k])}}}}else{var found=false;for(var j=0;j<ao.length;j++){if(ao[j]===k){this.globalConfig[k]=rd[k];found=true;break}}if(!found){GravityRD.Log.debug("Attribute '"+k+"' treated as global nameValue");this.setGlobalNameValue(k,rd[k])}}}},getRequestNumber:function(){return this.requestNumber},addEvent:function(rd){rd.recId=rd.recommendationId||rd.recId||undefined;rd.recommendationId=undefined;if(rd.recId==undefined){var rid;if(rd.eventType==="REC_CLICK"){rid=GravityRD.Core.Cookie.getRecId(rd.itemId);if(rid!=null){GravityRD.Log.debug("Adding recId '"+rid+"' for event '"+rd.eventType+"', item '"+rd.itemId+"'");GravityRD.Core.Cookie.registerRecClickId(rd.itemId,rid);rd.recId=rid}}else{rid=GravityRD.Core.Cookie.getRecClickId(rd.itemId);if(rid!=null){GravityRD.Log.debug("Adding recClickId '"+rid+"' for event '"+rd.eventType+"', item '"+rd.itemId+"'");rd.recId=rid}}}this.addLocationAndReferrer("event",rd);GravityRD.Core.Cookie.trackEvents(rd);this.params.events.push(rd);GravityRD.each(this.listeners,function(listener){if(GravityRD.isFunction(listener.onEvent)){listener.onEvent.call(this,rd)}},this)},addLocationAndReferrer:function(type,rd){var config=GravityRD.Core.getConfig();var trackReferrer=config.trackReferrer||{};if(trackReferrer===true||trackReferrer[type]===true){if(document.referrer!=undefined&&document.referrer!=null){GravityRD.Log.debug("Adding referrer '"+document.referrer+"' for "+type,rd);rd._referrer=document.referrer}}var trackLocation=config.trackLocation||{};if(trackLocation===true||trackReferrer[type]===true){if(document.location.href!==undefined&&document.location.href!=null){GravityRD.Log.debug("Adding location '"+document.location.href+"' for "+type,rd);rd._location=document.location.href}}},addRandomSeed:function(rd){if(GravityRD.Core.getConfig()["addRandomSeed"]){rd.GravityRandomSeed=GravityRD.Core.Cookie.getRandomSeed()}},debug:function(key){var debugGlobal=this.getConfig()["debugGlobal"]||[];var debugConfig=this.getConfig()["debug"];var ret=this.debugMask[key]||debugGlobal[key]||false;if(debugConfig===true){return ret}else{return !!debugConfig[key]&&ret}},debugMask:function(mask){this.debugMask=mask},addRecommendationRequest:function(rd){this.checkTemplating(rd);if(rd.resultNames==undefined&&rd.templating!=undefined&&!rd.templating.serverSide){rd.resultNames=this.parseTemplateVariables(rd.templating.template);GravityRD.Log.debug("Autogenerating resultNames",rd.resultNames)}rd.recommendationIndex=this.params.recommendationRequests.length;if(rd.groupId!==undefined){if(rd.groupSeq==undefined){GravityRD.Log.usageError("GR-023",rd.groupId)}var index=-1;for(var i=0;i<this.params.recommendationRequests.length;i++){if(this.params.recommendationRequests[i].groupId==rd.groupId){index=i;break}}if(index==-1){if(rd.groupSize==undefined){GravityRD.Log.usageError("GR-024",rd.groupId)}if(rd.groupSize<1){GravityRD.Log.usageError("GR-026",rd.groupId,rd.groupSize)}if(rd.groupSize==1){rd.__completed=true}}else{var last=this.params.recommendationRequests[index];var size=last.groupSize;if(rd.groupSize!=undefined){if(rd.groupSize!==size){GravityRD.Log.usageError("GR-027",rd.groupId,rd.groupSize,size)}}var seq=1;while(last.__next!==undefined&&last.__next!==null){seq=seq+1;last=last.__next}if(seq+1==rd.groupSeq){last.__next=rd;if(seq+1==size){last=this.params.recommendationRequests[index];last.__completed=true;while(last.__next!==undefined&&last.__next!==null){last=last.__next;last.__completed=true}}}else{GravityRD.Log.usageError("GR-025",rd.groupId,rd.groupSeq,seq+1)}}}this.addLocationAndReferrer("recommendation",rd);this.addRandomSeed(rd);this.params.recommendationRequests.push(rd);GravityRD.each(this.listeners,function(listener){if(GravityRD.isFunction(listener.onRecommendation)){listener.onRecommendation.call(this,rd)}},this)},addExplanationRequest:function(rd){this.checkTemplating(rd);if(rd.resultNames==undefined&&rd.templating!=undefined){rd.resultNames=this.parseTemplateVariables(rd.templating.template);GravityRD.Log.debug("Autogenerating resultNames",rd.resultNames)}rd.explanationIndex=this.params.explanationRequests.length;this.addLocationAndReferrer("explanation",rd);this.addRandomSeed(rd);this.params.explanationRequests.push(rd);GravityRD.each(this.listeners,function(listener){if(GravityRD.isFunction(listener.onExplanation)){listener.onExplanation.call(this,rd)}},this)},checkTemplating:function(rd){if(rd.templating===undefined&&rd.callback===undefined){GravityRD.Log.usageError("GR-012")}if(rd.templating!==undefined){rd.templating.serverSide=false;if(rd.templating.templateElementId!=undefined){if(rd.templating.template!==undefined){GravityRD.Log.usageError("GR-013")}var element=document.getElementById(rd.templating.templateElementId);if(element!=null){rd.templating.template=element.value;if(typeof(templateContent)==="undefined"){rd.templating.template=element.innerHTML}}}else{if(rd.templating.templateId!==undefined&&rd.templating.template===undefined){GravityRD.Log.debug("Server side templating");rd.templating.serverSide=true}else{if(rd.templating.template===undefined){GravityRD.Log.usageError("GR-014")}}}}if(rd.templating&&rd.templating.template===undefined&&rd.templating.templateId===undefined){GravityRD.Log.usageError("GR-015")}if(rd.templating&&rd.templating.template!==undefined&&rd.templating.templateId!==undefined){GravityRD.Log.usageError("GR-030")}},getConfig:function(){var ret={};GravityRD.apply(ret,this.globalConfig);GravityRD.apply(ret,this.serverConfig);var ao=(this.serverConfig.allowOverride||[]);for(var i=0;i<ao.length;i++){if(this.globalConfig[ao[i]]!=undefined){ret[ao[i]]=this.globalConfig[ao[i]]}}return ret},request:function(){var dequeue=GravityRD.Core.Cookie.dequeueEvents()||[];var uid=this.globalConfig.userId;if(dequeue.length>0&&dequeue[0].__userId!==uid){GravityRD.Log.debug("Warning: 'uid' and 'euid' is different, possible misconfiguration issue. uid:"+uid+", euid:"+dequeue[0].__userId);var oldParams=this.params;this.initParams(null,dequeue);GravityRD.Core.Request.createRequest(this.getConfig(),this.params);this.params=oldParams;GravityRD.Core.Request.createRequest(this.getConfig(),this.params)}else{this.params.events=dequeue.concat(this.params.events);GravityRD.Core.Request.createRequest(this.getConfig(),this.params)}},scheduleRequest:function(ms){if(this.handle!=null){window.clearTimeout(this.handle)}if(ms>=0){window.setTimeout(GravityRD.bind(this.request,this),ms)}},process:function(queue,force){GravityRD.Log.group("Processing",true);var submit=this.firstCall;this.firstCall=false;submit|=(force||false);var config=GravityRD.Core.getConfig();for(var l=0;l<queue.length;l++){var command=queue[l];if(!(command.type==="set"||command.type==="fakeexception")){GravityRD.apply(command,this.globalNameValues,false);command.__userId=this.globalConfig.userId}GravityRD.Typecheck.pushObjectChecker(command).validate();if(command.type==="recommendation"){GravityRD.Log.timeStamp("GR:RD");this.addRecommendationRequest(command);submit=true}else{if(command.type==="explanation"){this.addExplanationRequest(command);submit=true}else{if(command.type==="event"){this.addEvent(command)}else{if(command.type==="set"){this.set(command)}else{if(command.type==="fakeexception"){config=GravityRD.Core.getConfig();var ep=GravityRD.Core.Request.getEndpoint(config.retargeting,"JSServlet4");GravityRD.Core.Request.scriptTagRequest(ep,"ec=fake")}else{if(command.type==="register-recid"){if(config.enableRegisterRecId===true){for(var i=0;i<command.itemId.length;i++){GravityRD.Core.Cookie.registerRecId(command.itemId[i],command.recId)}}else{GravityRD.Log.usageError("GR-019")}}else{if(command.type==="domready"){GravityRD.CustomConfig.domready(command.apply,true)}else{if(command.type==="customconfig"){GravityRD.Log.timeStamp("GR:CC push");window.setTimeout((function(c){return function(){GravityRD.Log.timeStamp("GR:CC");GravityRD.Log.time("GR:CC");GravityRD.CustomConfig.set(c.config,c.environment,true);GravityRD.Log.timeEnd("GR:CC")}})(command),0)}else{if(command.type==="search"){GravityRD.Search.install(command);submit=false}else{GravityRD.Log.error("Invalid type specified for push object!",queue)}}}}}}}}}}GravityRD.Log.groupEnd();if(config.deferEvents===false||submit){GravityRD.Log.debug("Immediate submit");this.scheduleRequest(-1);this.request()}else{GravityRD.Log.debug("Defered submit");GravityRD.Core.Cookie.queueEvents(this.params.events);this.params.events=[];this.scheduleRequest(config.deferEventsTime)}},initParams:function(o,e){this.params={events:e||[],requestNameValues:[],recommendationRequests:o||[],explanationRequests:[],templateData:{}};for(var i=0;i<this.params.recommendationRequests.length;i++){this.params.recommendationRequests[i].recommendationIndex=i}},saveParams:function(o){GravityRD.Log.debug("Remaining",o);this.parmsHistory.push(this.params);this.initParams(o);this.requestNumber++},useResultCB:function(result){GravityRD.Core.Request.useResultCB(result);GravityRD.Log.debug("useResultCB",result);if(result&&result.recommendationWrappers){var perfKey="GR:RD CB("+result.requestNumber+")";GravityRD.Log.timeStamp(perfKey);GravityRD.Log.time(perfKey);if(!!this.parmsHistory[result.requestNumber]){var resultPerf=this.parmsHistory[result.requestNumber].__perf;resultPerf.end();GravityRD.Log.debug("PERF",resultPerf.get(),true)}for(i=0;i<result.recommendationWrappers.length;i++){var recIndex=result.recommendationWrappers[i].recommendationIndex;var recRequest=this.parmsHistory[result.requestNumber].recommendationRequests[recIndex];var recommendation=result.recommendationWrappers[i].recommendation;recId=recommendation.recommendationId;recRequest.__rt_time=(+new Date())-recRequest.__stag_time;if(this.debug("stagtime")){this.addEvent({type:"event",eventType:"TRACK",rtTime:""+recRequest.__rt_time})}var perf=GravityRD.Perf.create("rec://"+recRequest.scenarioId+"/"+result.requestNumber+"/"+recIndex);if(recommendation.items!==undefined){(function(){var savedrec=recommendation;var savedrecid=recId;var savedURI="rec://"+recRequest.scenarioId+"/"+result.requestNumber+"/"+recIndex;window.setTimeout(function(){GravityRD.Log.group("Registering of recids for "+savedURI,true);for(var j=0;j<savedrec.items.length;j++){GravityRD.Core.Cookie.registerRecId(savedrec.items[j].itemid,savedrecid)}GravityRD.Log.groupEnd()},0)})()}perf.phase("register recid");if(recRequest.templating!==undefined){if(!recRequest.templating.serverSide){targetId=recRequest.templating.targetElementId;target=document.getElementById(targetId);recommendation.templateData=recRequest.templating.templateData;recommendation.template=recRequest.templating.template;recommendation._MODIFIERS=recRequest.templating.modifiers||{};GravityRD.apply(recommendation._MODIFIERS,modifiers);recommendation.template=recommendation.template.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");try{resultHTML=TrimPath.parseTemplate(recommendation.template).process(recommendation,{throwExceptions:true});if(recRequest.templating.replace===true){var wrapper=document.createElement("div");wrapper.innerHTML=resultHTML;while(wrapper.children.length!==0){target.parentNode.insertBefore(wrapper.children[0],target)}target.parentNode.removeChild(target)}else{target.innerHTML=resultHTML}}catch(e){GravityRD.Log.usageError("GR-028",e)}perf.phase("templating");if(GravityRD.Core.debug("perf")){var sheet=document.createElement("style");sheet.innerHTML=".gr_tooltip::after {background: rgba(0, 0, 0, 0.7);border-radius: 4px 4px 4px 4px;box-shadow: 2px 2px 16px rgba(0, 0, 0, 0.5);color: #FFF;content: attr(data-gr_tooltip);margin-top: -24px;padding: 3px 7px; position: absolute; opacity: 1; visibility: visible;transition: all 0.7s ease-in-out;}";document.body.appendChild(sheet);var info="N: "+perf.name+",Rt: "+recRequest.__rt_time+",Rr: "+perf.getPhases()["register recid"]+",Te: "+perf.getPhases()["templating"]+",Ca: "+perf.getPhases()["callback"];target.className=(target.className||"")+" gr_tooltip";target.setAttribute("data-gr_tooltip",info)}}else{if(recommendation.content!==undefined&&recRequest.templating.serverSide){var targetElement=document.getElementById(recRequest.templating.targetElementId);if(targetElement!==undefined){targetElement.innerHTML=recommendation.content}}}}if(recRequest.callback!==undefined){try{if(GravityRD.Core.debug("callback")){GravityRD.Log.debug("Evaluating callback",recRequest.callback)}recRequest.callback(recommendation,recRequest.templating)}catch(e){GravityRD.Log.error("Exception during callback evaluation (recommendation) ",e)}}perf.phase("callback");perf.end();GravityRD.Log.debug(perf.name,perf.get());GravityRD.each(this.listeners,function(listener){if(GravityRD.isFunction(listener.onRecommendationResponse)){listener.onRecommendationResponse.call(this,recRequest,recommendation)}},this)}GravityRD.Log.timeEnd(perfKey)}if(result&&result.explanationWrappers){for(var i=0;i<result.explanationWrappers.length;i++){var expIndex=result.explanationWrappers[i].explanationIndex;var expRequest=this.parmsHistory[result.requestNumber].explanationRequests[expIndex];var explanation=result.explanationWrappers[i].explanation;var recId=explanation.recommendationId;if(expRequest.templating!==undefined){var targetId=expRequest.templating.targetElementId;var target=document.getElementById(targetId);explanation.templateData=expRequest.templating.templateData;explanation.template=expRequest.templating.template;explanation._MODIFIERS=expRequest.templating.modifiers||{};GravityRD.apply(explanation._MODIFIERS,modifiers);explanation.template=explanation.template.replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&");var resultHTML=TrimPath.parseTemplate(explanation.template).process(explanation);if(expRequest.callback!==undefined){try{expRequest.callback(explanation,expRequest.templating)}catch(e){GravityRD.Log.error("Exception during callback evaluation (explanation)",e)}}}else{try{expRequest.callback(explanation)}catch(e){GravityRD.Log.error("Exception during callback evaluation (explanation)",e)}}}}},errorCB:function(rn,rri,eri){if(rri!==null){for(var i=0;i<rri.length;i++){var recIndex=rri[i];var recRequest=this.parmsHistory[rn].recommendationRequests[recIndex];if(recRequest.error!==undefined){try{recRequest.error(recRequest.templating)}catch(e){GravityRD.Log.error("Exception during error callback evaluation (recommendation) ",e)}}}}if(eri!==null){for(var i=0;i<eri.length;i++){var expIndex=eri[i];var expRequest=this.parmsHistory[rn].explanationRequests[expIndex];if(expRequest.error!==undefined){try{expRequest.error(expRequest.templating)}catch(e){GravityRD.Log.error("Exception during error callback evaluation (explanation) ",e)}}}}},parseTemplateVariables:function(input){var map={};var idx;while((idx=input.indexOf("${"))!=-1){input=input.substring(idx+2);var end=input.indexOf("}");if(end!=-1){var parName=input.substring(0,end);if(parName.indexOf("templateData.")==0){continue}if(parName.indexOf("|")!=-1){parName=parName.substring(0,parName.indexOf("|"))}if(parName.indexOf(".")!=-1){parName=parName.substring(parName.indexOf(".")+1);map[parName]=true}}}var ret=[];for(var k in map){ret.push(k)}return ret},onUsageError:function(msg){GravityRD.each(this.listeners,function(listener){if(GravityRD.isFunction(listener.onUsageError)){listener.onUsageError.call(this,msg)}},this)}});GravityRD.register("GravityRD","Core",new GravityRD_Core())})();(function(){var JSONSerializer=new GravityRD.extend(Object,{decodeValue:function(v){var o=null;try{o=grJSON3.parse(unescape(v))}catch(e){}return o},encodeValue:function(v){return escape(grJSON3.stringify(v))}});var LocalSessionStore=GravityRD.extend(Object,{set:function(name,value){localStorage.setItem(name,value)},get:function(name){return localStorage.getItem(name)}});var CookieSessionStore=GravityRD.extend(Object,{set:function(name,value){var config=GravityRD.Core.getConfig();var cookie=name+"="+value+";path="+config.cookiePath;var cookieDomainVal=GravityRD.Core.Cookie.resolveCookieDomain(config,document.location.host);if(cookieDomainVal!==null){cookie+=";domain="+cookieDomainVal}document.cookie=cookie},get:function(name){var cookie=document.cookie;if(cookie.length>0){var start=cookie.indexOf(name+"=");if(start!==-1){start=start+name.length+1;var c_end=cookie.indexOf(";",start);if(c_end===-1){c_end=cookie.length}return cookie.substring(start,c_end)}}return null}});var SessionStoreProvider=GravityRD.extend(Object,{instance:null,provide:function(){if(this.instance===null){var config=GravityRD.Core.getConfig();var localStoreEnabled=false;try{localStoreEnabled=!GravityRD.isUndefined(window.localStorage)&&config.sessionStorage===true}catch(e){}if(localStoreEnabled){try{window.localStorage.setItem("gr_localstoretest","test");window.localStorage.removeItem("gr_localstoretest")}catch(e){localStoreEnabled=false}}if(localStoreEnabled){this.instance=new LocalSessionStore()}else{this.instance=new CookieSessionStore()}}return this.instance}});var ClientObject=GravityRD.Base.extend({cookieName:null,handle:null,storageProvider:new SessionStoreProvider(),serializer:new JSONSerializer(),constructor:function(cookieName){this.cookieName=cookieName},getValue:function(key){var cookieRawVal=this.storageProvider.provide().get(this.cookieName);var cacheObj=this.serializer.decodeValue(cookieRawVal)||{};return cacheObj[key]},getAllValues:function(){var cookieRawVal=this.storageProvider.provide().get(this.cookieName);var cacheObj=this.serializer.decodeValue(cookieRawVal)||{};return cacheObj},setAllValues:function(values){this.storageProvider.provide().set(this.cookieName,this.serializer.encodeValue(values),0)},setValue:function(key,value){var cookieRawVal=this.storageProvider.provide().get(this.cookieName)||{};var cacheObj=(cookieRawVal!==null)?(this.serializer.decodeValue(cookieRawVal)||{}):{};cacheObj[key]=value;this.storageProvider.provide().set(this.cookieName,this.serializer.encodeValue(cacheObj),0)},removeValue:function(key){var cookieRawVal=this.storageProvider.provide().get(this.cookieName)||{};var cacheObj=(cookieRawVal!==null)?(this.serializer.decodeValue(cookieRawVal)||{}):{};delete cacheObj[key];this.storageProvider.provide().set(this.cookieName,this.serializer.encodeValue(cacheObj),0)},push:function(item,maxsize){var cookieRawVal=this.storageProvider.provide().get(this.cookieName);var cacheObj=(cookieRawVal!==null)?(this.serializer.decodeValue(cookieRawVal)||[]):[];cacheObj.push(item);if(maxsize!==undefined){if(cacheObj.length>maxsize){cacheObj=cacheObj.slice(cacheObj.length-maxsize)}}this.storageProvider.provide().set(this.cookieName,this.serializer.encodeValue(cacheObj),0)},get:function(){var cookieRawVal=this.storageProvider.provide().get(this.cookieName);var cacheObj=(cookieRawVal!==null)?this.serializer.decodeValue(cookieRawVal):null;return cacheObj}});var ClientSessionObject=ClientObject.extend({storageProvider:{instance:null,provide:function(){if(this.instance==null){this.instance=new CookieSessionStore()}return this.instance}}});var ExpiringClientObject=GravityRD.extend(Object,{values:null,times:null,handle:null,constructor:function(name){ExpiringClientObject.superclass.constructor(name);this.times=new ClientObject(name+"_ts");this.values=new ClientObject(name)},getValue:function(key){window.setTimeout(GravityRD.bind(this.clearOldValues,this),0);var d=+new Date();kd=this.times.getValue(key);if(this.timeout()===0||kd+this.timeout()>d){return this.values.getValue(key)}else{GravityRD.Log.debug("Removing key from "+this.cookieName+", because it expired: "+key+" (request)");this.values.removeValue(key);this.times.removeValue(key);return null}},setValue:function(key,value){window.setTimeout(GravityRD.bind(this.clearOldValues,this),0);this.values.setValue(key,value);this.times.setValue(key,+new Date())},clearOldValues:function(){var maxsize=this.maxSize();var d=+new Date()-this.timeout();var vall=this.values.getAllValues();var tall=this.times.getAllValues();var tlen=0;var kmin=null,karg=null;for(var k in tall){if(this.timeout()!==0&&tall[k]<d){GravityRD.Log.debug("Removing key from "+this.cookieName+", because it expired: "+k+" (thread)");delete tall[k];delete vall[k]}else{tlen++;if(kmin===null||tall[k]<kmin){kmin=tall[k];karg=k}}}if(tlen>maxsize&&karg!==null){GravityRD.Log.debug("Removing key from "+this.cookieName+", because it exceeds size limit: "+karg+" (thread)");delete tall[karg];delete vall[karg]}this.values.setAllValues(vall);this.times.setAllValues(tall)},getKeys:function(){var ret=[];for(var key in this.values.getAllValues()){ret.push(key)}return ret},timeout:function(){return 0},maxSize:function(){return 100}});var RecClickMapping=ExpiringClientObject.extend({timeout:function(){return(GravityRD.Core.getConfig()["recClickExpire"]||0)*1000},maxSize:function(){return GravityRD.Core.getConfig()["recClickTrackMax"]||20}});var Cart=ClientObject.extend({serializer:new JSONSerializer(),getItems:function(){return this.getAllValues()},addItem:function(itemId,quantity){var count=this.getValue(itemId)||0;if(quantity!==undefined){count+=quantity}else{count++}this.setValue(itemId,count)},removeItem:function(itemId,quantity){var count=this.getValue(itemId)||0;if(quantity!==undefined){count-=quantity}else{count--}if(count>0){this.setValue(itemId,count)}else{this.removeValue(itemId)}},removeItems:function(itemId){this.removeValue(itemId)}});var InMemoryObject=GravityRD.Base.extend({storage:{},getValue:function(key){return this.storage[key]},setValue:function(key,value){return this.storage[key]=value},getKeys:function(){var ret=[];for(var key in this.storage){ret.push(key)}return ret}});var RecIdMapping=GravityRD.Base.extend({local:new InMemoryObject(),registerRecId:function(itemId,recId){GravityRD.Log.debug("RegisterRecId for '"+itemId+"': '"+recId+"'");this.local.setValue(itemId,recId)},getRecId:function(itemId){var ret=this.local.getValue(itemId)||null;GravityRD.Log.debug("GetRecId for '"+itemId+"': '"+ret+"'");return ret}});var RandomSeed=ExpiringClientObject.extend({timeout:function(){return(GravityRD.Core.getConfig()["randomSeedExpire"]||10)*1000},maxSize:function(){return 1},getRandomSeed:function(){var rs=this.getValue("_");if(rs===null){rs=Math.floor(Math.random()*4294967296);this.setValue("_",rs)}return rs}});var GravityRD_Core_Cookie=GravityRD.Base.extend({__public__:["initSessionCookie","initPageCookie","getDebugCookie","setDebugCookie","getGeneratedCookie","setGeneratedCookie","registerRecId","getRecId","trackEvents","getTracking","getLastViewedItem","resolveCookieDomain","queueEvents","dequeueEvents","registerRecClickId","getRecClickId","getCookie","setCookie","retarget","randHexWord","getRandomSeed","addPersistentNameValue","getPersistentNameValues","addSessionNameValue","getSessionNameValues"],queueEventsTrack:new ClientObject("gr_track"),randomSeed:new RandomSeed("gr_rs"),initSessionCookie:function(){if(GravityRD.Core.getConfig()["trackSession"]===true){var cookieName="gr_session";var sid=GravityRD.Core.Cookie.getCookie(cookieName);if(sid===null){sid=(+new Date().getTime()).toString(16)+"-"+this.createRandomString();GravityRD.Core.Cookie.setCookie(cookieName,sid,false)}GravityRD.Core.setGlobalNameValue("sessionId",sid)}},initPageCookie:function(){if(GravityRD.Core.getConfig()["trackPage"]===true){var cookieName="gr_page";var sid=GravityRD.Core.Cookie.getCookie(cookieName);if(sid===null){sid=0}else{sid=sid*1+1}GravityRD.Core.Cookie.setCookie(cookieName,""+sid,false);GravityRD.Core.setGlobalNameValue("pageId",sid+"-"+this.randHexWord())}},getRandomSeed:function(){return this.randomSeed.getRandomSeed()},getDebugCookie:function(){var serializer=new JSONSerializer();var grdebug=this.getCookie("gr_debug");var json=serializer.decodeValue(grdebug)||{};return json},setDebugCookie:function(json){var serializer=new JSONSerializer();var enc=serializer.encodeValue(json);this.setCookie("gr_debug",enc)},queueEvents:function(x,key,overwrite){var k=key||"events";var queue=(!!overwrite)?[]:(this.queueEventsTrack.getValue(k)||[]);var nqueue=queue.concat(x);GravityRD.Log.debug("queueEvents ["+k+"]",nqueue);this.queueEventsTrack.setValue(k,nqueue)},dequeueEvents:function(key){var k=key||"events";var ret=this.queueEventsTrack.getValue(k);this.queueEventsTrack.setValue(k,[]);GravityRD.Log.debug("dequeueEvents ["+k+"]",ret);return ret},resolveCookieDomain:function(config,host){var cookieDomainVal=null;if(config.cookieDomain!==null){var cookieDomain=config.cookieDomain;var cookieDomainVal=null;var host=host.replace(/:\d+/,"");if(Object.prototype.toString.apply(cookieDomain)==="[object Array]"){for(var i=0;i<cookieDomain.length;i++){if(host.indexOf(cookieDomain[i])>-1){cookieDomainVal=cookieDomain[i];break}}if(cookieDomainVal===null){GravityRD.Log.error("Can't resolve cookiedomain for: "+host)}}else{if(typeof(cookieDomain)==="function"){cookieDomainVal=cookieDomain(host)}else{if(typeof(cookieDomain)==="string"){var m=cookieDomain.match(/level-(\d+)/);if(cookieDomain.match(/level-(\d+)/)!==null){var level=+m[1];var ld=host.split(".");var li=ld.length;while(--li>=0&&--level>=0){if(cookieDomainVal===null){cookieDomainVal=ld[li]}else{cookieDomainVal=ld[li]+"."+cookieDomainVal}}}else{if(cookieDomain.indexOf(".")>-1){cookieDomainVal=cookieDomain}else{GravityRD.Log.error("Unrecognized cookieDomain!")}}}}}}return cookieDomainVal},setCookie:function(name,value,expire){if(typeof(expire)==="undefined"){expire=+new Date()+1000*60*60*24*365}var config=GravityRD.Core.getConfig();var cookie=name+"="+escape(value)+(expire===false?"":";expires="+new Date(expire).toUTCString())+";path="+config.cookiePath+"";var cookieDomainVal=this.resolveCookieDomain(config,document.location.host);if(cookieDomainVal!==null){cookie+=";domain="+cookieDomainVal}GravityRD.Log.debug("setCookie: '"+cookie+"'");document.cookie=cookie},getCookie:function(name){var cookie=document.cookie;if(cookie.length>0){var start=cookie.indexOf(name+"=");if(start!==-1){start=start+name.length+1;var c_end=cookie.indexOf(";",start);if(c_end===-1){c_end=cookie.length}return unescape(cookie.substring(start,c_end))}}return null},getGeneratedCookie:function(val){var config=GravityRD.Core.getConfig();var name=config.cookieName;var cId=this.getCookie(name);if(config.useJsGeneratedCookie){var pattern=/[a-f0-9]{10,}-[a-f0-9]{16}/;if(cId!==null&&cId.match(pattern)===null){GravityRD.Core.Request.scriptTagRequest(GravityRD.Core.Request.getEndpoint(false,"JSServlet4"),"ec="+encodeURIComponent("INVALID CID")+"&ex="+encodeURIComponent(cId));cId=null}}if(cId===null){if(!GravityRD.isUndefined(val)){cId=val}else{var ts=+new Date().getTime();cId=ts.toString(16);cId+="-"+this.createRandomString()}GravityRD.Log.debug("Generating cookie ID [forced: "+(cId===val)+"]",cId);this.setCookie(name,cId)}return cId},setGeneratedCookie:function(val){var name=GravityRD.Core.getConfig()["cookieName"];var cId=this.getCookie(name);GravityRD.Log.debug("Generating cookie ID [forced: "+(cId===val)+"]",val);this.setCookie(name,val)},retarget:function(cId){var config=GravityRD.Core.getConfig();if(config.retargetingTrack===true&&config.retargeting===false){if(GravityRD.Core.Cookie.getCookie("gr_rt")!==cId){var ep=GravityRD.Core.Request.getEndpoint(true,"AdServlet");GravityRD.Core.Request.scriptTagRequest(ep,"action=setcookie&cid="+cId+"&customer="+config.partnerId);GravityRD.Core.Cookie.setCookie("gr_rt",cId,false)}}},lastViewedItem:null,recIdMapping:new RecIdMapping(),recClickMapping:new RecClickMapping("gr_click"),eventHistory:new ClientObject("gr_event"),cart:new Cart("gr_cart"),persistentNameValues:new ClientObject("gr_persist"),sessionNameValues:new ClientSessionObject("gr_ps"),trackEvents:function(rd){if(rd.eventType==="VIEW"){this.lastViewedItem=rd.itemId}else{if(rd.eventType==="ADD_TO_CART"){this.addToCartEvent(rd)}else{if(rd.eventType==="REMOVE_FROM_CART"){this.removeFromCartEvent(rd)}else{if(rd.eventType==="BUY"){this.buyEvent(rd)}}}}var config=GravityRD.Core.getConfig();if(config.trackEvents===true){var eventType=rd.eventType;var itemId=rd.itemId;var ta=(config.trackEventsFilter||{})[eventType];if(ta!==undefined){var pushObj=null;var extraFields=false;var extra={};var recId=null;if(ta.length>0){for(var i=0;i<ta.length;i++){if(rd[ta[i]]!==undefined){extra[ta[i]]=rd[ta[i]];extraFields=true}if(ta[i]==="recId"){recId=this.getRecId(itemId)}}}if(extraFields){pushObj=[eventType,itemId,recId,extra]}else{if(recId!==null){pushObj=[eventType,itemId,recId]}else{pushObj=[eventType,itemId]}}this.eventHistory.push(pushObj,config.trackEventsMaxSize)}}},getLastViewedItem:function(){return this.lastViewedItem},registerRecId:function(itemId,recId){this.recIdMapping.registerRecId(itemId,recId)},getRecId:function(itemId){return this.recIdMapping.getRecId(itemId)},registerRecClickId:function(itemId,recId){GravityRD.Log.debug("Registering recId '"+recId+"' for item '"+itemId+"'");this.recClickMapping.setValue(itemId,recId)},getRecClickId:function(itemId){return this.recClickMapping.getValue(itemId)},addToCartEvent:function(event){if(GravityRD.Core.getConfig()["trackCart"]===true){this.cart.addItem(event.itemId,event.quantity)}},removeFromCartEvent:function(event){if(GravityRD.Core.getConfig()["trackCart"]===true){this.cart.removeItem(event.itemId,event.quantity)}},buyEvent:function(event){if(GravityRD.Core.getConfig()["trackCart"]===true){this.cart.removeItems(event.itemId)}},getTracking:function(){return{cart:this.cart,eventHistory:this.eventHistory}},randHexWord:function(){return(((1+Math.random())*65536)|0).toString(16).substring(1)},createRandomString:function(){return(this.randHexWord()+this.randHexWord()+this.randHexWord()+this.randHexWord())},addPersistentNameValue:function(name,value){if(value==null){this.persistentNameValues.removeValue(name)}else{this.persistentNameValues.setValue(name,value)}},addSessionNameValue:function(name,value){if(value==null){this.sessionNameValues.removeValue(name)}else{this.sessionNameValues.setValue(name,value)}},getPersistentNameValues:function(){return this.persistentNameValues.getAllValues()},getSessionNameValues:function(){return this.sessionNameValues.getAllValues()}});GravityRD.register("GravityRD.Core","Cookie",new GravityRD_Core_Cookie())})();(function(){var shortNameDictionary=[{name:"BUY",value:"e1"},{name:"VIEW",value:"e2"},{name:"ADD_TO_CART",value:"e3"},{name:"REMOVE_FROM_CART",value:"e4"},{name:"ADD_TO_FAVORITES",value:"e5"},{name:"REMOVE_FROM_FAVORITES",value:"e6"},{name:"ADD_TO_WISHLIST",value:"e7"},{name:"REMOVE_FROM_WISHLIST",value:"e8"},{name:"RATING",value:"e9"},{name:"REC_CLICK",value:"e10"},{name:"ItemID",value:"nv1"},{name:"Position",value:"nv2"},{name:"UnitPrice",value:"nv3"},{name:"Quantity",value:"nv4"},{name:"OrderId",value:"nv5"},{name:"Value",value:"nv6"},{name:"MAIN_PAGE",value:"si1"},{name:"CATEGORY_PAGE",value:"si2"},{name:"LISTING_PAGE",value:"si3"},{name:"ITEM_PAGE",value:"si4"},{name:"CART_PAGE",value:"si5"}];var GravityRD_Core_Request=GravityRD.Base.extend({__public__:["createRequest","setupRouting","scriptTagRequest","getEndpoint","useResultCB","_T","_U"],routes:[],routeTargets:{},nr:0,setupRouting:function(routes){var that=this;GravityRD.each(routes,function(routeConfig){var rc=GravityRD.apply(routeConfig,{predicate:function(){return true},disableDefaultTarget:false,additionalTargets:[]},false);var at=[];for(var i=0;i<rc.additionalTargets.length;i++){var cur=rc.additionalTargets[i];if(GravityRD.isString(cur)){var ncur={partner:cur};cur=ncur}if(cur.partner===null){GravityRD.Log.error("Partner not set in additionalTargets (skipping configuration): ",routeConfig);continue}that.routeTargets[cur.partner]={eventRequests:[]};at.push(GravityRD.apply(cur,{process:function(event){return event}},false))}rc.additionalTargets=at;that.routes.push(rc)});if(GravityRD.Core.debug("routing")){GravityRD.Log.group("Routing info");for(var i=0;i<this.routes.length;i++){GravityRD.Log.debug("R"+i,this.routes[i])}GravityRD.Log.debug("Route targets",this.routeTargets);GravityRD.Log.groupEnd()}},getShortNameValue:function(key){var develop=GravityRD.Core.getConfig()["mode"]==="DEVELOP";var ret="";if(key!==null&&key!==""){var exist=false;var i=0;while(!exist&&i<shortNameDictionary.length){exist=(key===shortNameDictionary[i].name);i++}if(exist&&!develop){ret="."+shortNameDictionary[i-1].value}else{ret="*"+key}}return ret},_T:function(string){if(string===null||string===undefined){return null}string=string.toString().replace(/-/g,"-0").replace(/,/g,"-1").replace(/;/g,"-2").replace(/\[/g,"-3").replace(/\]/g,"-4").replace(/:/g,"-5").replace(/\|/g,"-6");return this._E(string)},_U:function(string){if(string===null||string==undefined){return null}string=decodeURIComponent(string);string=string.toString().replace(/-6/g,"|").replace(/-5/g,":").replace(/-4/g,"]").replace(/-3/g,"[").replace(/-2/g,";").replace(/-1/g,",").replace(/-0/g,"-");return string},_E:function(string){return encodeURIComponent(string)},_TA:function(arr){var resultNamesEnc=[];for(var i=0;i<(arr||[]).length;i++){resultNamesEnc.push(this._T(arr[i]))}return resultNamesEnc.join(";")},getEndpoint:function(serverNameOrRetargeting,servletName,customerName){var config=GravityRD.Core.getConfig();var serverName=serverNameOrRetargeting;if(!GravityRD.isString(serverNameOrRetargeting)){if(serverNameOrRetargeting){var rs=config.retargetingServer;var rsa=rs.split(".");if(rsa[0]==config.partnerId&&!!customerName){rsa[0]=customerName;serverName=rsa.join(".")}else{serverName=rs}}else{serverName=config.targetServer}}var proto=document.location.protocol;if(proto==="file:"){proto="http:"}if(!!config.forceProtocol){proto=config.forceProtocol+":"}return proto+"//"+serverName+"/grrec-"+(customerName||config.partnerId)+"-war/"+servletName},useResultCB:function(result){var rn=result.requestNumber;var rri=[];var eri=[];if(result&&result.recommendationWrappers){for(i=0;i<result.recommendationWrappers.length;i++){rri.push(result.recommendationWrappers[i].recommendationIndex)}}if(result&&result.explanationWrappers){for(var i=0;i<result.explanationWrappers.length;i++){eri.push(result.explanationWrappers[i].explanationIndex)}}var cb=window.GravityRD["callback"+rn+"__"+rri.join("_")+"__"+eri.join("_")];if(cb){cb(result)}},scriptTagRequest:function(endpoint,params,rn,rri,eri){var that=this;var script=document.createElement("script");script.type="text/javascript";script.id="x_"+(that.nr++);function isIE(){var myNav=navigator.userAgent.toLowerCase();return(myNav.indexOf("msie")!=-1)?parseInt(myNav.split("msie")[1]):false}(function(){var lastValue;var done=0;var cleanUp=function(i){script.onreadystatechange=script.onload=script.onerror=null;(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).removeChild(script)};if(rri!=null&&eri!=null){window.GravityRD["callback"+rn+"__"+rri.join("_")+"__"+eri.join("_")]=function(result){lastValue=result};var notifySuccess=function(json){if(!(done++)){cleanUp()}};var notifyError=function(type){if(!(done++)){cleanUp();GravityRD.Core.errorCB(rn,rri,eri)}};if(isIE()&&isIE()<10){script.htmlFor=script.id;script.event="onclick"}script.onload=script.onerror=function(result){if(!script.readyState||!/i/.test(script.readyState)){try{script.onclick&&script.onclick()}catch(_){}result=lastValue;lastValue=0;result?notifySuccess(result[0]):notifyError("error")}}}script.src=endpoint+"?"+params;(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(script)})()},addNameValue:function(nameValues,n,v){var wrongAttributes=GravityRD.Core.getConfig()["wrongNameValues"]||[];for(var i=0;i<wrongAttributes.length;i++){if(wrongAttributes[i]===n){GravityRD.Log.usageError("GR-022",n)}}if(Object.prototype.toString.apply(v)==="[object Array]"){if(v.length>0){var s="";for(var i=0;i<v.length;i++){s+=(s==""?"":"|")+this._T(v[i])}nameValues.push(this._T(this.getShortNameValue(n))+":"+s)}}else{nameValues.push(this._T(this.getShortNameValue(n))+":"+this._T(v))}},serializeEvent:function(event){var eventDec=[];eventDec.push(this._T(this.getShortNameValue(event.eventType)));eventDec.push(this._T(event.itemId));var nameValues=[];for(var k in event){if(typeof(event[k])==="function"){continue}var kl=String(k).toLowerCase();if(kl.indexOf("__")===0){continue}if("type"===kl||"eventtype"===kl||"itemid"===kl){continue}if(event[k]!==undefined){this.addNameValue(nameValues,k,event[k])}}if(nameValues.length!==0){eventDec.push("["+nameValues.join(";")+"]")}var eventSer=eventDec.join(",");return eventSer},createGlobalData:function(addCookie,addUser,dontSetCookie){if(GravityRD.isUndefined(addCookie)){addCookie=true}if(GravityRD.isUndefined(addUser)){addUser=true}if(GravityRD.isUndefined(dontSetCookie)){dontSetCookie=false}var globalRecoData=[];var config=GravityRD.Core.getConfig();globalRecoData.push({name:"rn",value:GravityRD.Core.getRequestNumber()});if(config.userId!==null&&addUser){globalRecoData.push({name:"uid",value:this._E(config.userId)})}var cookieval=null;if(!config.retargeting&&addCookie){cookieval=config.cookieId;if(config.useJsGeneratedCookie){cookieval=GravityRD.Core.Cookie.getGeneratedCookie()}GravityRD.Core.Cookie.retarget(cookieval)}if(cookieval!==null){globalRecoData.push({name:"cid",value:this._E(cookieval)})}globalRecoData.push({name:"v",value:GravityRD.Core.getConfig()["buildSHA"]});if(dontSetCookie){globalRecoData.push({name:"dsc",value:"true"})}globalRecoData.push({name:"ts",value:(+new Date()/1000|0)});return globalRecoData},createRequest:function(config,params){if(config.partnerId===null){GravityRD.Log.usageError("GR-016");return}if(config.retargeting===false){if(config.cookieId===null&&config.useJsGeneratedCookie===false){GravityRD.Log.usageError("GR-017")}if(config.cookieId!==null&&config.useJsGeneratedCookie===true){GravityRD.Log.usageError("GR-018")}}for(var i=0;i<params.recommendationRequests.length;i++){params.recommendationRequests[i].__stag_time=+new Date()}params.__perf=GravityRD.Perf.create();var globalRecoData=this.createGlobalData();var eventRequests=[];var recommendationRequests=[];var explanationRequests=[];var routedebug=GravityRD.Core.debug("routing");routedebug&&GravityRD.Log.group("Route matching");if(params.events.length>0){for(var i=0;i<params.events.length;i++){var event=GravityRD.apply({},params.events[i]);if(routedebug){GravityRD.Log.group("Event "+event.eventType);GravityRD.Log.debug("Trying to match event",event)}var matched=false;var route=null;for(var j=0;j<this.routes.length&&!matched;j++){route=this.routes[j];matched=!!(new RegExp(route.eventType)).exec(event.eventType)&&route.predicate(event);if(matched){routedebug&&GravityRD.Log.debug("[+] Route matched",route);if(!route.disableDefaultTarget){eventRequests.push(this.serializeEvent(event))}for(var k=0;k<route.additionalTargets.length;k++){var at=route.additionalTargets[k];var pev=at.process(event);if(pev!==null){this.routeTargets[at.partner].eventRequests.push(this.serializeEvent(pev))}}break}else{routedebug&&GravityRD.Log.debug("[-] Route not matched",route)}}if(!matched){eventRequests.push(this.serializeEvent(event))}routedebug&&GravityRD.Log.groupEnd()}}routedebug&&GravityRD.Log.groupEnd();var remaining=[];if(params.recommendationRequests.length>0){for(var i=0;i<params.recommendationRequests.length;i++){var rr=params.recommendationRequests[i];if(rr.groupId!==undefined){if(rr.__completed!==true){remaining.push(rr);continue}else{if(rr.groupSeq===1){var ss=this.serializeRecRequest(rr);for(var last=rr;last.__next!==undefined;last=last.__next){ss+=this.serializeRecRequest(last.__next)}recommendationRequests.push(ss)}}}else{recommendationRequests.push(this.serializeRecRequest(rr))}}}if(params.explanationRequests.length>0){for(var i=0;i<params.explanationRequests.length;i++){var rr=params.explanationRequests[i];var rrDec=[];rrDec.push(rr.explanationIndex);rrDec.push(this._T(rr.scenarioId));rrDec.push(this._T(rr.numberLimit));rrDec.push(this._T(rr.recommendationId));rrDec.push("["+this._TA(rr.resultNames)+"]");rrDec.push("["+this._TA(rr.recommendedItemIds)+"]");var nameValues=[];for(var k in rr){if(typeof(rr[k])==="function"){continue}var kl=String(k).toLowerCase();if(kl.indexOf("__")===0){continue}if("explanationindex"===kl||"type"===kl||"scenarioid"===kl||"numberlimit"===kl||"templating"===kl||"resultnames"===kl||"callback"===kl||"recommendeditemids"===kl||"recommendationid"===kl){continue}this.addNameValue(nameValues,k,rr[k])}rrDec.push((nameValues.length>0)?"["+nameValues.join(";")+"]":"");explanationRequests.push(rrDec.join(","))}}params.__perf.phase("preprocess");GravityRD.Core.saveParams(remaining);var ep=GravityRD.Core.Request.getEndpoint(config.retargeting,"JSServlet4");this.createScriptTagRequests(ep,globalRecoData,eventRequests,recommendationRequests,explanationRequests,params.__perf);var config=GravityRD.Core.getConfig();for(var customer in this.routeTargets){var useUser=(config.routingGlobal[customer]||{}).useUser||config.routingGlobal.useUser||false;var globalData=this.createGlobalData(false,useUser,true);var routeTarget=this.routeTargets[customer];if(routeTarget.eventRequests.length>0){var ep=GravityRD.Core.Request.getEndpoint(true,"JSServlet4",customer);this.createScriptTagRequests(ep,globalData,routeTarget.eventRequests,[],[],params.__perf)}}},serializeRecRequest:function(rr){var rrDec=[];rrDec.push(rr.recommendationIndex);rrDec.push(this._T(rr.scenarioId));if(rr.templating&&rr.templating.serverSide){rrDec.push(rr.templating.templateId)}rrDec.push(this._T(rr.numberLimit||0));var nameValues=[];for(var k in rr){var kl=String(k).toLowerCase();if(kl.indexOf("__")===0){continue}if(typeof(rr[k])==="function"){continue}if("recommendationindex"===kl||"type"===kl||"scenarioid"===kl||"numberlimit"===kl||"templating"===kl||"resultnames"===kl||"callback"===kl){continue}this.addNameValue(nameValues,k,rr[k])}rrDec.push((nameValues.length>0)?"["+nameValues.join(";")+"]":"");rrDec.push("["+this._TA(rr.resultNames)+"]");var serialized=rrDec.join(",");if(rr.templating&&rr.templating.serverSide){serialized="&rs="+rrDec.join(",")}else{serialized="&rd="+rrDec.join(",")}return serialized},serializeCart:function(){var cart=GravityRD.Core.Cookie.getTracking()["cart"].get()||{};var cartS="";var cartItemIds=[];var empty=true;for(var i in cart){if(cart[i]!==null){empty=false;cartItemIds.push(i)}}if(!empty){var nameValues=[];this.addNameValue(nameValues,"CartItemId",cartItemIds);cartS=(nameValues.length>0)?"["+nameValues.join(";")+"]":""}return cartS},serializeEventHistory:function(maxsize){var eventHistory=GravityRD.Core.Cookie.getTracking()["eventHistory"].get()||[];var eventHistoryS="";for(var i=eventHistory.length-1;i>0;i--){var eventDesc=eventHistory[i];var event={type:"event",eventType:eventDesc[0],itemId:eventDesc[1]};if(eventDesc[2]!==undefined&&eventDesc[2]!==null){event.recId=eventDesc[2]}if(eventDesc[3]!==undefined){GravityRD.apply(event,eventDesc[3])}if(maxsize>0&&(eventHistoryS.length+1+this.serializeEvent(event).length)>maxsize){break}eventHistoryS=this.serializeEvent(event)+(eventHistoryS==""?"":"|")+eventHistoryS}return eventHistoryS},createScriptTagRequests:function(endpoint,globalRecoData,eventRequests,recommendationRequests,explanationRequests,perf){var queryLimit=2048-5-11;var gparms=[];for(var i=0;i<globalRecoData.length;i++){gparms.push(globalRecoData[i].name+"="+globalRecoData[i].value)}var baseUrl=gparms.join("&");var maxrun=recommendationRequests.length+eventRequests.length+explanationRequests.length;while(recommendationRequests.length!==0||eventRequests.length!==0||explanationRequests.length!==0){if(maxrun--<0){GravityRD.Log.error("Possible infinite loop");break}var src=baseUrl;var hadEvent=false;var hadRecommendation=false;if(eventRequests.length>0){hadEvent=true;if((eventRequests[0].length+3)>(queryLimit-src.length)){src+="&e="+eventRequests[0];eventRequests=eventRequests.slice(1);src+="&tr=1";GravityRD.Log.error("Query limit is too small to push event request");this.loadScripts(endpoint,src,null,null,perf);continue}else{while(eventRequests.length>0&&(eventRequests[0].length+3)<(queryLimit-src.length)){src+="&e="+eventRequests[0];eventRequests=eventRequests.slice(1)}}}var rri=[];var eri=[];if(recommendationRequests.length>0){var cartS=this.serializeCart();var histS=this.serializeEventHistory(0);if((recommendationRequests[0].length+4+cartS.length+5+histS.length+4)>=(queryLimit-src.length)){if(hadEvent){GravityRD.Log.debug("Pushing events");this.loadScripts(endpoint,src,null,null,perf);continue}var rrs=recommendationRequests[0];src+=rrs;rri.push(rrs.split(",")[0].split("=")[1]);src+="&grd="+cartS;var remaining=queryLimit-src.length-4;if(remaining>0){GravityRD.Log.debug("Remaining: "+remaining);src+="&eh="+this.serializeEventHistory(remaining)}src+="&tr=2";recommendationRequests=recommendationRequests.slice(1);GravityRD.Log.error("Query limit is too small to push recommendation request");this.loadScripts(endpoint,src,rri,eri,perf);rri=[];eri=[];continue}else{src+="&grd="+cartS;src+="&eh="+this.serializeEventHistory(0);while(recommendationRequests.length>0&&(recommendationRequests[0].length+4)<(queryLimit-src.length)){var rrs=recommendationRequests[0];src+=rrs;rri.push(rrs.split(",")[0].split("=")[1]);recommendationRequests=recommendationRequests.slice(1)}}}if(explanationRequests.length>0){if((explanationRequests[0].length+4)>=(queryLimit-src.length)){if(hadEvent||hadRecommendation){GravityRD.Log.debug("Pushing events");this.loadScripts(endpoint,src,rri,eri,perf);rri=[];eri=[];continue}var ers=explanationRequests[0];eri.push(ers.split(",")[0]);src+="&xp="+ers;var remaining=queryLimit-src.length-4;src+="&tr=3";explanationRequests=explanationRequests.slice(1);GravityRD.Log.error("Query limit is too small to push recommendation request");this.loadScripts(endpoint,src,rri,eri,perf);rri=[];eri=[];continue}else{while(explanationRequests.length>0&&(explanationRequests[0].length+4)<(queryLimit-src.length)){var ers=explanationRequests[0];eri.push(ers.split(",")[0]);src+="&xp="+ers;explanationRequests=explanationRequests.slice(1)}}}this.loadScripts(endpoint,src,rri,eri,perf)}},loadScripts:function(endpoint,url,rri,eri,perf){GravityRD.Log.timeStamp("GR:LOAD("+(GravityRD.Core.getRequestNumber()-1)+")");perf.phase("loadscripts");GravityRD.Log.group("LoadScripts "+endpoint,true);url.replace(/([^&]+)&?/g,function(_,p){GravityRD.Log.debug(p)});GravityRD.Core.Request.scriptTagRequest(endpoint,url+"&r="+GravityRD.Core.Cookie.randHexWord()+GravityRD.Core.Cookie.randHexWord(),GravityRD.Core.getRequestNumber()-1,rri,eri);GravityRD.Log.groupEnd();perf.phase("loadscriptsend")}});GravityRD.register("GravityRD.Core","Request",new GravityRD_Core_Request())})();(function(){var ErrorMessages={"GR-001":"Attribute '#1#' should have '#2#' type","GR-002":"Dom element with id '#1#' not found","GR-003":"Attribute '#1#' shouldn't be null","GR-004":"Parameter [#1#] of #2# should not be undefined","GR-005":"Parameter [#1#] of #2# should not be null","GR-006":"Parameter [#1#] of #2# should have '#3#' type","GR-007":"Invalid push item specified: '#1#'. Parameters to push() should have object type","GR-008":"Invalid type attribute in push item specified: '#1#'. Possible candidates: [#2#]","GR-009":"Invalid eventType attribute in push item specified: '#1#'. Possible candidates: [#2#]","GR-010":"Missing mandatory parameter: '#1#'. Push object: '#2#'","GR-011":"Invalid attribute in push item specified: '#1#'. Possible candidates: [#2#]","GR-012":"Either 'templating' or 'callback' attribute should be specified in recommendation push object","GR-013":"Both template and templateElementId specified","GR-014":"Neither template nor templateElementId specified","GR-015":"Initializing of templates failed","GR-016":"Please configure the 'partnerId'","GR-017":"CookieId is null, and autogeneration of cookies is disabled","GR-018":"CookieId is not null, and autogeneration of cookies is enabled","GR-019":"You don't have enough privileges to access this function","GR-020":"Array parameter [#1#] should have at least one element.","GR-021":"The value [#1#] for attribute '#2#' is suspicious. If you are sure it is valid, please contact us, to disable this feature!","GR-022":"Invalid push attribute [#1#] specified. Maybe you should try: {type:'set', #1#: [...]}","GR-023":"No 'groupSeq' attribute defined for group [#1#]","GR-024":"No 'groupSize' attribute defined for group [#1#]","GR-025":"Invalid 'groupSequence' attribute specified for group [#1#]. Got: #2#, expected: [#3#]}","GR-026":"Invalid 'groupSize' attribute specified for group [#1#], groupSize: [#2#]","GR-027":"Invalid 'groupSize' attribute specified for group [#1#], groupSize: [#2#], expected: [#3#]","GR-028":"Exception thrown by template rendering: '#1#'","GR-029":"Loading the javascript framework from this domain is not allowed","GR-030":"Server side and client side template rendering is not allowed on the same recommendation. (Use template or templateId, but not both)."};var GravityRD_Log_Logback=GravityRD.Base.extend({__public__:["debug","error","info","usageError","validationError","flush","message"],message:function(msg,obj){var res=msg+" ";if(obj!==undefined){res+=obj}res+="\n";return res},debug:function(msg,obj){this.log+=GravityRD.message(msg,obj)},info:function(msg,obj){this.log+=GravityRD.message(msg,obj)},error:function(msg,obj){this.log+=GravityRD.message("ERROR: "+msg,obj)},usageError:function(msg,obj){this.log+=GravityRD.message("USAGEERROR: "+msg,obj)},validationError:function(msg,obj){this.log+=GravityRD.message("VALIDATIONERROR: "+msg,obj)},flush:function(){var ss=1600;for(var p=0;p+ss<this.log.length;p+=ss){var config=GravityRD.Core.getConfig();var ep=GravityRD.Core.Request.getEndpoint(config.retargeting,"JSServlet4");GravityRD.Core.Request.scriptTagRequest(ep,"ex=CUSTOM&ec="+encodeURIComponent(this.log.slice(p,p+ss)))}this.log=""}});var GravityRD_Log_Firebug=GravityRD.Base.extend({__public__:["debug","error","info","group","groupEnd","timeStamp","time","timeEnd","usageError","validationError"],prefixes:[],haveConsole:function(){return(typeof(console)!=="undefined")},haveGroup:function(){return this.haveConsole()&&GravityRD.isFunction(console.group)&&GravityRD.isFunction(console.groupCollapsed)&&GravityRD.isFunction(console.groupEnd)&&GravityRD.Core.getConfig()["mode"]==="DEVELOP"},debug:function(msg,obj){if(this.haveConsole()){if(GravityRD.Core.getConfig()["mode"]==="DEVELOP"){if(obj!==undefined){console.log(this.prefix()+msg,obj)}else{console.log(this.prefix()+msg)}}}},group:function(groupName,collapsed){if(this.haveGroup()){if(collapsed===true){console.groupCollapsed(groupName)}else{console.group(groupName)}}else{this.prefixes.push(groupName)}},prefix:function(){if(!this.haveGroup()){return this.prefixes.join("::")+"::"}else{return""}},groupEnd:function(){if(this.haveGroup()){console.groupEnd()}else{this.prefixes.pop()}},info:function(msg,obj){if(this.haveConsole()){if(obj!==undefined){console.info(this.prefix()+msg,obj)}else{console.info(this.prefix()+msg)}}},error:function(msg,obj){if(this.haveConsole()){if(obj!==undefined){console.error(this.prefix()+msg,obj)}else{console.error(this.prefix()+msg)}}},timeStamp:function(str){if(GravityRD.Core.debug("perf")&&this.haveConsole()&&GravityRD.isFunction(console.timeStamp)){console.timeStamp(str)}},time:function(str){if(GravityRD.Core.debug("perf")&&this.haveConsole()&&GravityRD.isFunction(console.time)){console.time(str)}},timeEnd:function(str){if(GravityRD.Core.debug("perf")&&this.haveConsole()&&GravityRD.isFunction(console.timeEnd)){console.timeEnd(str)}},usageError:function(msg){var error=msg;if(msg.indexOf("GR-")===0&&ErrorMessages[msg]!==undefined){error=msg+":"+ErrorMessages[msg];for(var i=1;i<arguments.length;i++){error=error.replace(new RegExp("#"+i+"#","img"),arguments[i])}}else{this.error("Invalid error message specified")}if(this.haveConsole()){console.error(error)}var config=GravityRD.Core.getConfig();if(config.logExceptions===true){var ep=GravityRD.Core.Request.getEndpoint(config.retargeting,"JSServlet4");GravityRD.Core.Request.scriptTagRequest(ep,"ex="+encodeURIComponent(error)+"&ec="+encodeURIComponent(msg))}GravityRD.Core.onUsageError(error+" @"+window.location.href);if(!(msg==="GR-021")){throw new GravityRD.Exc(GravityRD.Exc.APIUSAGE,error)}},validationError:function(errors){if(this.haveConsole()){for(var i=0;i<errors.length;i++){GravityRD.Log.error("Error received from server, code="+errors[i].code+", message="+errors[i].msg)}}throw new GravityRD.Exc(GravityRD.Exc.VALIDATION,errors[0].code+":"+errors[0].msg)}});GravityRD.register("GravityRD","Log",new GravityRD_Log_Firebug())})();(function(){var AbstractTypechecker=GravityRD.Base.extend({});var ArgumentTypechecker=AbstractTypechecker.extend({constructor:function(name,args){this.name=name;this.args=args},validArg:function(pos){return(this.args.length>pos)},notNull:function(pos){if(!this.validArg(pos)||GravityRD.isNull(this.args[pos])){GravityRD.Log.usageError("GR-005",(pos+1),this.name)}return this},notUndefined:function(pos){if(!this.validArg(pos)||GravityRD.isUndefined(this.args[pos])){GravityRD.Log.usageError("GR-004",(pos+1),this.name)}return this},isObject:function(pos){if(!this.validArg(pos)||!GravityRD.isObject(this.args[pos])){GravityRD.Log.usageError("GR-006",(pos+1),this.name,"object")}return this}});var GlobalTypeDescription={set:{strict:false,optional:{partnerId:{type:"string"},userId:{type:"string",nullString:true,allowNull:true},cookieName:{type:"string",nullString:true},cookieId:{type:"string",nullString:true},useJsGeneratedCookie:{type:"boolean"}}},"register-recid":{strict:true,mandatory:{itemId:{type:"string",array:true,nullString:true},recId:{type:"string"}}},event:true,domready:{mandatory:{apply:{type:"function"}}},customconfig:{mandatory:{config:{type:"object"}}},fakeexception:{},recommendation:{mandatory:{scenarioId:{type:"string"}},optional:{numberLimit:{type:"integer"},resultNames:{type:"string",array:true},callback:{type:"function"},groupId:{type:"string"},groupSeq:{type:"integer"},groupSize:{type:"integer"},templating:{type:"object",descriptor:{mandatory:{targetElementId:{type:"dom"}},optional:{templateElementId:{type:"dom"},template:{type:"string"},templateData:{type:"object"},targetElementId:{type:"dom"},modifiers:{type:"object"}}}}}},explanation:{mandatory:{scenarioId:{type:"string"},numberLimit:{type:"integer"},recommendedItemIds:{type:"string",array:true},recommendationId:{type:"string"}},optional:{resultNames:{type:"string",array:true},callback:{type:"function"},templating:{type:"object",descriptor:{mandatory:{targetElementId:{type:"dom"}},optional:{templateElementId:{type:"dom"},template:{type:"string"},templateData:{type:"object"},targetElementId:{type:"dom"},modifiers:{type:"object"}}}}}},search:{mandatory:{count:{type:"integer"},inputSelector:{type:"string"},name:{type:"string"}},optional:{}}};var defEvDesc={mandatory:{eventType:{type:"string"},itemId:{type:"string",nullString:true}}};var emptyEvDesc={mandatory:{eventType:{type:"string"}}};var EventTypeDescription={FEEDBACK:defEvDesc,BUY:defEvDesc,MARK_BY_STAR:defEvDesc,MARK_FOR_LATER_WATCHING:defEvDesc,ADD_TO_FAVORITES:defEvDesc,USER_RECOMMEND:defEvDesc,RATING:defEvDesc,LANCE:defEvDesc,VIEW:defEvDesc,ADD_TO_CART:defEvDesc,REC_CLICK:defEvDesc,HIDE:defEvDesc,FREE_VIEW:defEvDesc,PAID_VIEW:defEvDesc,PRODUCT_SEARCH:emptyEvDesc,LETTER_SEND:emptyEvDesc,TEST_FILL:emptyEvDesc,LOGIN:emptyEvDesc,SHOW_ITEM:emptyEvDesc,SMS_SEND:emptyEvDesc,SUBSCRIBE:emptyEvDesc,LETTER_READ:emptyEvDesc,WATCH_LIVE:defEvDesc,WATCH_RECORDED:defEvDesc,WATCH_VOD_TRAILER:defEvDesc,WATCH_VOD:defEvDesc,RECORD:defEvDesc,REMOVE_FROM_FAVORITES:defEvDesc,SHOW_RECOMMENDATION:emptyEvDesc,NEXT_RECOMMENDATION:emptyEvDesc,ADD_TO_WISHLIST:defEvDesc,REMOVE_FROM_WISHLIST:defEvDesc,REMOVE_FROM_CART:defEvDesc,CLICK_OUT:defEvDesc,UNHIDE:defEvDesc,SHARE:defEvDesc,ASK_QUESTION:emptyEvDesc,COMMENT:defEvDesc,ADD_ITEM:defEvDesc,ADD_FRIEND:emptyEvDesc,DELETE_ITEM:defEvDesc,SUBSCRIPTION_VIEW:defEvDesc,FOLLOW_USER:emptyEvDesc,NOT_INTERESTED:defEvDesc,SMS_RECEIVE:emptyEvDesc,REDEEM:defEvDesc,BROWSE:emptyEvDesc,PREMIUM_VIEW:defEvDesc,CHAT:emptyEvDesc,LIKE:defEvDesc,DISLIKE:defEvDesc,BUY_INIT:emptyEvDesc,LEAVE_PAGE:emptyEvDesc,COMPARE:emptyEvDesc,LETTER_CLICK:emptyEvDesc,SMS_START:emptyEvDesc,GIFT_CLICK:emptyEvDesc,GIFT_SEND:emptyEvDesc,UNSUBSCRIBE:emptyEvDesc,MODIFY_ITEM:defEvDesc,QUANTITY_CHECK:defEvDesc,CLICK:defEvDesc,TRACK:emptyEvDesc,RETURN:defEvDesc,PHONE_CLICK:defEvDesc,ADD_TO_PLAYLIST:defEvDesc,PRINT_CLICK:defEvDesc,LINK_MODULE_CLICK:defEvDesc,GALLERY_CLICK:defEvDesc,SEARCH:emptyEvDesc,REMOVE_FROM_PLAYLIST:emptyEvDesc,WATCHED:emptyEvDesc,UNFOLLOW_USER:emptyEvDesc,BID:defEvDesc,IMPRESSION:defEvDesc,DOWNLOAD:defEvDesc,EMAIL_ALERT:emptyEvDesc,ADD_TO_WATCH_LIST:defEvDesc,USER_REGISTRATION:emptyEvDesc,POST_ITEM:emptyEvDesc,ITEM_ON_SCREEN:defEvDesc,REC_ON_SCREEN:emptyEvDesc,AGGREGATOR:emptyEvDesc,ACTION_TRIGGERED:emptyEvDesc,INTERNAL_A:emptyEvDesc,INTERNAL_B:emptyEvDesc,INTERNAL_C:emptyEvDesc,INTERNAL_D:emptyEvDesc,ERROR:emptyEvDesc,APPLY:defEvDesc,WATCH_LIVE_OTT:defEvDesc,WATCH:defEvDesc,BUY_CATCHUP:defEvDesc,WATCH_CATCHUP:defEvDesc,WATCH_VOD_OTT:defEvDesc,SUBSCRIPTION_VIEW_OTT:defEvDesc,BUY_ANONYM:defEvDesc,WATCH_VOD_ANONYM:defEvDesc,SUBSCRIPTION_VIEW_ANONYM:defEvDesc,WATCH_CATCHUP_ANONYM:defEvDesc,ADD_TO_BOOKMARK:defEvDesc};var NullStringChecker=AbstractTypechecker.extend({constructor:function(name){var config=GravityRD.Core.getConfig();this.name=name;this.nullStrings=config.nullStrings},checkNullString:function(val){for(var i=0;i<this.nullStrings.length;i++){if(this.nullStrings[i]===val){GravityRD.Log.usageError("GR-021",val,this.name)}}}});var PushObjectTypeChecker=AbstractTypechecker.extend({obj:null,constructor:function(obj){this.obj=obj},validate:function(){if(!GravityRD.isObject(this.obj)){GravityRD.Log.usageError("GR-007",this.obj)}var type=this.obj.type,k,candidates;if(GravityRD.isString(type)!==true||GlobalTypeDescription[type]===undefined){candidates="";for(k in GlobalTypeDescription){if(!GlobalTypeDescription.hasOwnProperty(k)){continue}candidates+=((candidates==="")?k:(","+k))}GravityRD.Log.usageError("GR-008",type,candidates)}var descriptor;if("event"==type){var subType=this.obj.eventType;if(GravityRD.isString(subType)!==true||EventTypeDescription[subType]===undefined){candidates="";for(k in EventTypeDescription){if(!EventTypeDescription.hasOwnProperty(k)){continue}candidates+=((candidates==="")?k:(","+k))}GravityRD.Log.usageError("GR-008",subType,candidates)}descriptor=EventTypeDescription[subType]}else{descriptor=GlobalTypeDescription[type]}this.validateAttributes(this.obj,descriptor)},validateAttributes:function(obj,descriptor){if(GravityRD.isUndefined(descriptor)){return}var mandatory=descriptor.mandatory||{};var optional=descriptor.optional||{};var candidates="",k;for(k in mandatory){if(!mandatory.hasOwnProperty(k)){continue}candidates+=((candidates==="")?k:(","+k))}for(k in optional){if(!optional.hasOwnProperty(k)){continue}candidates+=((candidates==="")?k:(","+k))}for(k in mandatory){if(!mandatory.hasOwnProperty(k)){continue}if(obj[k]===undefined){GravityRD.Log.usageError("GR-010",k,obj)}}for(k in obj){if(!obj.hasOwnProperty(k)){continue}if(k==="type"){continue}if(mandatory[k]!==undefined){this.validateAttribute(k,obj,mandatory[k],true)}else{if(optional[k]!==undefined){this.validateAttribute(k,obj,optional[k],false)}else{if(descriptor.strict===true){GravityRD.Log.usageError("GR-011",k,candidates)}}}}},validateAttribute:function(attrname,attrs,descriptor){var attrvalue=attrs[attrname];if(GravityRD.isNull(attrvalue)){if(descriptor.allowNull===true){return}else{GravityRD.Log.usageError("GR-003",attrname)}}if(descriptor.array===true){if(!GravityRD.isArray(attrvalue)){var val=[];val.push(attrvalue);attrs[attrname]=val;attrvalue=val}if(attrvalue.length==0){GravityRD.Log.usageError("GR-020",attrname)}else{attrvalue=attrvalue[0]}}if(descriptor.type!==undefined){var type=descriptor.type;if(type==="string"){if(!GravityRD.isString(attrvalue)){GravityRD.Log.usageError("GR-001",attrname,type)}else{if(descriptor.nullString===true){new NullStringChecker(attrname).checkNullString(attrvalue)}}}else{if(type==="integer"){if(typeof(attrvalue)!=="number"){GravityRD.Log.usageError("GR-001",attrname,type)}}else{if(type==="boolean"){if(typeof(attrvalue)!=="boolean"){GravityRD.Log.usageError("GR-001",attrname,type)}}else{if(type==="dom"){var element=document.getElementById(attrvalue);if(element===null){GravityRD.Log.usageError("GR-002",attrvalue)}}else{if(type==="object"){if(!GravityRD.isObject(attrvalue)){GravityRD.Log.usageError("GR-001",attrname,type)}this.validateAttributes(attrvalue,descriptor.descriptor)}else{if(type==="function"){if(!GravityRD.isFunction(attrvalue)){GravityRD.Log.usageError("GR-001",attrname,type)}}else{GravityRD.Log.error("Invalid type specified in the field descriptor: "+descriptor.type)}}}}}}}}});var GravityRD_Typecheck=GravityRD.Base.extend({__public__:["argumentChecker","pushObjectChecker","nullStringChecker"],argumentChecker:function(name,args){return new ArgumentTypechecker(name,args)},pushObjectChecker:function(o){return new PushObjectTypeChecker(o)},nullStringChecker:function(name){return new NullStringChecker(name)}});GravityRD.register("GravityRD","Typecheck",new GravityRD_Typecheck())})();(function(){var GravityRD_Worker_PushProcessor=GravityRD.extend(Object,{handle:null,equeue:[],queue:[],lastHash:-1,push:function(parm,sync){GravityRD.Log.debug("Push request:",parm);if(parm.type==="event"){var hash=GravityRD.hash(parm);if(hash===this.lastHash){GravityRD.Log.debug("Suppressed event because it has the same hash as the previous event",parm);return}this.lastHash=hash;parm._ts=+new Date()/1000|0}if(GravityRD.Core.debug("eventbirth")&&parm.type==="event"){parm._I=(+new Date())+"_"+parseInt(Math.random()*9999,10);parm._S=(sync!==false)?"1":"0"}if(parm.type==="event"){this.equeue.push(parm);GravityRD.Core.Cookie.queueEvents(this.equeue,"push",true)}else{this.queue.push(parm)}this.schedule()},process:function(){this.handle=null;GravityRD.Log.group("Process queue");for(var i=0;i<this.queue.length;i++){GravityRD.Log.debug(""+i,this.queue[i])}GravityRD.Log.groupEnd();var fromCookie=GravityRD.Core.Cookie.dequeueEvents("push")||[];GravityRD.Core.process((this.queue||[]).concat(fromCookie));this.equeue=[];this.queue=[]},schedule:function(){this.clearPending();this.handle=window.setTimeout(GravityRD.bind(this.process,this),0)},clearPending:function(){if(this.handle!==null){window.clearTimeout(this.handle)}}});var pushProcessor=new GravityRD_Worker_PushProcessor();var GravityRD_Worker=GravityRD.Base.extend({__public__:["start"],keyHooked:false,installPushProcessor:function(){_gravity=pushProcessor;window.onunload=function(){if(GravityRD.Core.getConfig()["trackPageLeaveEvent"]===true){var last=GravityRD.Core.Cookie.getLastViewedItem();if(last!==null){_gravity.push({type:"event",eventType:"LEAVE_PAGE",itemId:last})}}};pushProcessor.schedule();GravityRD.Log.debug("Push processor installed")},processInitialArray:function(){for(var i=0;i<_gravity.length;i++){var item=_gravity[i];pushProcessor.push(item,false)}GravityRD.Log.debug("Initial array processed")},handleGravityHashCustom:function(){var hash=document.location.href.match("#gravity-?([^-]*)");if(hash!==null){if(""==hash[1]||"on"==hash[1]){GravityRD.Log.debug("Turning on customconfig in demo mode");GravityRD.Core.Cookie.setCookie("gr_custom","true")}else{if("session"===hash[1]){GravityRD.Core.Cookie.setCookie("gr_custom","true",false)}else{GravityRD.Core.Cookie.setCookie("gr_custom","false",0)}}}},hookCustomConfigInitKey:function(){if(!this.keyHooked){GravityRD.Log.debug("Hooking key");var demoKey=GravityRD.Core.getConfig()["customConfigDemoKey"];if(demoKey!==null){var keyCode=119;var match=demoKey.match("F([1-9][0-2]?)");if(match!==null){keyCode=111+1*match[1]}that=this;var callback=function(e){if(e.keyCode===keyCode){GravityRD.CustomConfig.init(true)}};if(document.addEventListener){document.addEventListener("keydown",callback,false)}else{document.attachEvent("onkeydown",callback)}}}this.keyHooked=true},handleCustomConfigMode:function(){if(GravityRD.CustomConfig!==undefined){var customConfig=GravityRD.Core.getConfig()["customConfig"];if(customConfig==="enabled"){GravityRD.CustomConfig.enable()}else{if(customConfig==="demo"){this.handleGravityHashCustom();var val=GravityRD.Core.Cookie.getCookie("gr_custom");if(val!==null){GravityRD.CustomConfig.enable()}this.hookCustomConfigInitKey()}}}},handleGravityHashDebug:function(){var hash=document.location.href.match("#gravity-debug-([^-]*)-([^-]*)");var debugJson=GravityRD.Core.Cookie.getDebugCookie()||{};if(hash!==null){var facet=hash[1].split(",");GravityRD.each(facet,function(f){if("on"==hash[2]){debugJson[f]=true}else{if("off"==hash[2]){debugJson[f]=false}}GravityRD.Log.debug("DEBUG_"+f,debugJson[f])});GravityRD.Core.Cookie.setDebugCookie(debugJson)}GravityRD.Core.debugMask(debugJson)},start:function(){this.handleCustomConfigMode();this.handleGravityHashDebug();GravityRD.Log.debug("Gravity object",window.gravity);_gravity=window._gravity||[];if(GravityRD.Core.debug("log")){GravityRD.Core.set({mode:"DEVELOP"})}GravityRD.Log.timeStamp("GR:start()");if(!GravityRD.isArray(_gravity)){GravityRD.Log.debug("Framework already initialized");return false}var pnv=GravityRD.Core.Cookie.getPersistentNameValues();GravityRD.each(GravityRD.keys(pnv),function(k){GravityRD.Log.debug("Loading persistent namevalue: "+k,pnv[k]);GravityRD.Core.addGlobalNameValue(k,pnv[k],true,false)});var snv=GravityRD.Core.Cookie.getSessionNameValues();GravityRD.each(GravityRD.keys(snv),function(k){GravityRD.Log.debug("Loading session namevalue: "+k,snv[k]);GravityRD.Core.addGlobalNameValue(k,snv[k],true,false)});for(var i=0;i<_gravity.length;i++){var item=_gravity[i];if(item.type==="set"){GravityRD.Core.set(item)}}var config=GravityRD.Core.getConfig();if(config.disabled===true){GravityRD.Log.usageError("GR-029");return}if(GravityRD.CustomConfig!==undefined){GravityRD.CustomConfig.init()}if(GravityRD.HUD!==undefined&&GravityRD.Core.debug("hud")){GravityRD.HUD.start()}if(!!window._gravity_init_jq){if(!!window.jQuery){window._gravity_init_jq(window.jQuery)}else{GravityRD.Log.debug("Typeahead support disabled because no jQuery found.")}}GravityRD.Log.debug("Customconfig initialized");GravityRD.Core.Cookie.setCookie("gr_recmap","",0);GravityRD.Core.Cookie.setCookie("gr_recmapkeys","",0);GravityRD.Core.Cookie.initSessionCookie();GravityRD.Core.Cookie.initPageCookie();var qp={};document.location.href.replace(/.*\?/,"").replace(/([^=]+)=([^#&]*)&?/g,function(_,a,b){try{qp[decodeURIComponent(a)]=decodeURIComponent(b)}catch(e){GravityRD.Log.debug("Invalid parameter: ",[a,b])}});if(!!qp.__iid&&!!qp.__rid){GravityRD.Core.Cookie.registerRecId(qp.__iid,qp.__rid);GravityRD.Log.debug("Registering '"+qp.__rid+"' for item '"+qp.__iid+"', reason: landing page.")}if(!!qp.__cid&&config.retargeting===true&&config.useJsGeneratedCookie===true){GravityRD.Core.Cookie.getGeneratedCookie(qp.__cid)}this.processInitialArray();this.installPushProcessor();GravityRD.Log.debug("Worker started");return true}});GravityRD.register("GravityRD","Worker",new GravityRD_Worker())})();(function(){var PerfObject=GravityRD.extend(Object,{startTime:null,endTime:null,lastTime:null,phaseNames:[],phases:{},name:null,constructor:function(name){this.name=name;this.lastTime=this.startTime=+new Date();this.phaseNames=[];this.phases={};this.endTime=null},phase:function(name){this.phaseNames.push(name);var currTime=+new Date();this.phases[name]=(currTime-this.lastTime);this.lastTime=currTime},end:function(name){if(name!=undefined){this.phase(name)}this.endTime=+new Date()},getTime:function(){if(this.endTime!=null){return this.endTime-this.startTime}else{return -1}},getPhases:function(){return this.phases},get:function(){return{diff:this.getTime(),phaseNames:this.phaseNames,phases:this.getPhases()}}});var GravityRD_Perf=GravityRD.Base.extend({__public__:["create","stat","dump"],perfObjectNames:[],perfObjects:{},create:function(name){var perfObj=new PerfObject();if(name!==undefined){this.attach(name,perfObj)}return perfObj},attach:function(name,perfobj){perfobj.name=name;this.perfObjectNames.push(name);this.perfObjects[name]=perfobj},get:function(name){return this.perfObjects[name]},stat:function(){return this.perfObjects},padR:function(s,d){while(s.length<(d||60)){s+=" "}return s},padL:function(s,d){while(s.length<(d||60)){s=" "+s}return s},dump:function(phases){var ret="";GravityRD.each(this.perfObjectNames,function(s){ret+=this.padR(s)+this.padL(""+this.perfObjects[s].getTime(),8)+" ms\n";if(phases===true){var perf=this.perfObjects[s].get();GravityRD.each(perf.phaseNames,function(name){ret+=this.padR(" - "+name)+this.padL(""+perf.phases[name],8)+" ms\n"},this)}},this);return ret}});GravityRD.register("GravityRD","Perf",new GravityRD_Perf())})();(function(){ /*! extracted from https://github.com/sindresorhus/multiline */ var reCommentContents=/\/\*!?(?:\@preserve)?[ \t]*(?:\r\n|\n)([\s\S]*?)(?:\r\n|\n)\s*\*\//;var stripIndent=function(str){var match=str.match(/^[ \t]*(?=[^\s])/gm);if(!match){return str}var indent=Math.min.apply(Math,match.map(function(el){return el.length}));var re=new RegExp("^[ \\t]{"+indent+"}","gm");return indent>0?str.replace(re,""):str};multiline=function(fn){if(typeof fn!=="function"){throw new TypeError("Expected a function.")}var match=reCommentContents.exec(fn.toString());if(!match){throw new TypeError("Multiline comment missing.")}return match[1]};multiline.stripIndent=function(fn){return stripIndent(multiline(fn))}})(); /*! * domready (c) Dustin Diaz 2012 - License MIT */ !function(name,definition){if(typeof module!="undefined"){module.exports=definition()}else{if(typeof define=="function"&&typeof define.amd=="object"){define(definition)}else{this[name]=definition()}}}("domready",function(ready){var fns=[],fn,f=false,doc=document,testEl=doc.documentElement,hack=testEl.doScroll,domContentLoaded="DOMContentLoaded",addEventListener="addEventListener",onreadystatechange="onreadystatechange",readyState="readyState",loadedRgx=hack?/^loaded|^c/:/^loaded|c/,loaded=loadedRgx.test(doc[readyState]);function flush(f){loaded=1;while(f=fns.shift()){f()}}doc[addEventListener]&&doc[addEventListener](domContentLoaded,fn=function(){doc.removeEventListener(domContentLoaded,fn,f);flush()},f);hack&&doc.attachEvent(onreadystatechange,fn=function(){if(/^c/.test(doc[readyState])){doc.detachEvent(onreadystatechange,fn);flush()}});return(ready=hack?function(fn){self!=top?loaded?fn():fns.push(fn):function(){try{testEl.doScroll("left")}catch(e){return setTimeout(function(){ready(fn)},50)}fn()}()}:function(fn){loaded?fn():fns.push(fn)})}) /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ ;(function(){var isLoader=typeof define==="function"&&define.amd;var objectTypes={"function":true,object:true};var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var root=objectTypes[typeof window]&&window||this,freeGlobal=freeExports&&objectTypes[typeof module]&&module&&!module.nodeType&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}function runInContext(context,exports){context||(context=root.Object());exports||(exports=root.Object());var Number=context.Number||root.Number,String=context.String||root.String,Object=context.Object||root.Object,Date=context.Date||root.Date,SyntaxError=context.SyntaxError||root.SyntaxError,TypeError=context.TypeError||root.TypeError,Math=context.Math||root.Math,nativeJSON=context.JSON||root.JSON;if(typeof nativeJSON=="object"&&nativeJSON){exports.stringify=nativeJSON.stringify;exports.parse=nativeJSON.parse}var objectProto=Object.prototype,getClass=objectProto.toString,isProperty,forEach,undef;var isExtended=new Date(-3509827334573292);try{isExtended=isExtended.getUTCFullYear()==-109252&&isExtended.getUTCMonth()===0&&isExtended.getUTCDate()===1&&isExtended.getUTCHours()==10&&isExtended.getUTCMinutes()==37&&isExtended.getUTCSeconds()==6&&isExtended.getUTCMilliseconds()==708}catch(exception){}function has(name){if(has[name]!==undef){return has[name]}var isSupported;if(name=="bug-string-char-index"){isSupported="a"[0]!="a"}else{if(name=="json"){isSupported=has("json-stringify")&&has("json-parse")}else{var value,serialized='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if(name=="json-stringify"){var stringify=exports.stringify,stringifySupported=typeof stringify=="function"&&isExtended;if(stringifySupported){(value=function(){return 1}).toJSON=value;try{stringifySupported=stringify(0)==="0"&&stringify(new Number())==="0"&&stringify(new String())=='""'&&stringify(getClass)===undef&&stringify(undef)===undef&&stringify()===undef&&stringify(value)==="1"&&stringify([value])=="[1]"&&stringify([undef])=="[null]"&&stringify(null)=="null"&&stringify([undef,getClass,null])=="[null,null,null]"&&stringify({a:[value,true,false,null,"\x00\b\n\f\r\t"]})==serialized&&stringify(null,value)==="1"&&stringify([1,2],null,1)=="[\n 1,\n 2\n]"&&stringify(new Date(-8640000000000000))=='"-271821-04-20T00:00:00.000Z"'&&stringify(new Date(8640000000000000))=='"+275760-09-13T00:00:00.000Z"'&&stringify(new Date(-62198755200000))=='"-000001-01-01T00:00:00.000Z"'&&stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"'}catch(exception){stringifySupported=false}}isSupported=stringifySupported}if(name=="json-parse"){var parse=exports.parse;if(typeof parse=="function"){try{if(parse("0")===0&&!parse(false)){value=parse(serialized);var parseSupported=value.a.length==5&&value.a[0]===1;if(parseSupported){try{parseSupported=!parse('"\t"')}catch(exception){}if(parseSupported){try{parseSupported=parse("01")!==1}catch(exception){}}if(parseSupported){try{parseSupported=parse("1.")!==1}catch(exception){}}}}}catch(exception){parseSupported=false}}isSupported=parseSupported}}}return has[name]=!!isSupported}if(!has("json")){var functionClass="[object Function]",dateClass="[object Date]",numberClass="[object Number]",stringClass="[object String]",arrayClass="[object Array]",booleanClass="[object Boolean]";var charIndexBuggy=has("bug-string-char-index");if(!isExtended){var floor=Math.floor;var Months=[0,31,59,90,120,151,181,212,243,273,304,334];var getDay=function(year,month){return Months[month]+365*(year-1970)+floor((year-1969+(month=+(month>1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty=objectProto.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in (this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties();for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&objectTypes[typeof object.hasOwnProperty]&&object.hasOwnProperty||isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property)){}}}else{if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,(property="constructor"))){callback(property)}}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,useCharIndex=!charIndexBuggy||length>10;var symbols=useCharIndex&&(charIndexBuggy?value.split(""):value);for(;index<length;index++){var charCode=value.charCodeAt(index);switch(charCode){case 8:case 9:case 10:case 12:case 13:case 34:case 92:result+=Escapes[charCode];break;default:if(charCode<32){result+=unicodePrefix+toPaddedString(2,charCode.toString(16));break}result+=useCharIndex?symbols[index]:value.charAt(index)}}return result+'"'};var serialize=function(property,object,callback,properties,whitespace,indentation,stack){var value,className,year,month,date,time,hours,minutes,seconds,milliseconds,results,element,index,length,prefix,result;try{value=object[property]}catch(exception){}if(typeof value=="object"&&value){className=getClass.call(value);if(className==dateClass&&!isProperty.call(value,"toJSON")){if(value>-1/0&&value<1/0){if(getDay){date=floor(value/86400000);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++){}for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++){}date=1+date-getDay(year,month);time=(value%86400000+86400000)%86400000;hours=floor(time/3600000)%24;minutes=floor(time/60000)%60;seconds=floor(time/1000)%60;milliseconds=time%1000}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=10000?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else{if(typeof value.toJSON=="function"&&((className!=numberClass&&className!=stringClass&&className!=arrayClass)||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else{if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else{if(className==stringClass){return quote(""+value)}}}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index<length;index++){element=serialize(index,value,callback,properties,whitespace,indentation,stack);results.push(element===undef?"null":element)}result=results.length?(whitespace?"[\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"]":("["+results.join(",")+"]")):"[]"}else{forEach(properties||value,function(property){var element=serialize(property,value,callback,properties,whitespace,indentation,stack);if(element!==undef){results.push(quote(property)+":"+(whitespace?" ":"")+element)}});result=results.length?(whitespace?"{\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"}":("{"+results.join(",")+"}")):"{}"}stack.pop();return result}};exports.stringify=function(source,filter,width){var whitespace,callback,properties,className;if(objectTypes[typeof filter]&&filter){if((className=getClass.call(filter))==functionClass){callback=filter}else{if(className==arrayClass){properties={};for(var index=0,length=filter.length,value;index<length;value=filter[index++],((className=getClass.call(value)),className==stringClass||className==numberClass)&&(properties[value]=1)){}}}}if(width){if((className=getClass.call(width))==numberClass){if((width-=width%1)>0){for(whitespace="",width>10&&(width=10);whitespace.length<width;whitespace+=" "){}}}else{if(className==stringClass){whitespace=width.length<=10?width:width.slice(0,10)}}}return serialize("",(value={},value[""]=source,value),callback,properties,whitespace,"",[])}}if(!has("json-parse")){var fromCharCode=String.fromCharCode;var Unescapes={92:"\\",34:'"',47:"/",98:"\b",116:"\t",110:"\n",102:"\f",114:"\r"};var Index,Source;var abort=function(){Index=Source=null;throw SyntaxError()};var lex=function(){var source=Source,length=source.length,value,begin,position,isSigned,charCode;while(Index<length){charCode=source.charCodeAt(Index);switch(charCode){case 9:case 10:case 13:case 32:Index++;break;case 123:case 125:case 91:case 93:case 58:case 44:value=charIndexBuggy?source.charAt(Index):source[Index];Index++;return value;case 34:for(value="@",Index++;Index<length;){charCode=source.charCodeAt(Index);if(charCode<32){abort()}else{if(charCode==92){charCode=source.charCodeAt(++Index);switch(charCode){case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:value+=Unescapes[charCode];Index++;break;case 117:begin=++Index;for(position=Index+4;Index<position;Index++){charCode=source.charCodeAt(Index);if(!(charCode>=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&((charCode=source.charCodeAt(Index+1)),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index<length&&((charCode=source.charCodeAt(Index)),charCode>=48&&charCode<=57);Index++){}if(source.charCodeAt(Index)==46){position=++Index;for(;position<length&&((charCode=source.charCodeAt(position)),charCode>=48&&charCode<=57);position++){}if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position<length&&((charCode=source.charCodeAt(position)),charCode>=48&&charCode<=57);position++){}if(position==Index){abort()}Index=position}return +source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else{if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else{if(source.slice(Index,Index+4)=="null"){Index+=4;return null}}}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else{if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};exports.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}exports.runInContext=runInContext;return exports}if(freeExports&&!isLoader){runInContext(root,freeExports)}else{var nativeJSON=root.JSON,previousJSON=root.JSON3,isRestored=false;var JSON3=runInContext(root,(root.JSON3={noConflict:function(){if(!isRestored){isRestored=true;root.JSON=nativeJSON;root.JSON3=previousJSON;nativeJSON=previousJSON=null}return JSON3}}));root.JSON={parse:JSON3.parse,stringify:JSON3.stringify}}if(isLoader){define(function(){return JSON3})}}).call(this);grJSON3=JSON3.noConflict();"use strict";(function(E){function t(e,a,c){var g=0,b=[],d=0,f,k,l,h,m,w,n,q=!1,r=!1,p=[],t=[],v,u=!1;c=c||{};f=c.encoding||"UTF8";v=c.numRounds||1;l=y(a,f);if(v!==parseInt(v,10)||1>v){throw Error("numRounds must a integer >= 1")}if("SHA-1"===e){m=512,w=z,n=F,h=160}else{throw Error("Chosen SHA variant is not supported")}k=x(e);this.setHMACKey=function(a,b,d){var c;if(!0===r){throw Error("HMAC key already set")}if(!0===q){throw Error("Cannot set HMAC key after finalizing hash")}if(!0===u){throw Error("Cannot set HMAC key after calling update")}f=(d||{}).encoding||"UTF8";b=y(b,f)(a);a=b.binLen;b=b.value;c=m>>>3;d=c/4-1;if(c<a/8){for(b=n(b,a,0,x(e));b.length<=d;){b.push(0)}b[d]&=4294967040}else{if(c>a/8){for(;b.length<=d;){b.push(0)}b[d]&=4294967040}}for(a=0;a<=d;a+=1){p[a]=b[a]^909522486,t[a]=b[a]^1549556828}k=w(p,k);g=m;r=!0};this.update=function(a){var e,c,f,h=0,n=m>>>5;e=l(a,b,d);a=e.binLen;c=e.value;e=a>>>5;for(f=0;f<e;f+=n){h+m<=a&&(k=w(c.slice(f,f+n),k),h+=m)}g+=h;b=c.slice(h>>>5);d=a%m;u=!0};this.getHash=function(a,c){var f,l,m;if(!0===r){throw Error("Cannot call getHash after setting HMAC key")}m=A(c);switch(a){case"HEX":f=function(a){return B(a,m)};break;case"B64":f=function(a){return C(a,m)};break;case"BYTES":f=D;break;default:throw Error("format must be HEX, B64, or BYTES")}if(!1===q){for(k=n(b,d,g,k),l=1;l<v;l+=1){k=n(k,h,0,x(e))}}q=!0;return f(k)};this.getHMAC=function(a,c){var f,l,p;if(!1===r){throw Error("Cannot call getHMAC without first setting HMAC key")}p=A(c);switch(a){case"HEX":f=function(a){return B(a,p)};break;case"B64":f=function(a){return C(a,p)};break;case"BYTES":f=D;break;default:throw Error("outputFormat must be HEX, B64, or BYTES")}!1===q&&(l=n(b,d,g,k),k=w(t,x(e)),k=n(l,h,m,k));q=!0;return f(k)}}function G(e,a,c){var g=e.length,b,d,f,k,l;a=a||[0];c=c||0;l=c>>>3;if(0!==g%2){throw Error("String of HEX type must be in byte increments")}for(b=0;b<g;b+=2){d=parseInt(e.substr(b,2),16);if(isNaN(d)){throw Error("String of HEX type contains invalid characters")}k=(b>>>1)+l;for(f=k>>>2;a.length<=f;){a.push(0)}a[f]|=d<<8*(3-k%4)}return{value:a,binLen:4*g+c}}function H(e,a,c){var g=[],b,d,f,k,g=a||[0];c=c||0;d=c>>>3;for(b=0;b<e.length;b+=1){a=e.charCodeAt(b),k=b+d,f=k>>>2,g.length<=f&&g.push(0),g[f]|=a<<8*(3-k%4)}return{value:g,binLen:8*e.length+c}}function I(e,a,c){var g=[],b=0,d,f,k,l,h,m,g=a||[0];c=c||0;a=c>>>3;if(-1===e.search(/^[a-zA-Z0-9=+\/]+$/)){throw Error("Invalid character in base-64 string")}f=e.indexOf("=");e=e.replace(/\=/g,"");if(-1!==f&&f<e.length){throw Error("Invalid '=' found in base-64 string")}for(f=0;f<e.length;f+=4){h=e.substr(f,4);for(k=l=0;k<h.length;k+=1){d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(h[k]),l|=d<<18-6*k}for(k=0;k<h.length-1;k+=1){m=b+a;for(d=m>>>2;g.length<=d;){g.push(0)}g[d]|=(l>>>16-8*k&255)<<8*(3-m%4);b+=1}}return{value:g,binLen:8*b+c}}function B(e,a){var c="",g=4*e.length,b,d;for(b=0;b<g;b+=1){d=e[b>>>2]>>>8*(3-b%4),c+="0123456789abcdef".charAt(d>>>4&15)+"0123456789abcdef".charAt(d&15)}return a.outputUpper?c.toUpperCase():c}function C(e,a){var c="",g=4*e.length,b,d,f;for(b=0;b<g;b+=3){for(f=b+1>>>2,d=e.length<=f?0:e[f],f=b+2>>>2,f=e.length<=f?0:e[f],f=(e[b>>>2]>>>8*(3-b%4)&255)<<16|(d>>>8*(3-(b+1)%4)&255)<<8|f>>>8*(3-(b+2)%4)&255,d=0;4>d;d+=1){8*b+6*d<=32*e.length?c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(f>>>6*(3-d)&63):c+=a.b64Pad}}return c}function D(e){var a="",c=4*e.length,g,b;for(g=0;g<c;g+=1){b=e[g>>>2]>>>8*(3-g%4)&255,a+=String.fromCharCode(b)}return a}function A(e){var a={outputUpper:!1,b64Pad:"="};e=e||{};a.outputUpper=e.outputUpper||!1;!0===e.hasOwnProperty("b64Pad")&&(a.b64Pad=e.b64Pad);if("boolean"!==typeof a.outputUpper){throw Error("Invalid outputUpper formatting option")}if("string"!==typeof a.b64Pad){throw Error("Invalid b64Pad formatting option")}return a}function y(e,a){var c;switch(a){case"UTF8":case"UTF16BE":case"UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE")}switch(e){case"HEX":c=G;break;case"TEXT":c=function(e,b,d){var f=[],c=[],l=0,h,m,p,n,q,f=b||[0];b=d||0;p=b>>>3;if("UTF8"===a){for(h=0;h<e.length;h+=1){for(d=e.charCodeAt(h),c=[],128>d?c.push(d):2048>d?(c.push(192|d>>>6),c.push(128|d&63)):55296>d||57344<=d?c.push(224|d>>>12,128|d>>>6&63,128|d&63):(h+=1,d=65536+((d&1023)<<10|e.charCodeAt(h)&1023),c.push(240|d>>>18,128|d>>>12&63,128|d>>>6&63,128|d&63)),m=0;m<c.length;m+=1){q=l+p;for(n=q>>>2;f.length<=n;){f.push(0)}f[n]|=c[m]<<8*(3-q%4);l+=1}}}else{if("UTF16BE"===a||"UTF16LE"===a){for(h=0;h<e.length;h+=1){d=e.charCodeAt(h);"UTF16LE"===a&&(m=d&255,d=m<<8|d>>>8);q=l+p;for(n=q>>>2;f.length<=n;){f.push(0)}f[n]|=d<<8*(2-q%4);l+=2}}}return{value:f,binLen:8*l+b}};break;case"B64":c=I;break;case"BYTES":c=H;break;default:throw Error("format must be HEX, TEXT, B64, or BYTES")}return c}function r(e,a){return e<<a|e>>>32-a}function p(e,a){var c=(e&65535)+(a&65535);return((e>>>16)+(a>>>16)+(c>>>16)&65535)<<16|c&65535}function u(e,a,c,g,b){var d=(e&65535)+(a&65535)+(c&65535)+(g&65535)+(b&65535);return((e>>>16)+(a>>>16)+(c>>>16)+(g>>>16)+(b>>>16)+(d>>>16)&65535)<<16|d&65535}function x(e){if("SHA-1"===e){e=[1732584193,4023233417,2562383102,271733878,3285377520]}else{throw Error("No SHA variants supported")}return e}function z(e,a){var c=[],g,b,d,f,k,l,h;g=a[0];b=a[1];d=a[2];f=a[3];k=a[4];for(h=0;80>h;h+=1){c[h]=16>h?e[h]:r(c[h-3]^c[h-8]^c[h-14]^c[h-16],1),l=20>h?u(r(g,5),b&d^~b&f,k,1518500249,c[h]):40>h?u(r(g,5),b^d^f,k,1859775393,c[h]):60>h?u(r(g,5),b&d^b&f^d&f,k,2400959708,c[h]):u(r(g,5),b^d^f,k,3395469782,c[h]),k=f,f=d,d=r(b,30),b=g,g=l}a[0]=p(g,a[0]);a[1]=p(b,a[1]);a[2]=p(d,a[2]);a[3]=p(f,a[3]);a[4]=p(k,a[4]);return a}function F(e,a,c,g){var b;for(b=(a+65>>>9<<4)+15;e.length<=b;){e.push(0)}e[a>>>5]|=128<<24-a%32;e[b]=a+c;c=e.length;for(a=0;a<c;a+=16){g=z(e.slice(a,a+16),g)}return g}"function"===typeof define&&define.amd?define(function(){return t}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=t:exports=t:E.jsSHA=t})(this); /*! Waypoints - 3.1.1 Copyright © 2011-2015 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/waypoints/blog/master/licenses.txt */ (function(){var keyCounter=0;var allWaypoints={};function Waypoint(options){if(!options){throw new Error("No options passed to Waypoint constructor")}if(!options.element){throw new Error("No element option passed to Waypoint constructor")}if(!options.handler){throw new Error("No handler option passed to Waypoint constructor")}this.key="waypoint-"+keyCounter;this.options=Waypoint.Adapter.extend({},Waypoint.defaults,options);this.element=this.options.element;this.adapter=new Waypoint.Adapter(this.element);this.callback=options.handler;this.axis=this.options.horizontal?"horizontal":"vertical";this.enabled=this.options.enabled;this.triggerPoint=null;this.group=Waypoint.Group.findOrCreate({name:this.options.group,axis:this.axis});this.context=Waypoint.Context.findOrCreateByElement(this.options.context);if(Waypoint.offsetAliases[this.options.offset]){this.options.offset=Waypoint.offsetAliases[this.options.offset]}this.group.add(this);this.context.add(this);allWaypoints[this.key]=this;keyCounter+=1}Waypoint.prototype.queueTrigger=function(direction){this.group.queueTrigger(this,direction)};Waypoint.prototype.trigger=function(args){if(!this.enabled){return}if(this.callback){this.callback.apply(this,args)}};Waypoint.prototype.destroy=function(){this.context.remove(this);this.group.remove(this);delete allWaypoints[this.key]};Waypoint.prototype.disable=function(){this.enabled=false;return this};Waypoint.prototype.enable=function(){this.context.refresh();this.enabled=true;return this};Waypoint.prototype.next=function(){return this.group.next(this)};Waypoint.prototype.previous=function(){return this.group.previous(this)};Waypoint.invokeAll=function(method){var allWaypointsArray=[];for(var waypointKey in allWaypoints){allWaypointsArray.push(allWaypoints[waypointKey])}for(var i=0,end=allWaypointsArray.length;i<end;i++){allWaypointsArray[i][method]()}};Waypoint.destroyAll=function(){Waypoint.invokeAll("destroy")};Waypoint.disableAll=function(){Waypoint.invokeAll("disable")};Waypoint.enableAll=function(){Waypoint.invokeAll("enable")};Waypoint.refreshAll=function(){Waypoint.Context.refreshAll()};Waypoint.viewportHeight=function(){return window.innerHeight||document.documentElement.clientHeight};Waypoint.viewportWidth=function(){return document.documentElement.clientWidth};Waypoint.adapters=[];Waypoint.defaults={context:window,continuous:true,enabled:true,group:"default",horizontal:false,offset:0};Waypoint.offsetAliases={"bottom-in-view":function(){return this.context.innerHeight()-this.adapter.outerHeight()},"right-in-view":function(){return this.context.innerWidth()-this.adapter.outerWidth()}};window.Waypoint=Waypoint}());(function(){function requestAnimationFrameShim(callback){window.setTimeout(callback,1000/60)}var keyCounter=0;var contexts={};var Waypoint=window.Waypoint;var oldWindowLoad=window.onload;function Context(element){this.element=element;this.Adapter=Waypoint.Adapter;this.adapter=new this.Adapter(element);this.key="waypoint-context-"+keyCounter;this.didScroll=false;this.didResize=false;this.oldScroll={x:this.adapter.scrollLeft(),y:this.adapter.scrollTop()};this.waypoints={vertical:{},horizontal:{}};element.waypointContextKey=this.key;contexts[element.waypointContextKey]=this;keyCounter+=1;this.createThrottledScrollHandler();this.createThrottledResizeHandler()}Context.prototype.add=function(waypoint){var axis=waypoint.options.horizontal?"horizontal":"vertical";this.waypoints[axis][waypoint.key]=waypoint;this.refresh()};Context.prototype.checkEmpty=function(){var horizontalEmpty=this.Adapter.isEmptyObject(this.waypoints.horizontal);var verticalEmpty=this.Adapter.isEmptyObject(this.waypoints.vertical);if(horizontalEmpty&&verticalEmpty){this.adapter.off(".waypoints");delete contexts[this.key]}};Context.prototype.createThrottledResizeHandler=function(){var self=this;function resizeHandler(){self.handleResize();self.didResize=false}this.adapter.on("resize.waypoints",function(){if(!self.didResize){self.didResize=true;Waypoint.requestAnimationFrame(resizeHandler)}})};Context.prototype.createThrottledScrollHandler=function(){var self=this;function scrollHandler(){self.handleScroll();self.didScroll=false}this.adapter.on("scroll.waypoints",function(){if(!self.didScroll||Waypoint.isTouch){self.didScroll=true;Waypoint.requestAnimationFrame(scrollHandler)}})};Context.prototype.handleResize=function(){Waypoint.Context.refreshAll()};Context.prototype.handleScroll=function(){var triggeredGroups={};var axes={horizontal:{newScroll:this.adapter.scrollLeft(),oldScroll:this.oldScroll.x,forward:"right",backward:"left"},vertical:{newScroll:this.adapter.scrollTop(),oldScroll:this.oldScroll.y,forward:"down",backward:"up"}};for(var axisKey in axes){var axis=axes[axisKey];var isForward=axis.newScroll>axis.oldScroll;var direction=isForward?axis.forward:axis.backward;for(var waypointKey in this.waypoints[axisKey]){var waypoint=this.waypoints[axisKey][waypointKey];var wasBeforeTriggerPoint=axis.oldScroll<waypoint.triggerPoint;var nowAfterTriggerPoint=axis.newScroll>=waypoint.triggerPoint;var crossedForward=wasBeforeTriggerPoint&&nowAfterTriggerPoint;var crossedBackward=!wasBeforeTriggerPoint&&!nowAfterTriggerPoint;if(crossedForward||crossedBackward){waypoint.queueTrigger(direction);triggeredGroups[waypoint.group.id]=waypoint.group}}}for(var groupKey in triggeredGroups){triggeredGroups[groupKey].flushTriggers()}this.oldScroll={x:axes.horizontal.newScroll,y:axes.vertical.newScroll}};Context.prototype.innerHeight=function(){if(this.element==this.element.window){return Waypoint.viewportHeight()}return this.adapter.innerHeight()};Context.prototype.remove=function(waypoint){delete this.waypoints[waypoint.axis][waypoint.key];this.checkEmpty()};Context.prototype.innerWidth=function(){if(this.element==this.element.window){return Waypoint.viewportWidth()}return this.adapter.innerWidth()};Context.prototype.destroy=function(){var allWaypoints=[];for(var axis in this.waypoints){for(var waypointKey in this.waypoints[axis]){allWaypoints.push(this.waypoints[axis][waypointKey])}}for(var i=0,end=allWaypoints.length;i<end;i++){allWaypoints[i].destroy()}};Context.prototype.refresh=function(){var isWindow=this.element==this.element.window;var contextOffset=this.adapter.offset();var triggeredGroups={};var axes;this.handleScroll();axes={horizontal:{contextOffset:isWindow?0:contextOffset.left,contextScroll:isWindow?0:this.oldScroll.x,contextDimension:this.innerWidth(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:isWindow?0:contextOffset.top,contextScroll:isWindow?0:this.oldScroll.y,contextDimension:this.innerHeight(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};for(var axisKey in axes){var axis=axes[axisKey];for(var waypointKey in this.waypoints[axisKey]){var waypoint=this.waypoints[axisKey][waypointKey];var adjustment=waypoint.options.offset;var oldTriggerPoint=waypoint.triggerPoint;var elementOffset=0;var freshWaypoint=oldTriggerPoint==null;var contextModifier,wasBeforeScroll,nowAfterScroll;var triggeredBackward,triggeredForward;if(waypoint.element!==waypoint.element.window){elementOffset=waypoint.adapter.offset()[axis.offsetProp]}if(typeof adjustment==="function"){adjustment=adjustment.apply(waypoint)}else{if(typeof adjustment==="string"){adjustment=parseFloat(adjustment);if(waypoint.options.offset.indexOf("%")>-1){adjustment=Math.ceil(axis.contextDimension*adjustment/100)}}}contextModifier=axis.contextScroll-axis.contextOffset;waypoint.triggerPoint=elementOffset+contextModifier-adjustment;wasBeforeScroll=oldTriggerPoint<axis.oldScroll;nowAfterScroll=waypoint.triggerPoint>=axis.oldScroll;triggeredBackward=wasBeforeScroll&&nowAfterScroll;triggeredForward=!wasBeforeScroll&&!nowAfterScroll;if(!freshWaypoint&&triggeredBackward){waypoint.queueTrigger(axis.backward);triggeredGroups[waypoint.group.id]=waypoint.group}else{if(!freshWaypoint&&triggeredForward){waypoint.queueTrigger(axis.forward);triggeredGroups[waypoint.group.id]=waypoint.group}else{if(freshWaypoint&&axis.oldScroll>=waypoint.triggerPoint){waypoint.queueTrigger(axis.forward);triggeredGroups[waypoint.group.id]=waypoint.group}}}}}for(var groupKey in triggeredGroups){triggeredGroups[groupKey].flushTriggers()}return this};Context.findOrCreateByElement=function(element){return Context.findByElement(element)||new Context(element)};Context.refreshAll=function(){for(var contextId in contexts){contexts[contextId].refresh()}};Context.findByElement=function(element){return contexts[element.waypointContextKey]};window.onload=function(){if(oldWindowLoad){oldWindowLoad()}Context.refreshAll()};Waypoint.requestAnimationFrame=function(callback){var requestFn=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||requestAnimationFrameShim;requestFn.call(window,callback)};Waypoint.Context=Context}());(function(){function byTriggerPoint(a,b){return a.triggerPoint-b.triggerPoint}function byReverseTriggerPoint(a,b){return b.triggerPoint-a.triggerPoint}var groups={vertical:{},horizontal:{}};var Waypoint=window.Waypoint;function Group(options){this.name=options.name;this.axis=options.axis;this.id=this.name+"-"+this.axis;this.waypoints=[];this.clearTriggerQueues();groups[this.axis][this.name]=this}Group.prototype.add=function(waypoint){this.waypoints.push(waypoint)};Group.prototype.clearTriggerQueues=function(){this.triggerQueues={up:[],down:[],left:[],right:[]}};Group.prototype.flushTriggers=function(){for(var direction in this.triggerQueues){var waypoints=this.triggerQueues[direction];var reverse=direction==="up"||direction==="left";waypoints.sort(reverse?byReverseTriggerPoint:byTriggerPoint);for(var i=0,end=waypoints.length;i<end;i+=1){var waypoint=waypoints[i];if(waypoint.options.continuous||i===waypoints.length-1){waypoint.trigger([direction])}}}this.clearTriggerQueues()};Group.prototype.next=function(waypoint){this.waypoints.sort(byTriggerPoint);var index=Waypoint.Adapter.inArray(waypoint,this.waypoints);var isLast=index===this.waypoints.length-1;return isLast?null:this.waypoints[index+1]};Group.prototype.previous=function(waypoint){this.waypoints.sort(byTriggerPoint);var index=Waypoint.Adapter.inArray(waypoint,this.waypoints);return index?this.waypoints[index-1]:null};Group.prototype.queueTrigger=function(waypoint,direction){this.triggerQueues[direction].push(waypoint)};Group.prototype.remove=function(waypoint){var index=Waypoint.Adapter.inArray(waypoint,this.waypoints);if(index>-1){this.waypoints.splice(index,1)}};Group.prototype.first=function(){return this.waypoints[0]};Group.prototype.last=function(){return this.waypoints[this.waypoints.length-1]};Group.findOrCreate=function(options){return groups[options.axis][options.name]||new Group(options)};Waypoint.Group=Group}());(function(){var Waypoint=window.Waypoint;function isWindow(element){return element===element.window}function getWindow(element){if(isWindow(element)){return element}return element.defaultView}function NoFrameworkAdapter(element){this.element=element;this.handlers={}}NoFrameworkAdapter.prototype.innerHeight=function(){var isWin=isWindow(this.element);return isWin?this.element.innerHeight:this.element.clientHeight};NoFrameworkAdapter.prototype.innerWidth=function(){var isWin=isWindow(this.element);return isWin?this.element.innerWidth:this.element.clientWidth};NoFrameworkAdapter.prototype.off=function(event,handler){function removeListeners(element,listeners,handler){for(var i=0,end=listeners.length-1;i<end;i++){var listener=listeners[i];if(!handler||handler===listener){element.removeEventListener(listener)}}}var eventParts=event.split(".");var eventType=eventParts[0];var namespace=eventParts[1];var element=this.element;if(namespace&&this.handlers[namespace]&&eventType){removeListeners(element,this.handlers[namespace][eventType],handler);this.handlers[namespace][eventType]=[]}else{if(eventType){for(var ns in this.handlers){removeListeners(element,this.handlers[ns][eventType]||[],handler);this.handlers[ns][eventType]=[]}}else{if(namespace&&this.handlers[namespace]){for(var type in this.handlers[namespace]){removeListeners(element,this.handlers[namespace][type],handler)}this.handlers[namespace]={}}}}};NoFrameworkAdapter.prototype.offset=function(){if(!this.element.ownerDocument){return null}var documentElement=this.element.ownerDocument.documentElement;var win=getWindow(this.element.ownerDocument);var rect={top:0,left:0};if(this.element.getBoundingClientRect){rect=this.element.getBoundingClientRect()}return{top:rect.top+win.pageYOffset-documentElement.clientTop,left:rect.left+win.pageXOffset-documentElement.clientLeft}};NoFrameworkAdapter.prototype.on=function(event,handler){var eventParts=event.split(".");var eventType=eventParts[0];var namespace=eventParts[1]||"__default";var nsHandlers=this.handlers[namespace]=this.handlers[namespace]||{};var nsTypeList=nsHandlers[eventType]=nsHandlers[eventType]||[];nsTypeList.push(handler);this.element.addEventListener(eventType,handler)};NoFrameworkAdapter.prototype.outerHeight=function(includeMargin){var height=this.innerHeight();var computedStyle;if(includeMargin&&!isWindow(this.element)){computedStyle=window.getComputedStyle(this.element);height+=parseInt(computedStyle.marginTop,10);height+=parseInt(computedStyle.marginBottom,10)}return height};NoFrameworkAdapter.prototype.outerWidth=function(includeMargin){var width=this.innerWidth();var computedStyle;if(includeMargin&&!isWindow(this.element)){computedStyle=window.getComputedStyle(this.element);width+=parseInt(computedStyle.marginLeft,10);width+=parseInt(computedStyle.marginRight,10)}return width};NoFrameworkAdapter.prototype.scrollLeft=function(){var win=getWindow(this.element);return win?win.pageXOffset:this.element.scrollLeft};NoFrameworkAdapter.prototype.scrollTop=function(){var win=getWindow(this.element);return win?win.pageYOffset:this.element.scrollTop};NoFrameworkAdapter.extend=function(){var args=Array.prototype.slice.call(arguments);function merge(target,obj){if(typeof target==="object"&&typeof obj==="object"){for(var key in obj){if(obj.hasOwnProperty(key)){target[key]=obj[key]}}}return target}for(var i=1,end=args.length;i<end;i++){merge(args[0],args[i])}return args[0]};NoFrameworkAdapter.inArray=function(element,array,i){return array==null?-1:array.indexOf(element,i)};NoFrameworkAdapter.isEmptyObject=function(obj){for(var name in obj){return false}return true};Waypoint.adapters.push({name:"noframework",Adapter:NoFrameworkAdapter});Waypoint.Adapter=NoFrameworkAdapter}()); /*! Waypoints Inview Shortcut Timer based - 3.1.1 Copyright © 2011-2015 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/waypoints/blog/master/licenses.txt */ (function(){var Waypoint=window.Waypoint;function InviewTimer(options){this.options=Waypoint.Adapter.extend({},InviewTimer.defaults,options);this.options.ratio=parseFloat(/(\d+)\%/.exec(this.options.offset)[1])/100;this.waypoints=[];this.timerVertical=null;this.timerHorizontal=null;this.timerVerticalDone=false;this.timerHorizontalDone=false;this.createWaypoints()}var noop=function(){};InviewTimer.prototype.createWaypoints=function(){var r=this.options.ratio;var rI=1-r;function addLog(command,direction,wp,extra){var d=new Date().toISOString().split("T")[1];d+=" "+wp.options.debug;d+=" "+command;d+=" "+direction;d+=" "+wp.axis;d+=" page="+wp.context.innerHeight()+"X"+wp.context.innerWidth();d+=" div="+wp.adapter.outerHeight()+"X"+wp.adapter.outerWidth();d+=" triggerPoint="+wp.triggerPoint;d+=" cur_offset="+wp.options.offset.call(wp)+" with "+wp.options.o;if(extra!==undefined&&extra!==""){d+=extra}}function timeoutDone(c,o,wp,direction){if(c.isHorizontal){o.timerHorizontalDone=true}else{o.timerVerticalDone=true}var shouldBeCalled=o.timerVerticalDone===true&&o.timerHorizontalDone===true;addLog("done ",direction,wp,shouldBeCalled?" trigger":"");if(shouldBeCalled){o.options.callback(o.options);if(o.options.destroyOnValid){o.destroy()}else{if(c.isHorizontal){o.timerHorizontal=null}else{o.timerVertical=null}}}}function enter(c,o,direction,wp){var timer=c.isHorizontal?o.timerHorizontal:o.timerVertical;addLog("enter",direction,wp,timer!==null?" already entered":"");if(timer!==null){return}timer=window.setTimeout(function(){timeoutDone(c,o,wp,direction)},o.options.timeout);if(c.isHorizontal){o.timerHorizontal=timer}else{o.timerVertical=timer}}function exit(c,o,direction,wp){var timer=c.isHorizontal?o.timerHorizontal:o.timerVertical;addLog("exit ",direction,wp,timer===null?" no prior enter":"");if(timer===null){return}clearTimeout(timer);if(c.isHorizontal){o.timerHorizontalDone=false;o.timerHorizontal=null}else{o.timerVerticalDone=false;o.timerVertical=null}}function top(){return -1*Math.round(this.adapter.outerHeight()*rI)-1}function bottom(){return Math.round(this.context.innerHeight()-this.adapter.outerHeight()*r)+1}function left(){return -1*Math.round(this.adapter.outerWidth()*rI)-1}function right(){return Math.round(this.context.innerWidth()-this.adapter.outerWidth()*r)+1}var configs={vertical:[{up:exit,down:enter,offset:bottom,o:"bottom"},{up:enter,down:exit,offset:top,o:"top"}],horizontal:[{left:exit,right:enter,offset:right,o:"right"},{left:enter,right:exit,offset:left,o:"left"}]};this.generateWaypoints(configs.vertical,false);this.generateWaypoints(configs.horizontal,true)};InviewTimer.prototype.generateWaypoints=function(configs,isHorizontal){for(var i=0;i<configs.length;i++){this.createWaypoint(Waypoint.Adapter.extend({},{isHorizontal:isHorizontal,debug:this.options.debug},configs[i]))}};InviewTimer.prototype.createWaypoint=function(config){this.waypoints.push(new Waypoint({element:this.options.element,handler:(function(config,o){return function(direction){config[direction](config,o,direction,this)}}(config,this)),offset:config.offset,horizontal:config.isHorizontal,debug:config.debug,o:config.o}))};InviewTimer.prototype.destroy=function(){for(var i=0,end=this.waypoints.length;i<end;i++){this.waypoints[i].destroy()}this.waypoints=[]};InviewTimer.defaults={timeout:100,offset:"80%",callback:noop,destroyOnValid:true};Waypoint.InviewTimer=InviewTimer}());if(typeof(TrimPath)=="undefined"){TrimPath={}}(function(){if(TrimPath.evalEx==null){TrimPath.evalEx=function(src){return eval(src)}}var UNDEFINED;if(Array.prototype.pop==null){Array.prototype.pop=function(){if(this.length===0){return UNDEFINED}return this[--this.length]}}if(Array.prototype.push==null){Array.prototype.push=function(){for(var i=0;i<arguments.length;++i){this[this.length]=arguments[i]}return this.length}}TrimPath.parseTemplate=function(tmplContent,optTmplName,optEtc){if(optEtc==null){optEtc=TrimPath.parseTemplate_etc}var funcSrc=parse(tmplContent,optTmplName,optEtc);var func=TrimPath.evalEx(funcSrc,optTmplName,1);if(func!=null){return new optEtc.Template(optTmplName,tmplContent,funcSrc,func,optEtc)}return null};var exceptionDetails=function(e){return(e.toString())+";\n "+(e.message)+";\n "+(e.name)+";\n "+(e.stack||"no stack trace")+";\n "+(e.description||"no further description")+";\n "+(e.fileName||"no file name")+";\n "+(e.lineNumber||"no line number")};try{String.prototype.process=function(context,optFlags){var template=TrimPath.parseTemplate(this,null);if(template!=null){return template.process(context,optFlags)}return this}}catch(e){}TrimPath.parseTemplate_etc={};TrimPath.parseTemplate_etc.statementTag="forelse|for|if|elseif|else|var|macro";TrimPath.parseTemplate_etc.statementDef={"if":{delta:1,prefix:"if (",suffix:") {",paramMin:1},"else":{delta:0,prefix:"} else {"},elseif:{delta:0,prefix:"} else if (",suffix:") {",paramDefault:"true"},"/if":{delta:-1,prefix:"}"},"for":{delta:1,paramMin:3,prefixFunc:function(stmtParts,state,tmplName,etc){if(stmtParts[2]!="in"){throw new etc.ParseError(tmplName,state.line,"bad for loop statement: "+stmtParts.join(" "))}var iterVar=stmtParts[1];var listVar="__LIST__"+iterVar;return["var ",listVar," = ",stmtParts[3],";","var __LENGTH_STACK__;","if (typeof(__LENGTH_STACK__) == 'undefined' || !__LENGTH_STACK__.length) __LENGTH_STACK__ = new Array();","__LENGTH_STACK__[__LENGTH_STACK__.length] = 0;","if ((",listVar,") != null) { ","var ",iterVar,"_ct = 0;","for (var ",iterVar,"_index in ",listVar,") { ",iterVar,"_ct++;","if (typeof(",listVar,"[",iterVar,"_index]) == 'function') {continue;}","__LENGTH_STACK__[__LENGTH_STACK__.length - 1]++;","var ",iterVar," = ",listVar,"[",iterVar,"_index];"].join("")}},forelse:{delta:0,prefix:"} } if (__LENGTH_STACK__[__LENGTH_STACK__.length - 1] == 0) { if (",suffix:") {",paramDefault:"true"},"/for":{delta:-1,prefix:"} }; delete __LENGTH_STACK__[__LENGTH_STACK__.length - 1];"},"var":{delta:0,prefix:"var ",suffix:";"},macro:{delta:1,prefixFunc:function(stmtParts,state,tmplName,etc){var macroName=stmtParts[1].split("(")[0];return["var ",macroName," = function",stmtParts.slice(1).join(" ").substring(macroName.length),"{ var _OUT_arr = []; var _OUT = { write: function(m) { if (m) _OUT_arr.push(m); } }; "].join("")}},"/macro":{delta:-1,prefix:" return _OUT_arr.join(''); };"}};TrimPath.parseTemplate_etc.modifierDef={eat:function(v){return""},escape:function(s){return String(s).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")},capitalize:function(s){return String(s).toUpperCase()},"default":function(s,d){return s!=null?s:d}};TrimPath.parseTemplate_etc.modifierDef.h=TrimPath.parseTemplate_etc.modifierDef.escape;TrimPath.parseTemplate_etc.Template=function(tmplName,tmplContent,funcSrc,func,etc){this.process=function(context,flags){if(context==null){context={}}if(context._MODIFIERS==null){context._MODIFIERS={}}if(context.defined==null){context.defined=function(str){return(context[str]!=undefined)}}for(var k in etc.modifierDef){if(context._MODIFIERS[k]==null){context._MODIFIERS[k]=etc.modifierDef[k]}}if(flags==null){flags={}}var resultArr=[];var resultOut={write:function(m){resultArr.push(m)}};try{func(resultOut,context,flags)}catch(e){if(flags.throwExceptions==true){throw e}var result=new String(resultArr.join("")+"[ERROR: template: <pre>"+exceptionDetails(e)+"</pre>]");result.exception=e;return result}return resultArr.join("")};this.name=tmplName;this.source=tmplContent;this.sourceFunc=funcSrc;this.toString=function(){return"TrimPath.Template ["+tmplName+"]"}};TrimPath.parseTemplate_etc.ParseError=function(name,line,message){this.name=name;this.line=line;this.message=message};TrimPath.parseTemplate_etc.ParseError.prototype.toString=function(){return("TrimPath template ParseError in "+this.name+": line "+this.line+", "+this.message)};var parse=function(body,tmplName,etc){body=cleanWhiteSpace(body);var funcText=["var TrimPath_Template_TEMP = function(_OUT, _CONTEXT, _FLAGS) { with (_CONTEXT) {"];var state={stack:[],line:1};var endStmtPrev=-1;while(endStmtPrev+1<body.length){var begStmt=endStmtPrev;begStmt=body.indexOf("{",begStmt+1);while(begStmt>=0){var endStmt=body.indexOf("}",begStmt+1);var stmt=body.substring(begStmt,endStmt);var blockrx=stmt.match(/^\{(cdata|minify|eval)/);if(blockrx){var blockType=blockrx[1];var blockMarkerBeg=begStmt+blockType.length+1;var blockMarkerEnd=body.indexOf("}",blockMarkerBeg);if(blockMarkerEnd>=0){var blockMarker;if(blockMarkerEnd-blockMarkerBeg<=0){blockMarker="{/"+blockType+"}"}else{blockMarker=body.substring(blockMarkerBeg+1,blockMarkerEnd)}var blockEnd=body.indexOf(blockMarker,blockMarkerEnd+1);if(blockEnd>=0){emitSectionText(body.substring(endStmtPrev+1,begStmt),funcText);var blockText=body.substring(blockMarkerEnd+1,blockEnd);if(blockType=="cdata"){emitText(blockText,funcText)}else{if(blockType=="minify"){emitText(scrubWhiteSpace(blockText),funcText)}else{if(blockType=="eval"){if(blockText!=null&&blockText.length>0){funcText.push("_OUT.write( (function() { "+blockText+" })() );")}}}}begStmt=endStmtPrev=blockEnd+blockMarker.length-1}}}else{if(body.charAt(begStmt-1)!="$"&&body.charAt(begStmt-1)!="\\"){var offset=(body.charAt(begStmt+1)=="/"?2:1);if(body.substring(begStmt+offset,begStmt+10+offset).search(TrimPath.parseTemplate_etc.statementTag)==0){break}}}begStmt=body.indexOf("{",begStmt+1)}if(begStmt<0){break}var endStmt=body.indexOf("}",begStmt+1);if(endStmt<0){break}emitSectionText(body.substring(endStmtPrev+1,begStmt),funcText);emitStatement(body.substring(begStmt,endStmt+1),state,funcText,tmplName,etc);endStmtPrev=endStmt}emitSectionText(body.substring(endStmtPrev+1),funcText);if(state.stack.length!=0){throw new etc.ParseError(tmplName,state.line,"unclosed, unmatched statement(s): "+state.stack.join(","))}funcText.push("}}; TrimPath_Template_TEMP");return funcText.join("")};var emitStatement=function(stmtStr,state,funcText,tmplName,etc){var parts=stmtStr.slice(1,-1).split(" ");var stmt=etc.statementDef[parts[0]];if(stmt==null){emitSectionText(stmtStr,funcText);return}if(stmt.delta<0){if(state.stack.length<=0){throw new etc.ParseError(tmplName,state.line,"close tag does not match any previous statement: "+stmtStr)}state.stack.pop()}if(stmt.delta>0){state.stack.push(stmtStr)}if(stmt.paramMin!=null&&stmt.paramMin>=parts.length){throw new etc.ParseError(tmplName,state.line,"statement needs more parameters: "+stmtStr)}if(stmt.prefixFunc!=null){funcText.push(stmt.prefixFunc(parts,state,tmplName,etc))}else{funcText.push(stmt.prefix)}if(stmt.suffix!=null){if(parts.length<=1){if(stmt.paramDefault!=null){funcText.push(stmt.paramDefault)}}else{for(var i=1;i<parts.length;i++){if(i>1){funcText.push(" ")}funcText.push(parts[i])}}funcText.push(stmt.suffix)}};var emitSectionText=function(text,funcText){if(text.length<=0){return}var nlPrefix=0;var nlSuffix=text.length-1;while(nlPrefix<text.length&&(text.charAt(nlPrefix)=="\n")){nlPrefix++}while(nlSuffix>=0&&(text.charAt(nlSuffix)==" "||text.charAt(nlSuffix)=="\t")){nlSuffix--}if(nlSuffix<nlPrefix){nlSuffix=nlPrefix}if(nlPrefix>0){funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');var s=text.substring(0,nlPrefix).replace("\n","\\n");if(s.charAt(s.length-1)=="\n"){s=s.substring(0,s.length-1)}funcText.push(s);funcText.push('");')}var lines=text.substring(nlPrefix,nlSuffix+1).split("\n");for(var i=0;i<lines.length;i++){emitSectionTextLine(lines[i],funcText);if(i<lines.length-1){funcText.push('_OUT.write("\\n");\n')}}if(nlSuffix+1<text.length){funcText.push('if (_FLAGS.keepWhitespace == true) _OUT.write("');var s=text.substring(nlSuffix+1).replace("\n","\\n");if(s.charAt(s.length-1)=="\n"){s=s.substring(0,s.length-1)}funcText.push(s);funcText.push('");')}};var emitSectionTextLine=function(line,funcText){var endMarkPrev="}";var endExprPrev=-1;while(endExprPrev+endMarkPrev.length<line.length){var begMark="${",endMark="}";var begExpr=line.indexOf(begMark,endExprPrev+endMarkPrev.length);if(begExpr<0){break}if(line.charAt(begExpr+2)=="%"){begMark="${%";endMark="%}"}var endExpr=line.indexOf(endMark,begExpr+begMark.length);if(endExpr<0){break}emitText(line.substring(endExprPrev+endMarkPrev.length,begExpr),funcText);var exprArr=line.substring(begExpr+begMark.length,endExpr).replace(/\|\|/g,"#@@#").split("|");for(var k in exprArr){if(exprArr[k].replace){exprArr[k]=exprArr[k].replace(/#@@#/g,"||")}}funcText.push("_OUT.write(");emitExpression(exprArr,exprArr.length-1,funcText);funcText.push(");");endExprPrev=endExpr;endMarkPrev=endMark}emitText(line.substring(endExprPrev+endMarkPrev.length),funcText)};var emitText=function(text,funcText){if(text==null||text.length<=0){return}text=text.replace(/\\/g,"\\\\");text=text.replace(/\n/g,"\\n");text=text.replace(/"/g,'\\"');funcText.push('_OUT.write("');funcText.push(text);funcText.push('");')};var emitExpression=function(exprArr,index,funcText){var expr=exprArr[index];if(index<=0){funcText.push(expr);return}var parts=expr.split(":");funcText.push('_MODIFIERS["');funcText.push(parts[0]);funcText.push('"](');emitExpression(exprArr,index-1,funcText);if(parts.length>1){funcText.push(",");funcText.push(parts[1])}funcText.push(")")};var cleanWhiteSpace=function(result){result=result.replace(/\t/g," ");result=result.replace(/\r\n/g,"\n");result=result.replace(/\r/g,"\n");result=result.replace(/^(\s*\S*(\s+\S+)*)\s*$/,"$1");return result};var scrubWhiteSpace=function(result){result=result.replace(/^\s+/g,"");result=result.replace(/\s+$/g,"");result=result.replace(/\s+/g," ");result=result.replace(/^(\s*\S*(\s+\S+)*)\s*$/,"$1");return result};TrimPath.parseDOMTemplate=function(elementId,optDocument,optEtc){if(optDocument==null){optDocument=document}var element=optDocument.getElementById(elementId);var content=element.value;if(content==null){content=element.innerHTML}content=content.replace(/</g,"<").replace(/>/g,">");return TrimPath.parseTemplate(content,elementId,optEtc)};TrimPath.processDOMTemplate=function(elementId,context,optFlags,optDocument,optEtc){return TrimPath.parseDOMTemplate(elementId,optDocument,optEtc).process(context,optFlags)}})();GravityRD.bind(function use_private_scope(){ /*! * @preserve Qwery - A Blazing Fast query selector engine * https://github.com/ded/qwery * copyright Dustin Diaz 2012 * MIT License */ (function(name,context,definition){if(typeof module!="undefined"&&module.exports){module.exports=definition()}else{if(typeof define=="function"&&define.amd){define(definition)}else{context[name]=definition()}}})("qwery",this,function(){var doc=document,html=doc.documentElement,byClass="getElementsByClassName",byTag="getElementsByTagName",qSA="querySelectorAll",useNativeQSA="useNativeQSA",tagName="tagName",nodeType="nodeType",select,id=/#([\w\-]+)/,clas=/\.[\w\-]+/g,idOnly=/^#([\w\-]+)$/,classOnly=/^\.([\w\-]+)$/,tagOnly=/^([\w\-]+)$/,tagAndOrClass=/^([\w]+)?\.([\w\-]+)$/,splittable=/(^|,)\s*[>~+]/,normalizr=/^\s+|\s*([,\s\+\~>]|$)\s*/g,splitters=/[\s\>\+\~]/,splittersMore=/(?![\s\w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^'"]*\]|[\s\w\+\-]*\))/,specialChars=/([.*+?\^=!:${}()|\[\]\/\\])/g,simple=/^(\*|[a-z0-9]+)?(?:([\.\#]+[\w\-\.#]+)?)/,attr=/\[([\w\-]+)(?:([\|\^\$\*\~]?\=)['"]?([ \w\-\/\?\&\=\:\.\(\)\!,@#%<>\{\}\$\*\^]+)["']?)?\]/,pseudo=/:([\w\-]+)(\(['"]?([^()]+)['"]?\))?/,easy=new RegExp(idOnly.source+"|"+tagOnly.source+"|"+classOnly.source),dividers=new RegExp("("+splitters.source+")"+splittersMore.source,"g"),tokenizr=new RegExp(splitters.source+splittersMore.source),chunker=new RegExp(simple.source+"("+attr.source+")?("+pseudo.source+")?");var walker={" ":function(node){return node&&node!==html&&node.parentNode},">":function(node,contestant){return node&&node.parentNode==contestant.parentNode&&node.parentNode},"~":function(node){return node&&node.previousSibling},"+":function(node,contestant,p1,p2){if(!node){return false}return(p1=previous(node))&&(p2=previous(contestant))&&p1==p2&&p1}};function cache(){this.c={}}cache.prototype={g:function(k){return this.c[k]||undefined},s:function(k,v,r){v=r?new RegExp(v):v;return(this.c[k]=v)}};var classCache=new cache(),cleanCache=new cache(),attrCache=new cache(),tokenCache=new cache();function classRegex(c){return classCache.g(c)||classCache.s(c,"(^|\\s+)"+c+"(\\s+|$)",1)}function each(a,fn){var i=0,l=a.length;for(;i<l;i++){fn(a[i])}}function flatten(ar){for(var r=[],i=0,l=ar.length;i<l;++i){arrayLike(ar[i])?(r=r.concat(ar[i])):(r[r.length]=ar[i])}return r}function arrayify(ar){var i=0,l=ar.length,r=[];for(;i<l;i++){r[i]=ar[i]}return r}function previous(n){while(n=n.previousSibling){if(n[nodeType]==1){break}}return n}function q(query){return query.match(chunker)}function interpret(whole,tag,idsAndClasses,wholeAttribute,attribute,qualifier,value,wholePseudo,pseudo,wholePseudoVal,pseudoVal){var i,m,k,o,classes;if(this[nodeType]!==1){return false}if(tag&&tag!=="*"&&this[tagName]&&this[tagName].toLowerCase()!==tag){return false}if(idsAndClasses&&(m=idsAndClasses.match(id))&&m[1]!==this.id){return false}if(idsAndClasses&&(classes=idsAndClasses.match(clas))){for(i=classes.length;i--;){if(!classRegex(classes[i].slice(1)).test(this.className)){return false}}}if(pseudo&&qwery.pseudos[pseudo]&&!qwery.pseudos[pseudo](this,pseudoVal)){return false}if(wholeAttribute&&!value){o=this.attributes;for(k in o){if(Object.prototype.hasOwnProperty.call(o,k)&&(o[k].name||k)==attribute){return this}}}if(wholeAttribute&&!checkAttr(qualifier,getAttr(this,attribute)||"",value)){return false}return this}function clean(s){return cleanCache.g(s)||cleanCache.s(s,s.replace(specialChars,"\\$1"))}function checkAttr(qualify,actual,val){switch(qualify){case"=":return actual==val;case"^=":return actual.match(attrCache.g("^="+val)||attrCache.s("^="+val,"^"+clean(val),1));case"$=":return actual.match(attrCache.g("$="+val)||attrCache.s("$="+val,clean(val)+"$",1));case"*=":return actual.match(attrCache.g(val)||attrCache.s(val,clean(val),1));case"~=":return actual.match(attrCache.g("~="+val)||attrCache.s("~="+val,"(?:^|\\s+)"+clean(val)+"(?:\\s+|$)",1));case"|=":return actual.match(attrCache.g("|="+val)||attrCache.s("|="+val,"^"+clean(val)+"(-|$)",1))}return 0}function _qwery(selector,_root){var r=[],ret=[],i,l,m,token,tag,els,intr,item,root=_root,tokens=tokenCache.g(selector)||tokenCache.s(selector,selector.split(tokenizr)),dividedTokens=selector.match(dividers);if(!tokens.length){return r}token=(tokens=tokens.slice(0)).pop();if(tokens.length&&(m=tokens[tokens.length-1].match(idOnly))){root=byId(_root,m[1])}if(!root){return r}intr=q(token);els=root!==_root&&root[nodeType]!==9&÷dTokens&&/^[+~]$/.test(dividedTokens[dividedTokens.length-1])?function(r){while(root=root.nextSibling){root[nodeType]==1&&(intr[1]?intr[1]==root[tagName].toLowerCase():1)&&(r[r.length]=root)}return r}([]):root[byTag](intr[1]||"*");for(i=0,l=els.length;i<l;i++){if(item=interpret.apply(els[i],intr)){r[r.length]=item}}if(!tokens.length){return r}each(r,function(e){if(ancestorMatch(e,tokens,dividedTokens)){ret[ret.length]=e}});return ret}function is(el,selector,root){if(isNode(selector)){return el==selector}if(arrayLike(selector)){return !!~flatten(selector).indexOf(el)}var selectors=selector.split(","),tokens,dividedTokens;while(selector=selectors.pop()){tokens=tokenCache.g(selector)||tokenCache.s(selector,selector.split(tokenizr));dividedTokens=selector.match(dividers);tokens=tokens.slice(0);if(interpret.apply(el,q(tokens.pop()))&&(!tokens.length||ancestorMatch(el,tokens,dividedTokens,root))){return true}}return false}function ancestorMatch(el,tokens,dividedTokens,root){var cand;function crawl(e,i,p){while(p=walker[dividedTokens[i]](p,e)){if(isNode(p)&&(interpret.apply(p,q(tokens[i])))){if(i){if(cand=crawl(p,i-1,p)){return cand}}else{return p}}}}return(cand=crawl(el,tokens.length-1,el))&&(!root||isAncestor(cand,root))}function isNode(el,t){return el&&typeof el==="object"&&(t=el[nodeType])&&(t==1||t==9)}function uniq(ar){var a=[],i,j;o:for(i=0;i<ar.length;++i){for(j=0;j<a.length;++j){if(a[j]==ar[i]){continue o}}a[a.length]=ar[i]}return a}function arrayLike(o){return(typeof o==="object"&&isFinite(o.length))}function normalizeRoot(root){if(!root){return doc}if(typeof root=="string"){return qwery(root)[0]}if(!root[nodeType]&&arrayLike(root)){return root[0]}return root}function byId(root,id,el){return root[nodeType]===9?root.getElementById(id):root.ownerDocument&&(((el=root.ownerDocument.getElementById(id))&&isAncestor(el,root)&&el)||(!isAncestor(root,root.ownerDocument)&&select('[id="'+id+'"]',root)[0]))}function qwery(selector,_root){var m,el,root=normalizeRoot(_root);if(!root||!selector){return[]}if(selector===window||isNode(selector)){return !_root||(selector!==window&&isNode(root)&&isAncestor(selector,root))?[selector]:[]}if(selector&&arrayLike(selector)){return flatten(selector)}if(m=selector.match(easy)){if(m[1]){return(el=byId(root,m[1]))?[el]:[]}if(m[2]){return arrayify(root[byTag](m[2]))}if(hasByClass&&m[3]){return arrayify(root[byClass](m[3]))}}return select(selector,root)}function collectSelector(root,collector){return function(s){var oid,nid;if(splittable.test(s)){if(root[nodeType]!==9){if(!(nid=oid=root.getAttribute("id"))){root.setAttribute("id",nid="__qwerymeupscotty")}s='[id="'+nid+'"]'+s;collector(root.parentNode||root,s,true);oid||root.removeAttribute("id")}return}s.length&&collector(root,s,false)}}var isAncestor="compareDocumentPosition" in html?function(element,container){return(container.compareDocumentPosition(element)&16)==16}:"contains" in html?function(element,container){container=container[nodeType]===9||container==window?html:container;return container!==element&&container.contains(element)}:function(element,container){while(element=element.parentNode){if(element===container){return 1}}return 0},getAttr=function(){var e=doc.createElement("p");return((e.innerHTML='<a href="#x">x</a>')&&e.firstChild.getAttribute("href")!="#x")?function(e,a){return a==="class"?e.className:(a==="href"||a==="src")?e.getAttribute(a,2):e.getAttribute(a)}:function(e,a){return e.getAttribute(a)}}(),hasByClass=!!doc[byClass],hasQSA=doc.querySelector&&doc[qSA],selectQSA=function(selector,root){var result=[],ss,e;try{if(root[nodeType]===9||!splittable.test(selector)){return arrayify(root[qSA](selector))}each(ss=selector.split(","),collectSelector(root,function(ctx,s){e=ctx[qSA](s);if(e.length==1){result[result.length]=e.item(0)}else{if(e.length){result=result.concat(arrayify(e))}}}));return ss.length>1&&result.length>1?uniq(result):result}catch(ex){}return selectNonNative(selector,root)},selectNonNative=function(selector,root){var result=[],items,m,i,l,r,ss;selector=selector.replace(normalizr,"$1");if(m=selector.match(tagAndOrClass)){r=classRegex(m[2]);items=root[byTag](m[1]||"*");for(i=0,l=items.length;i<l;i++){if(r.test(items[i].className)){result[result.length]=items[i]}}return result}each(ss=selector.split(","),collectSelector(root,function(ctx,s,rewrite){r=_qwery(s,ctx);for(i=0,l=r.length;i<l;i++){if(ctx[nodeType]===9||rewrite||isAncestor(r[i],root)){result[result.length]=r[i]}}}));return ss.length>1&&result.length>1?uniq(result):result},configure=function(options){if(typeof options[useNativeQSA]!=="undefined"){select=!options[useNativeQSA]?selectNonNative:hasQSA?selectQSA:selectNonNative}};configure({useNativeQSA:true});qwery.configure=configure;qwery.uniq=uniq;qwery.is=is;qwery.pseudos={};return qwery}); /*! * Bonzo: DOM Utility (c) Dustin Diaz 2012 * https://github.com/ded/bonzo * License MIT */ (function(name,context,definition){if(typeof module!="undefined"&&module.exports){module.exports=definition()}else{if(typeof define=="function"&&define.amd){define(definition)}else{context[name]=definition()}}})("bonzo",this,function(){var win=window,doc=win.document,html=doc.documentElement,parentNode="parentNode",specialAttributes=/^(checked|value|selected|disabled)$/i,specialTags=/^(select|fieldset|table|tbody|tfoot|td|tr|colgroup)$/i,simpleScriptTagRe=/\s*<script +src=['"]([^'"]+)['"]>/,table=["<table>","</table>",1],td=["<table><tbody><tr>","</tr></tbody></table>",3],option=["<select>","</select>",1],noscope=["_","",0,1],tagMap={thead:table,tbody:table,tfoot:table,colgroup:table,caption:table,tr:["<table><tbody>","</tbody></table>",2],th:td,td:td,col:["<table><colgroup>","</colgroup></table>",2],fieldset:["<form>","</form>",1],legend:["<form><fieldset>","</fieldset></form>",2],option:option,optgroup:option,script:noscope,style:noscope,link:noscope,param:noscope,base:noscope},stateAttributes=/^(checked|selected|disabled)$/,hasClass,addClass,removeClass,uidMap={},uuids=0,digit=/^-?[\d\.]+$/,dattr=/^data-(.+)$/,px="px",setAttribute="setAttribute",getAttribute="getAttribute",features=function(){var e=doc.createElement("p");return{transform:function(){var props=["transform","webkitTransform","MozTransform","OTransform","msTransform"],i;for(i=0;i<props.length;i++){if(props[i] in e.style){return props[i]}}}(),classList:"classList" in e}}(),whitespaceRegex=/\s+/,toString=String.prototype.toString,unitless={lineHeight:1,zoom:1,zIndex:1,opacity:1,boxFlex:1,WebkitBoxFlex:1,MozBoxFlex:1},query=doc.querySelectorAll&&function(selector){return doc.querySelectorAll(selector)};function getStyle(el,property){var value=null,computed=doc.defaultView.getComputedStyle(el,"");computed&&(value=computed[property]);return el.style[property]||value}function isNode(node){return node&&node.nodeName&&(node.nodeType==1||node.nodeType==11)}function normalize(node,host,clone){var i,l,ret;if(typeof node=="string"){return bonzo.create(node)}if(isNode(node)){node=[node]}if(clone){ret=[];for(i=0,l=node.length;i<l;i++){ret[i]=cloneNode(host,node[i])}return ret}return node}function classReg(c){return new RegExp("(^|\\s+)"+c+"(\\s+|$)")}function each(ar,fn,opt_scope,opt_rev){var ind,i=0,l=ar.length;for(;i<l;i++){ind=opt_rev?ar.length-i-1:i;fn.call(opt_scope||ar[ind],ar[ind],ind,ar)}return ar}function deepEach(ar,fn,opt_scope){for(var i=0,l=ar.length;i<l;i++){if(isNode(ar[i])){deepEach(ar[i].childNodes,fn,opt_scope);fn.call(opt_scope||ar[i],ar[i],i,ar)}}return ar}function camelize(s){return s.replace(/-(.)/g,function(m,m1){return m1.toUpperCase()})}function decamelize(s){return s?s.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase():s}function data(el){el[getAttribute]("data-node-uid")||el[setAttribute]("data-node-uid",++uuids);var uid=el[getAttribute]("data-node-uid");return uidMap[uid]||(uidMap[uid]={})}function clearData(el){var uid=el[getAttribute]("data-node-uid");if(uid){delete uidMap[uid]}}function dataValue(d){var f;try{return(d===null||d===undefined)?undefined:d==="true"?true:d==="false"?false:d==="null"?null:(f=parseFloat(d))==d?f:d}catch(e){}return undefined}function some(ar,fn,opt_scope){for(var i=0,j=ar.length;i<j;++i){if(fn.call(opt_scope||null,ar[i],i,ar)){return true}}return false}function styleProperty(p){(p=="transform"&&(p=features.transform))||(/^transform-?[Oo]rigin$/.test(p)&&(p=features.transform+"Origin"));return p?camelize(p):null}function insert(target,host,fn,rev){var i=0,self=host||this,r=[],nodes=query&&typeof target=="string"&&target.charAt(0)!="<"?query(target):target;each(normalize(nodes),function(t,j){each(self,function(el){fn(t,r[i++]=j>0?cloneNode(self,el):el)},null,rev)},this,rev);self.length=i;each(r,function(e){self[--i]=e},null,!rev);return self}function xy(el,x,y){var $el=bonzo(el),style=$el.css("position"),offset=$el.offset(),rel="relative",isRel=style==rel,delta=[parseInt($el.css("left"),10),parseInt($el.css("top"),10)];if(style=="static"){$el.css("position",rel);style=rel}isNaN(delta[0])&&(delta[0]=isRel?0:el.offsetLeft);isNaN(delta[1])&&(delta[1]=isRel?0:el.offsetTop);x!=null&&(el.style.left=x-offset.left+delta[0]+px);y!=null&&(el.style.top=y-offset.top+delta[1]+px)}if(features.classList){hasClass=function(el,c){return el.classList.contains(c)};addClass=function(el,c){el.classList.add(c)};removeClass=function(el,c){el.classList.remove(c)}}else{hasClass=function(el,c){return classReg(c).test(el.className)};addClass=function(el,c){el.className=(el.className+" "+c).trim()};removeClass=function(el,c){el.className=(el.className.replace(classReg(c)," ")).trim()}}function setter(el,v){return typeof v=="function"?v.call(el,el):v}function scroll(x,y,type){var el=this[0];if(!el){return this}if(x==null&&y==null){return(isBody(el)?getWindowScroll():{x:el.scrollLeft,y:el.scrollTop})[type]}if(isBody(el)){win.scrollTo(x,y)}else{x!=null&&(el.scrollLeft=x);y!=null&&(el.scrollTop=y)}return this}function Bonzo(elements){this.length=0;if(elements){elements=typeof elements!=="string"&&!elements.nodeType&&typeof elements.length!=="undefined"?elements:[elements];this.length=elements.length;for(var i=0;i<elements.length;i++){this[i]=elements[i]}}}Bonzo.prototype={get:function(index){return this[index]||null},each:function(fn,opt_scope){return each(this,fn,opt_scope)},deepEach:function(fn,opt_scope){return deepEach(this,fn,opt_scope)},map:function(fn,opt_reject){var m=[],n,i;for(i=0;i<this.length;i++){n=fn.call(this,this[i],i);opt_reject?(opt_reject(n)&&m.push(n)):m.push(n)}return m},html:function(h,opt_text){var method=opt_text?"textContent":"innerHTML",that=this,append=function(el,i){each(normalize(h,that,i),function(node){el.appendChild(node)})},updateElement=function(el,i){try{if(opt_text||(typeof h=="string"&&!specialTags.test(el.tagName))){return el[method]=h}}catch(e){}append(el,i)};return typeof h!="undefined"?this.empty().each(updateElement):this[0]?this[0][method]:""},text:function(opt_text){return this.html(opt_text,true)},append:function(node){var that=this;return this.each(function(el,i){each(normalize(node,that,i),function(i){el.appendChild(i)})})},prepend:function(node){var that=this;return this.each(function(el,i){var first=el.firstChild;each(normalize(node,that,i),function(i){el.insertBefore(i,first)})})},appendTo:function(target,opt_host){return insert.call(this,target,opt_host,function(t,el){t.appendChild(el)})},prependTo:function(target,opt_host){return insert.call(this,target,opt_host,function(t,el){t.insertBefore(el,t.firstChild)},1)},before:function(node){var that=this;return this.each(function(el,i){each(normalize(node,that,i),function(i){el[parentNode].insertBefore(i,el)})})},after:function(node){var that=this;return this.each(function(el,i){each(normalize(node,that,i),function(i){el[parentNode].insertBefore(i,el.nextSibling)},null,1)})},insertBefore:function(target,opt_host){return insert.call(this,target,opt_host,function(t,el){t[parentNode].insertBefore(el,t)})},insertAfter:function(target,opt_host){return insert.call(this,target,opt_host,function(t,el){var sibling=t.nextSibling;sibling?t[parentNode].insertBefore(el,sibling):t[parentNode].appendChild(el)},1)},replaceWith:function(node){var that=this;return this.each(function(el,i){each(normalize(node,that,i),function(i){el[parentNode]&&el[parentNode].replaceChild(i,el)})})},clone:function(opt_host){var ret=[],l,i;for(i=0,l=this.length;i<l;i++){ret[i]=cloneNode(opt_host||this,this[i])}return bonzo(ret)},addClass:function(c){c=toString.call(c).split(whitespaceRegex);return this.each(function(el){each(c,function(c){if(c&&!hasClass(el,setter(el,c))){addClass(el,setter(el,c))}})})},removeClass:function(c){c=toString.call(c).split(whitespaceRegex);return this.each(function(el){each(c,function(c){if(c&&hasClass(el,setter(el,c))){removeClass(el,setter(el,c))}})})},hasClass:function(c){c=toString.call(c).split(whitespaceRegex);return some(this,function(el){return some(c,function(c){return c&&hasClass(el,c)})})},toggleClass:function(c,opt_condition){c=toString.call(c).split(whitespaceRegex);return this.each(function(el){each(c,function(c){if(c){typeof opt_condition!=="undefined"?opt_condition?!hasClass(el,c)&&addClass(el,c):removeClass(el,c):hasClass(el,c)?removeClass(el,c):addClass(el,c)}})})},show:function(opt_type){opt_type=typeof opt_type=="string"?opt_type:"";return this.each(function(el){el.style.display=opt_type})},hide:function(){return this.each(function(el){el.style.display="none"})},toggle:function(opt_callback,opt_type){opt_type=typeof opt_type=="string"?opt_type:"";typeof opt_callback!="function"&&(opt_callback=null);return this.each(function(el){el.style.display=(el.offsetWidth||el.offsetHeight)?"none":opt_type;opt_callback&&opt_callback.call(el)})},first:function(){return bonzo(this.length?this[0]:[])},last:function(){return bonzo(this.length?this[this.length-1]:[])},next:function(){return this.related("nextSibling")},previous:function(){return this.related("previousSibling")},parent:function(){return this.related(parentNode)},related:function(method){return bonzo(this.map(function(el){el=el[method];while(el&&el.nodeType!==1){el=el[method]}return el||0},function(el){return el}))},focus:function(){this.length&&this[0].focus();return this},blur:function(){this.length&&this[0].blur();return this},css:function(o,opt_v){var p,iter=o;if(opt_v===undefined&&typeof o=="string"){opt_v=this[0];if(!opt_v){return null}if(opt_v===doc||opt_v===win){p=(opt_v===doc)?bonzo.doc():bonzo.viewport();return o=="width"?p.width:o=="height"?p.height:""}return(o=styleProperty(o))?getStyle(opt_v,o):null}if(typeof o=="string"){iter={};iter[o]=opt_v}function fn(el,p,v){for(var k in iter){if(iter.hasOwnProperty(k)){v=iter[k];(p=styleProperty(k))&&digit.test(v)&&!(p in unitless)&&(v+=px);try{el.style[p]=setter(el,v)}catch(e){}}}}return this.each(fn)},offset:function(opt_x,opt_y){if(opt_x&&typeof opt_x=="object"&&(typeof opt_x.top=="number"||typeof opt_x.left=="number")){return this.each(function(el){xy(el,opt_x.left,opt_x.top)})}else{if(typeof opt_x=="number"||typeof opt_y=="number"){return this.each(function(el){xy(el,opt_x,opt_y)})}}if(!this[0]){return{top:0,left:0,height:0,width:0}}var el=this[0],de=el.ownerDocument.documentElement,bcr=el.getBoundingClientRect(),scroll=getWindowScroll(),width=el.offsetWidth,height=el.offsetHeight,top=bcr.top+scroll.y-Math.max(0,de&&de.clientTop,doc.body.clientTop),left=bcr.left+scroll.x-Math.max(0,de&&de.clientLeft,doc.body.clientLeft);return{top:top,left:left,height:height,width:width}},dim:function(){if(!this.length){return{height:0,width:0}}var el=this[0],de=el.nodeType==9&&el.documentElement,orig=!de&&!!el.style&&!el.offsetWidth&&!el.offsetHeight?function(t){var s={position:el.style.position||"",visibility:el.style.visibility||"",display:el.style.display||""};t.first().css({position:"absolute",visibility:"hidden",display:"block"});return s}(this):null,width=de?Math.max(el.body.scrollWidth,el.body.offsetWidth,de.scrollWidth,de.offsetWidth,de.clientWidth):el.offsetWidth,height=de?Math.max(el.body.scrollHeight,el.body.offsetHeight,de.scrollHeight,de.offsetHeight,de.clientHeight):el.offsetHeight;orig&&this.first().css(orig);return{height:height,width:width}},attr:function(k,opt_v){var el=this[0],n;if(typeof k!="string"&&!(k instanceof String)){for(n in k){k.hasOwnProperty(n)&&this.attr(n,k[n])}return this}return typeof opt_v=="undefined"?!el?null:specialAttributes.test(k)?stateAttributes.test(k)&&typeof el[k]=="string"?true:el[k]:el[getAttribute](k):this.each(function(el){specialAttributes.test(k)?(el[k]=setter(el,opt_v)):el[setAttribute](k,setter(el,opt_v))})},removeAttr:function(k){return this.each(function(el){stateAttributes.test(k)?(el[k]=false):el.removeAttribute(k)})},val:function(s){return(typeof s=="string"||typeof s=="number")?this.attr("value",s):this.length?this[0].value:null},data:function(opt_k,opt_v){var el=this[0],o,m;if(typeof opt_v==="undefined"){if(!el){return null}o=data(el);if(typeof opt_k==="undefined"){each(el.attributes,function(a){(m=(""+a.name).match(dattr))&&(o[camelize(m[1])]=dataValue(a.value))});return o}else{if(typeof o[opt_k]==="undefined"){o[opt_k]=dataValue(this.attr("data-"+decamelize(opt_k)))}return o[opt_k]}}else{return this.each(function(el){data(el)[opt_k]=opt_v})}},remove:function(){this.deepEach(clearData);return this.detach()},empty:function(){return this.each(function(el){deepEach(el.childNodes,clearData);while(el.firstChild){el.removeChild(el.firstChild)}})},detach:function(){return this.each(function(el){el[parentNode]&&el[parentNode].removeChild(el)})},scrollTop:function(y){return scroll.call(this,null,y,"y")},scrollLeft:function(x){return scroll.call(this,x,null,"x")}};function cloneNode(host,el){var c=el.cloneNode(true),cloneElems,elElems,i;if(host.$&&typeof host.cloneEvents=="function"){host.$(c).cloneEvents(el);cloneElems=host.$(c).find("*");elElems=host.$(el).find("*");for(i=0;i<elElems.length;i++){host.$(cloneElems[i]).cloneEvents(elElems[i])}}return c}function isBody(element){return element===win||(/^(?:body|html)$/i).test(element.tagName)}function getWindowScroll(){return{x:win.pageXOffset||html.scrollLeft,y:win.pageYOffset||html.scrollTop}}function createScriptFromHtml(html){var scriptEl=document.createElement("script"),matches=html.match(simpleScriptTagRe);scriptEl.src=matches[1];return scriptEl}function bonzo(els){return new Bonzo(els)}bonzo.setQueryEngine=function(q){query=q;delete bonzo.setQueryEngine};bonzo.aug=function(o,target){for(var k in o){o.hasOwnProperty(k)&&((target||Bonzo.prototype)[k]=o[k])}};bonzo.create=function(node){return typeof node=="string"&&node!==""?function(){if(simpleScriptTagRe.test(node)){return[createScriptFromHtml(node)]}var tag=node.match(/^\s*<([^\s>]+)/),el=doc.createElement("div"),els=[],p=tag?tagMap[tag[1].toLowerCase()]:null,dep=p?p[2]+1:1,ns=p&&p[3],pn=parentNode;el.innerHTML=p?(p[0]+node+p[1]):node;while(dep--){el=el.firstChild}if(ns&&el&&el.nodeType!==1){el=el.nextSibling}do{if(!tag||el.nodeType==1){els.push(el)}}while(el=el.nextSibling);each(els,function(el){el[pn]&&el[pn].removeChild(el)});return els}():isNode(node)?[node.cloneNode(true)]:[]};bonzo.doc=function(){var vp=bonzo.viewport();return{width:Math.max(doc.body.scrollWidth,html.scrollWidth,vp.width),height:Math.max(doc.body.scrollHeight,html.scrollHeight,vp.height)}};bonzo.firstChild=function(el){for(var c=el.childNodes,i=0,j=(c&&c.length)||0,e;i<j;i++){if(c[i].nodeType===1){e=c[j=i]}}return e};bonzo.viewport=function(){return{width:win.innerWidth,height:win.innerHeight}};bonzo.isAncestor="compareDocumentPosition" in html?function(container,element){return(container.compareDocumentPosition(element)&16)==16}:function(container,element){return container!==element&&container.contains(element)};return bonzo})},privatescope)();(function(){var GravityRD_RL=GravityRD.Base.extend({__public__:["start"],start:function(){var $=GravityRD.CustomConfig.getDomEngine();$("body").css({"margin-top":"32px"});GravityRD.CustomConfig.applyCss(["#gr_rltest .error { border: 0px solid; color: #D8000C; background-color: #FFBABA; margin:1px 1px; padding: 3px 3px; vertical-align:middle;}","#gr_rltest {height:20px;border:1px solid;position:fixed;z-index:20000;top:0;left:1;right:1;margin: 1px 1px; padding: 3px 0; background-color : #222222; vertical-align: middle; color:#f7D900;}","#gr_rltest a,img {text-decoration:none;color:#f7D900;vertical-align:middle;}"]);$("body").append('<div id="gr_rltest">  <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsSAAALEgHS3X78AAAABGdBTUEAALGOfPtRkwAAACBjSFJNAAB6JQAAgIMAAPn/AACA6QAAdTAAAOpgAAA6mAAAF2+SX8VGAAABsUlEQVR42mL8//8/AyUAIIAYcUmsC2boB1IFUO6EoLUMhdjUAQQQLs0OQPz/w5WC/+9PGvwHsUFi2NQCBBATDkPmawYnMLy5MIHh7Y0LDGq2EDFsCgECiAmL7Q1cYgoK/BIPGC6tZ2C4tImBQVCagYGTj0EBJIeuHiCAmNA0KwCpfL2oAAZWpgNwcTYOBgYdJzAzH6oGDgACCN0F/SLaDgKSahsYGP4hiQLZMpoMDEJSDAIgNcgaAAKICTnggFSAcQLQgj8PGBiQY/c/xBBjdzAvADlAAQKICT3guLiBtv9lwHABCPPwMzComwugBChAADEhB5yyA9Dmvx8gGrC4AIRVtD4wcAoIwAMUIIAYoYFy3jg9QUBOfwEDwy8g7zcE3z3EAHaNsiFCDIQfXAZqOMYAtInBECCAQC6oBwWcnMkBuC0g/O0dA8OdE0B8Csh+z4AiJ68CDFARcIDWAwQQyIAETT8BSMChGfANaMe3jxAaWY4R6CVdfbDnEgACiAVE/v4uwPDnG6ozuYEBJq8P8YKAKND876jynz9AggcggBihgVFPZmZsBAggRkqzM0CAAQCgU5LNtkF1hAAAAABJRU5ErkJggg==" /> <a href="http://gravityrd.com/"> YUSP TEST MODE</a> <a id="gr_rlmsg" class="error" style="display:none;">Errors detected on page (hover this message or check console for more details).</a></div>');GravityRD.Core.addListener({onUsageError:function(msg){$("#gr_rlmsg").show();$("#gr_rlmsg").attr("title",msg)}})}});GravityRD.register("GravityRD","RL",new GravityRD_RL())})();(function(){var AbstractMatcher=GravityRD.extend(Object,{config:null,constructor:function(c){this.config=c},match:function(){return false},register:function(){}});var RegexpMatcher=GravityRD.extend(AbstractMatcher,{match:function(){var input=this.getInput();var pattern=new RegExp(this.config.pattern);this.matchoutput=pattern.exec(input);return !!this.matchoutput},register:function(){if(this.match()){if(!!this.matchoutput){var register=this.config.registerGroup||this.config.register;if(!!register){for(var i=1;i<this.matchoutput.length;i++){if(!!register[i]){var key=GravityRD.isObject(register[i])&&GravityRD.isString(register[i].key)?register[i].key:register[i];var value=GravityRD.isObject(register[i])&&GravityRD.isFunction(register[i].formatter)?register[i].formatter(this.matchoutput[i]):this.matchoutput[i];GravityRD.Core.setGlobalNameValue(key,value)}}if(!!register[0]){GravityRD.Core.setGlobalNameValue(register[0],"true")}}}}},getInput:function(){return""}});var URLPathRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){return document.location.pathname}});var HostRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){return document.location.host}});var URLRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){return document.location.href}});var URLQueryRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){var s=document.location.search;try{return decodeURIComponent(s)}catch(e){try{return decodeURI(s)}catch(e){return unescape(s)}}}});var CookieRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){return GravityRD.Core.Cookie.getCookie(this.config.cookieName)}});var ReferrerRegexpMatcher=GravityRD.extend(RegexpMatcher,{getInput:function(){return document.referrer}});var SelectorMatcher=GravityRD.extend(AbstractMatcher,{match:function(){this.$=GravityRD.CustomConfig.getDomEngine();this.nodelist=this.$(this.config.selector);return this.nodelist.length>0},register:function(){if(this.match()){var register=this.config.register||{};var regTmp={};for(var key in register){if(!register.hasOwnProperty(key)){continue}if(typeof(key)=="string"){var formatter;var exp;if(GravityRD.isObject(register[key])){exp=register[key].value;formatter=register[key].formatter}else{exp=register[key]}var val=exp.split("::");var regNodeList=this.$(val[0]);GravityRD.each(regNodeList,function(item){regTmp[key]=regTmp[key]||[];var value=null;if(val[1]=="text()"){value=item.childNodes[0].nodeValue}else{if(val[1]=="number()"){var childNodesLength=item.childNodes.length;var i=0;var notFound=true;while(notFound&&i<childNodesLength){if(item.childNodes[i].nodeValue!==null){value=item.childNodes[i].nodeValue.replace(/\s/g,"");if(value!==null){var regex=/([0-9]+)([.,\s][0-9]+)?/;var groups=regex.exec(value);if(groups!==undefined&&groups!==null&&groups.length>0){value=groups[0];notFound=false}else{value=null}if(value!==null){var delimiterChar=value.indexOf(".")>-1?".":value.indexOf(",")>-1?",":null;if(delimiterChar&&(value.length-1)-value.indexOf(delimiterChar)>2){value=value.replace(/[.,]/g,"")}}}}i++}}else{if(val[1]=="content()"){value=item.innerHTML.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gmi,"");value=value.replace(/<[^>]*>/g,"").trim().replace(/\s{2,}/g," ")}else{value=item[val[1]]}}}if(value!==null){if(GravityRD.isFunction(formatter)){value=formatter(value)}regTmp[key].push(value)}})}}for(var key in regTmp){if(typeof(key)=="string"){if(regTmp[key]!=undefined&®Tmp[key].length>0){GravityRD.Core.setGlobalNameValue(key,regTmp[key])}}}}}});var DataLayerMatcher=GravityRD.extend(AbstractMatcher,{match:function(){try{var selector=""+this.config.selector;var value=dataLayer;selector.split(".").forEach(function(element){if(element.indexOf("[")!==-1){var condition=element.substring(1,element.length-1).split("=");var conditionKey=condition[0];var conditionValue=condition[1]||null;var i=0;var notFound=true;while(i<value.length&¬Found){for(var key in value[i]){if(key===conditionKey&&(condition.length===1||value[i][conditionKey]===conditionValue)){notFound=false;value=value[i]}}i++}}else{value=value[element]}});if(value!==undefined&&value!==null){this.value=value;return true}return false}catch(e){return false}},register:function(){if(this.match()){GravityRD.Core.setGlobalNameValue(this.config.name||this.config.varname,this.value)}}});var JSVarMatcher=GravityRD.extend(AbstractMatcher,{match:function(){try{eval("var value = "+this.config.varname+";");if(value!==undefined&&value!==null){this.value=value;return true}return false}catch(e){return false}},register:function(){if(this.match()){GravityRD.Core.setGlobalNameValue(this.config.name||this.config.varname,this.value)}}});var MetaTagMatcher=GravityRD.extend(AbstractMatcher,{match:function(){var metaTags=document.getElementsByTagName("meta");for(var i=0;i<metaTags.length;i++){if(metaTags[i].name===this.config.varname){this.value=metaTags[i].content;return true}}return false},register:function(){if(this.config.register){var register=this.config.register||{};var regTmp={};if(this.match()){for(var key in register){if(!register.hasOwnProperty(key)){continue}if(typeof(key)=="string"){var formatter;if(GravityRD.isObject(register[key])){formatter=register[key].formatter}else{formatter=register[key]}regTmp[key]=regTmp[key]||[];var value;if(GravityRD.isFunction(formatter)){value=formatter(this.value)}else{value=this.value}regTmp[key].push(value)}}}for(key in regTmp){if(typeof(key)=="string"){if(regTmp[key]!=undefined&®Tmp[key].length>0){GravityRD.Core.setGlobalNameValue(key,regTmp[key])}}}}}});var renamingStrategy={camelcase:function(input){var ia=input.split("-");var ret=ia[0];for(var i=1;i<ia.length;i++){ret+=ia[i].substring(0,1).toUpperCase();ret+=ia[i].substring(1)}return ret},identity:function(input){return input}};var MetaDataMatcher=GravityRD.extend(SelectorMatcher,{register:function(){if(this.match()){var rename=this.config.renamingStrategy||"camelcase";if(!GravityRD.isFunction(rename)){rename=renamingStrategy[rename];if(GravityRD.isUndefined(rename)){GravityRD.Log.error("Invalid renamingStrategy specified!")}}var register=this.config.register||{};var rh=this.config.registerHash;rh=rh===true?"_Hash":rh;var nv={};GravityRD.each(this.nodelist,function(element){GravityRD.each(element.getElementsByTagName("*"),function(node){var bnode=this.$(node);var name=bnode.data("name");var value=bnode.data("value");if(nv[name]===undefined){nv[name]=[]}nv[name].push(value);if(register===true){GravityRD.Core.addGlobalNameValue(rename(name),value)}else{if(register[name]!==undefined){if(register[name]===true){name=rename(name)}else{name=register[name]}GravityRD.Core.addGlobalNameValue(name,value)}}},this)},this);if(rh){var hash=GravityRD.hash(nv);GravityRD.Core.addGlobalNameValue(rh,""+hash)}}}});var UTMMatcher=GravityRD.extend(AbstractMatcher,{match:function(){return true},register:function(){GravityRD.each(this.config.source,function(sc){var paramMap=null;if(sc.type=="referrer"){paramMap=this.parseUrlParams(""+document.referrer)}else{if(sc.type=="location"){paramMap=this.parseUrlParams(""+document.location)}else{if(sc.type=="utmcookie"){var cookieVal=GravityRD.Core.Cookie.getCookie(this.config.utmcookie||"__utmz");paramMap=this.parseUTMCookieParams(cookieVal)}else{GravityRD.Log.error("Unknown source type specified: '"+sc.type+"'")}}}var cn=this.config.register.campaign;if(!!cn){var campaign=paramMap.utm_campaign||paramMap.utmccn||paramMap.utm_medium||paramMap.utmcmd||paramMap.utm_source||paramMap.utmcsr||paramMap.pk_campaign;if(!!campaign){GravityRD.Core.addGlobalNameValue(cn===true?"_Campaign":cn,campaign)}}var kw=this.config.register.keyword;if(!!kw){var keyword=paramMap.utm_term||paramMap.utmctr||paramMap.pk_keyword;if(!!keyword){GravityRD.Core.addGlobalNameValue(kw===true?"_Keyword":kw,keyword)}}},this)},parseUrlParams:function(input){var ret={};if(input!=null){input.replace(/.*\?/,"").replace(/([^=]+)=([^#&]*)&?/g,function(_,a,b){ret[decodeURIComponent(a)]=decodeURIComponent(b)})}return ret},parseUTMCookieParams:function(input){var ret={};if(input!=null){input.replace(/(utmc[^=]+)=([^|]*)/g,function(_,a,b){ret[decodeURIComponent(a)]=decodeURIComponent(b)})}return ret}});var MatcherFactory=GravityRD.extend(Object,{getInstance:function(config){var type=config.type;if("urlpath-regexp"===type){return new URLPathRegexpMatcher(config)}else{if("url-regexp"===type){return new URLRegexpMatcher(config)}else{if("urlquery-regexp"===type){return new URLQueryRegexpMatcher(config)}else{if("host-regexp"===type){return new HostRegexpMatcher(config)}else{if("cookie-regexp"===type){return new CookieRegexpMatcher(config)}else{if("referrer-regexp"===type){return new ReferrerRegexpMatcher(config)}else{if("selector"===type){return new SelectorMatcher(config)}else{if("meta-tag"===type){return new MetaTagMatcher(config)}else{if("meta-data"===type){return new MetaDataMatcher(config)}else{if("jsvar"===type){return new JSVarMatcher(config)}else{if("utm"===type){return new UTMMatcher(config)}else{if("dataLayer"===type){return new DataLayerMatcher(config)}else{GravityRD.Log.error("Unknown matcher type '"+type+"', please check your configuration");return null}}}}}}}}}}}}}});var AbstractSplitter=GravityRD.extend(Object,{config:null,constructor:function(c){this.config=c}});var splitCookieCache={};var ProportionalSplitter=GravityRD.extend(AbstractSplitter,{split:function(pageName,page){var groupName=(page.splitConfig.group||pageName);var cookieName="gr_split_"+groupName;var cookieVersionName="gr_splitv_"+groupName;var splitCookieVersion=parseInt(GravityRD.Core.Cookie.getCookie(cookieVersionName))||0;var expectedCookieVersion=parseInt(page.splitConfig.version)||0;if(expectedCookieVersion>splitCookieVersion){GravityRD.Log.debug("Expected cookie version ["+expectedCookieVersion+"] > currentCookieVersion ["+splitCookieVersion+"]. Removing old cookie.");GravityRD.Core.Cookie.setCookie(cookieName,"",0)}var splitValue=splitCookieCache[cookieName]||GravityRD.Core.Cookie.getCookie(cookieName);GravityRD.Log.debug("Split cookie found for page '"+pageName+"': '"+splitValue+"'");for(var i=0;i<page.splitConfig.names.length;i++){if(page.splitConfig.names[i]===splitValue){return{name:splitValue,version:expectedCookieVersion,created:false}}}var s=0,sold=0,splitIndex=-1;for(i=0;i<page.splitConfig.policy.values.length;i++){s+=page.splitConfig.policy.values[i]}var mod=(parseInt(Math.random()*1000000)%s);GravityRD.Log.debug("Split value is invalid.",mod);for(i=0,s=0;i<page.splitConfig.policy.values.length;i++){s+=page.splitConfig.policy.values[i];if(mod<s&&mod>=sold){splitIndex=i;break}sold=s}if(splitIndex!=-1){splitCookieCache[cookieName]=page.splitConfig.names[splitIndex];GravityRD.Core.Cookie.setCookie(cookieName,page.splitConfig.names[splitIndex]);if(expectedCookieVersion>0){GravityRD.Core.Cookie.setCookie(cookieVersionName,expectedCookieVersion)}return{name:page.splitConfig.names[splitIndex],version:expectedCookieVersion,created:true}}}});var FromCookieSplitter=GravityRD.extend(AbstractSplitter,{split:function(pageName,page){var cookieName=page.splitConfig.policy.cookieName;var splitValue=GravityRD.Core.Cookie.getCookie(cookieName);var n=page.splitConfig.names;GravityRD.Log.debug("Split cookie found for page '"+pageName+"': '"+splitValue+"'");var cv=page.splitConfig.policy.cookieValues;if(GravityRD.isArray(cv)){if(cv.length===n.length){for(var i=0;i<n.length;i++){var cr=new RegExp(cv[i]);if(!!cr.exec(splitValue)){return{name:n[i],version:0}}}}else{GravityRD.Log.error("Length of cookieValues is wrong, should be "+n.length)}}else{GravityRD.Log.error("Only array type is supported currently for cookieValues")}GravityRD.Log.debug("Split value is invalid.",splitValue);var f=page.splitConfig.policy.fallbackSplit;if(!GravityRD.isUndefined(f)){return{name:f,version:0}}return null}});var SplitterFactory=GravityRD.extend(Object,{getInstance:function(config){var type=config.policy.type;if("proportional"===type){return new ProportionalSplitter(config)}else{if("from-cookie"===type){return new FromCookieSplitter(config)}else{GravityRD.Log.error("Unknown splitter type '"+type+"', please check your configuration");return null}}}});var GravityRD_CustomConfig=GravityRD.Base.extend({__public__:["init","set","enable","applyCss","addEventListener","getDomEngine","domready","updateCart"],matcherFactory:new MatcherFactory(),splitterFactory:new SplitterFactory(),config:null,initialized:false,enabled:false,domengine:null,domreadyfunctions:[],domreadydone:false,enable:function(){this.enabled=true},set:function(config,environment,xinit){this.config=config;this.environment=environment;if(!!xinit){this.init()}},updateCart:function(ncart){var tr=GravityRD.Core.Cookie.getTracking();var cartObj=tr.cart;var ocart=cartObj.getItems();var nkeys=GravityRD.keys(ncart);var okeys=GravityRD.keys(ocart);for(var i=0;i<nkeys.length;i++){var vo=ocart[nkeys[i]]||0;var vn=ncart[nkeys[i]]||0;if(vn==0||vn<vo){cartObj.removeItem(nkeys[i],vo-vn);_gravity.push({type:"event",eventType:"REMOVE_FROM_CART",newQuantity:""+vn,itemId:""+nkeys[i]})}else{if(vn>vo){cartObj.addItem(nkeys[i],vn-vo);_gravity.push({type:"event",eventType:"ADD_TO_CART",newQuantity:""+vn,itemId:""+nkeys[i]})}}}for(i=0;i<okeys.length;i++){if(ncart[okeys[i]]==undefined){cartObj.removeItem(okeys[i]);_gravity.push({type:"event",eventType:"REMOVE_FROM_CART",newQuantity:"0",itemId:""+okeys[i]})}}},domready:function(fns,immediate){if(!!immediate){GravityRD.each(fns,function(fn){fn.apply(this)},this)}else{GravityRD.each(fns,function(fn){this.domreadyfunctions.push(fn)},this)}},applyCss:function(css){var st=this.styleTag=document.createElement("style");st.type="text/css";st.media="screen, projection";document.getElementsByTagName("head")[0].appendChild(st);var cssx="";GravityRD.each(css,function(line){cssx+=line+"\n"});if(st.styleSheet){st.styleSheet.cssText+="\n"+cssx}else{st.appendChild(document.createTextNode(cssx))}},getSelectorEngine:function(){this.selectorEngine=this.selectorEngine||(function(){if(privatescope.qwery){return function(selector){return privatescope.qwery(selector)}}else{throw"no css selector engine found"}})();return this.selectorEngine},getDomEngine:function(){this.domengine=this.domengine||(function(){if(!!privatescope.bonzo&&!!privatescope.qwery){privatescope.bonzo.setQueryEngine(privatescope.qwery);return function(selector){return privatescope.bonzo(privatescope.qwery(selector))}}else{throw"No dom enigne found."}})();return this.domengine},init:function(runJustDemo){if(!this.domreadydone){GravityRD.each(this.domreadyfunctions,function(fn){fn.call(this)},this);this.domreadydone=true}if(runJustDemo===true){if(this.enabled===true){GravityRD.Log.debug("CustomConfig [demo] enabled by default");return}if(this.initialized===true){GravityRD.Log.debug("CustomConfig [demo] already initialized");return}this.initialized=true}GravityRD.Log.debug("CustomConfig initialization, demo: "+this.demoMode,this.config);if(this.config==null){return}if("test"==this.environment&&GravityRD.RL!==undefined){GravityRD.RL.start()}if(this.config.routing!=null){GravityRD.Core.Request.setupRouting(this.config.routing)}this.pageName=this.identifyPage();GravityRD.Log.debug("Page identification: '"+this.pageName+"'");if(this.pageName==null){return}GravityRD.Core.setGlobalNameValue("_Page",this.pageName);var config=this.initSplit(this.pageName,this.config.pages[this.pageName],runJustDemo);GravityRD.Log.group("Split",true);var pages=this.config.pages||{};var pageOrder=this.calcPageOrder(pages);for(var j=0;j<pageOrder.length;j++){var xpageName=pageOrder[j];var page=this.config.pages[xpageName];if(page.splitConfig!==undefined){var splitter=this.splitterFactory.getInstance(page.splitConfig);var splitInfo=splitter.split(xpageName,page);GravityRD.Core.setGlobalNameValue("_Split"+(page.splitConfig.group||xpageName),splitInfo.name);if(splitInfo.version>0){GravityRD.Core.setGlobalNameValue("_SplitV"+(page.splitConfig.group||xpageName),splitInfo.version)}this.propagateThirdParty(page.splitConfig,splitInfo)}}GravityRD.Log.groupEnd();if(!runJustDemo&&(this.pageName!=null&&(GravityRD.Core.debug("tracking")||GravityRD.Core.debug("postrender")))){document.title="[["+this.pageName+(config.splitName!=null?"/"+config.splitName:"")+"]] "+document.title}GravityRD.Log.debug("Custom configuration for split "+config.splitName+":",config);GravityRD.each(config.register,function(conf){var matcher=this.matcherFactory.getInstance(conf);matcher.register()},this);var css="";GravityRD.each(config.applyCss,function(val){css+=val+"\n"});if(css!=""){GravityRD.CustomConfig.applyCss(css)}GravityRD.Log.debug("Executing postRenderCommands");GravityRD.each(config.postRenderCommands,function(val){try{eval(val)}catch(e){GravityRD.Log.error("Exception while executing postRenderCommands",e)}},this);GravityRD.Log.debug("Executing postRenderFunctions");GravityRD.each(config.postRenderFunction,function(val){try{val.call(this,this.getDomEngine())}catch(e){GravityRD.Log.error("Exception while executing postRenderFunctions",e)}},this);GravityRD.Log.debug("Install tracking");GravityRD.each(config.tracking,function(val){this.installTracking(this.pageName,val)},this);GravityRD.Log.debug("Install hooks");GravityRD.each(config.hooks,function(val){this.installHooks(val)},this)},calcPageOrder:function(pages){var pageOrderConfig=this.config.pageOrder||[];var pageDisableConfig=this.config.pageDisable||[];var pageNames={};var pageOrder=[];for(var pageName in pages){if(!pages.hasOwnProperty(pageName)){continue}if(GravityRD.isString(pageName)){pageNames[pageName]=!0}}for(var i=0;i<pageDisableConfig.length;i++){delete pageNames[pageDisableConfig[i]]}for(i=0;i<pageOrderConfig.length;i++){if(pageNames[pageOrderConfig[i]]){delete pageNames[pageOrderConfig[i]];pageOrder.push(pageOrderConfig[i])}}for(pageName in pageNames){if(!pages.hasOwnProperty(pageName)){continue}if(GravityRD.isString(pageName)){pageOrder.push(pageName)}}return pageOrder},identifyPage:function(){var D=GravityRD.Core.debug("page");D&&GravityRD.Log.group("Pages identification",true);var pages=this.config.pages||{};var pageOrder=this.calcPageOrder(pages);for(var j=0;j<pageOrder.length;j++){var pageName=pageOrder[j];D&&GravityRD.Log.group(pageName);var page=this.config.pages[pageName];var matchType=page.matchType||"all";var matcher;var matched=matchType==="all";if(GravityRD.isArray(page.match)){for(var i=0;i<page.match.length;i++){matcher=this.matcherFactory.getInstance(page.match[i]);var t=page.match[i].type;var m=matcher.match();if(m&&matchType=="any"){matched=true;D&&GravityRD.Log.debug(t+" matched(*): TRUE",page.match[i]);break}else{if(!m&&matchType=="all"){matched=false;D&&GravityRD.Log.debug(t+" matched(*): FALSE",page.match[i]);break}}D&&GravityRD.Log.debug(t+" matched: "+(!!m?"TRUE":"FALSE"),page.match[i])}}else{matcher=this.matcherFactory.getInstance(page.match);matched=matcher.match();D&&GravityRD.Log.debug(page.match.type+" didn't match ",page.match)}D&&GravityRD.Log.groupEnd();if(matched){D&&GravityRD.Log.groupEnd();GravityRD.each(page.match,function(conf){var matcher=this.matcherFactory.getInstance(conf);matcher.register()},this);return pageName}}D&&GravityRD.Log.groupEnd();return null},initSplit:function(pageName,page,runJustDemo){var splitName=null;if(page.splitConfig!==undefined){var splitter=this.splitterFactory.getInstance(page.splitConfig);var splitInfo=splitter.split(pageName,page);this.propagateThirdParty(page.splitConfig,splitInfo);splitName=splitInfo.name}return this.getSplitConfig(page,splitName,runJustDemo)},propagateThirdParty:function(splitConfig,splitInfo){if(splitInfo.created||false){GravityRD.Log.debug("Propagating 3rdparty split information",splitInfo);var thirdParty=splitConfig.thirdparty||{};if(thirdParty.store||false){var ep=GravityRD.Core.Request.getEndpoint(true,"AdServlet");GravityRD.Core.Request.scriptTagRequest(ep,"action=setparam&name="+(thirdParty.name||"_Split")+"&value="+encodeURIComponent(splitInfo.name))}}},getSplitConfig:function(page,splitName,runJustDemo){var config={};var i;if(splitName!=null){var split=(page.splits||{})[splitName]||{};var demo=split.__demo||{};var base=runJustDemo===true?demo:split;if(this.enabled){base=this.applyArray(base,demo,["__demo"])}config=this.applyArray(config,base,["templates","__demo"]);var templates=base.templates||[];for(i=0;i<templates.length;i++){config=this.applyArray(config,this.config.templates[templates[i]])}}var pageDemo=page.__demo||{};var pageBase=runJustDemo===true?pageDemo:page;if(this.enabled){pageBase=this.applyArray(pageBase,pageDemo,["splits","splitConfig","match","__demo"])}config=this.applyArray(config,pageBase,["splits","splitConfig","match","__demo"]);for(i=0;i<(pageBase.templates||[]).length;i++){config=this.applyArray(config,this.config.templates[pageBase.templates[i]])}config.splitName=splitName;return config},applyArray:function(target,source,prohibit){for(var k in source){if(!source.hasOwnProperty(k)){continue}var prohibited=false;if(prohibit!=undefined){for(var j=0;j<prohibit.length;j++){if(prohibit[j]==k){prohibited=true;break}}}if(!prohibited){if(!GravityRD.isArray(target[k])){var item=target[k];target[k]=[];if(item!=undefined){target[k].push(item)}target[k]=target[k]||[]}if(GravityRD.isArray(source[k])){target[k]=target[k].concat(source[k])}else{target[k].push(source[k])}}}return target},addEventListener:function(element,type,callback){if(element.addEventListener){element.addEventListener(type,callback,false)}else{element.attachEvent("on"+type,callback)}},installHooks:function(conf,debug,time){time=time||0;var $S=this.getSelectorEngine();var nl=(GravityRD.isFunction(conf.selector))?conf.selector.call(this,$S):$S(conf.selector);if(nl.length!==0){this.installHook(conf,debug,nl)}if(nl.length===0||conf.destroyOnFound===false){var d,m,p;if(conf.poll===true){d=conf.period===undefined||conf.period===null?250:conf.period;m=conf.until===undefined||conf.until===null?10000:conf.until;p=true}if(GravityRD.isArray(d)&&this.count===undefined){this.count=0}if(p&&(time<m)){if(GravityRD.isArray(d)&&this.count>=d.length){return}window.setTimeout(GravityRD.bind(function(){var ttime=time+GravityRD.isArray(d)?d[this.count]:d;this.installHooks(conf,debug,ttime)},this),GravityRD.isArray(d)?d[this.count++]:d)}}},installHook:function(conf,debug,nl){var on=conf.on||"click";var color=Math.round(Math.random()*256)+","+Math.round(Math.random()*256)+","+Math.round(Math.random()*256);GravityRD.each(nl,function(element){if(on==="init"){conf.callback.call(this,this.getDomEngine(),conf)}else{this.addEventListener(element,on,conf.callback);if(GravityRD.Core.debug(debug||"tracking")){element.setAttribute("style","background-color:rgb("+color+");")}}},this)},installTracking:function(pageName,conf){conf.callback=function(){_gravity.push({type:"event",eventType:"TRACK",pageName:pageName,boxName:conf.name})};this.installHooks(conf)}});GravityRD.register("GravityRD","CustomConfig",new GravityRD_CustomConfig())})();window._gravity_init_jq=function(jQuery){ /*! * typeahead.js 0.11.1 * https://github.com/twitter/typeahead.js * Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT */ (function(root,factory){if(typeof define==="function"&&define.amd){define(["jquery"],function(a0){return root.Bloodhound=factory(a0)})}else{if(typeof exports==="object"){module.exports=factory(require("jquery"))}else{root.Bloodhound=factory(jQuery)}}})(this,function($){var _=function(){return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:false},isBlankString:function(str){return !str||/^\s*$/.test(str)},escapeRegExChars:function(str){return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(obj){return typeof obj==="string"},isNumber:function(obj){return typeof obj==="number"},isArray:$.isArray,isFunction:$.isFunction,isObject:$.isPlainObject,isUndefined:function(obj){return typeof obj==="undefined"},isElement:function(obj){return !!(obj&&obj.nodeType===1)},isJQuery:function(obj){return obj instanceof $},toStr:function toStr(s){return _.isUndefined(s)||s===null?"":s+""},bind:$.proxy,each:function(collection,cb){$.each(collection,reverseArgs);function reverseArgs(index,value){return cb(value,index)}},map:$.map,filter:$.grep,every:function(obj,test){var result=true;if(!obj){return result}$.each(obj,function(key,val){if(!(result=test.call(null,val,key,obj))){return false}});return !!result},some:function(obj,test){var result=false;if(!obj){return result}$.each(obj,function(key,val){if(result=test.call(null,val,key,obj)){return false}});return !!result},mixin:$.extend,identity:function(x){return x},clone:function(obj){return $.extend(true,{},obj)},getIdGenerator:function(){var counter=0;return function(){return counter++}},templatify:function templatify(obj){return $.isFunction(obj)?obj:template;function template(){return String(obj)}},defer:function(fn){setTimeout(fn,0)},debounce:function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments,later,callNow;later=function(){timeout=null;if(!immediate){result=func.apply(context,args)}};callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow){result=func.apply(context,args)}return result}},throttle:function(func,wait){var context,args,timeout,result,previous,later;previous=0;later=function(){previous=new Date();timeout=null;result=func.apply(context,args)};return function(){var now=new Date(),remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args)}else{if(!timeout){timeout=setTimeout(later,remaining)}}return result}},stringify:function(val){return _.isString(val)?val:JSON.stringify(val)},noop:function(){}}}();var VERSION="0.11.1";var tokenizers=function(){return{nonword:nonword,whitespace:whitespace,obj:{nonword:getObjTokenizer(nonword),whitespace:getObjTokenizer(whitespace)}};function whitespace(str){str=_.toStr(str);return str?str.split(/\s+/):[]}function nonword(str){str=_.toStr(str);return str?str.split(/\W+/):[]}function getObjTokenizer(tokenizer){return function setKey(keys){keys=_.isArray(keys)?keys:[].slice.call(arguments,0);return function tokenize(o){var tokens=[];_.each(keys,function(k){tokens=tokens.concat(tokenizer(_.toStr(o[k])))});return tokens}}}}();var LruCache=function(){function LruCache(maxSize){this.maxSize=_.isNumber(maxSize)?maxSize:100;this.reset();if(this.maxSize<=0){this.set=this.get=$.noop}}_.mixin(LruCache.prototype,{set:function set(key,val){var tailItem=this.list.tail,node;if(this.size>=this.maxSize){this.list.remove(tailItem);delete this.hash[tailItem.key];this.size--}if(node=this.hash[key]){node.val=val;this.list.moveToFront(node)}else{node=new Node(key,val);this.list.add(node);this.hash[key]=node;this.size++}},get:function get(key){var node=this.hash[key];if(node){this.list.moveToFront(node);return node.val}},reset:function reset(){this.size=0;this.hash={};this.list=new List()}});function List(){this.head=this.tail=null}_.mixin(List.prototype,{add:function add(node){if(this.head){node.next=this.head;this.head.prev=node}this.head=node;this.tail=this.tail||node},remove:function remove(node){node.prev?node.prev.next=node.next:this.head=node.next;node.next?node.next.prev=node.prev:this.tail=node.prev},moveToFront:function(node){this.remove(node);this.add(node)}});function Node(key,val){this.key=key;this.val=val;this.prev=this.next=null}return LruCache}();var PersistentStorage=function(){var LOCAL_STORAGE;try{LOCAL_STORAGE=window.localStorage;LOCAL_STORAGE.setItem("~~~","!");LOCAL_STORAGE.removeItem("~~~")}catch(err){LOCAL_STORAGE=null}function PersistentStorage(namespace,override){this.prefix=["__",namespace,"__"].join("");this.ttlKey="__ttl__";this.keyMatcher=new RegExp("^"+_.escapeRegExChars(this.prefix));this.ls=override||LOCAL_STORAGE;!this.ls&&this._noop()}_.mixin(PersistentStorage.prototype,{_prefix:function(key){return this.prefix+key},_ttlKey:function(key){return this._prefix(key)+this.ttlKey},_noop:function(){this.get=this.set=this.remove=this.clear=this.isExpired=_.noop},_safeSet:function(key,val){try{this.ls.setItem(key,val)}catch(err){if(err.name==="QuotaExceededError"){this.clear();this._noop()}}},get:function(key){if(this.isExpired(key)){this.remove(key)}return decode(this.ls.getItem(this._prefix(key)))},set:function(key,val,ttl){if(_.isNumber(ttl)){this._safeSet(this._ttlKey(key),encode(now()+ttl))}else{this.ls.removeItem(this._ttlKey(key))}return this._safeSet(this._prefix(key),encode(val))},remove:function(key){this.ls.removeItem(this._ttlKey(key));this.ls.removeItem(this._prefix(key));return this},clear:function(){var i,keys=gatherMatchingKeys(this.keyMatcher);for(i=keys.length;i--;){this.remove(keys[i])}return this},isExpired:function(key){var ttl=decode(this.ls.getItem(this._ttlKey(key)));return _.isNumber(ttl)&&now()>ttl?true:false}});return PersistentStorage;function now(){return new Date().getTime()}function encode(val){return JSON.stringify(_.isUndefined(val)?null:val)}function decode(val){return $.parseJSON(val)}function gatherMatchingKeys(keyMatcher){var i,key,keys=[],len=LOCAL_STORAGE.length;for(i=0;i<len;i++){if((key=LOCAL_STORAGE.key(i)).match(keyMatcher)){keys.push(key.replace(keyMatcher,""))}}return keys}}();var Transport=function(){var pendingRequestsCount=0,pendingRequests={},maxPendingRequests=6,sharedCache=new LruCache(10);function Transport(o){o=o||{};this.cancelled=false;this.lastReq=null;this._send=o.transport;this._get=o.limiter?o.limiter(this._get):this._get;this._cache=o.cache===false?new LruCache(0):sharedCache}Transport.setMaxPendingRequests=function setMaxPendingRequests(num){maxPendingRequests=num};Transport.resetCache=function resetCache(){sharedCache.reset()};_.mixin(Transport.prototype,{_fingerprint:function fingerprint(o){o=o||{};return o.url+o.type+$.param(o.data||{})},_get:function(o,cb){var that=this,fingerprint,jqXhr;fingerprint=this._fingerprint(o);if(this.cancelled||fingerprint!==this.lastReq){return}if(jqXhr=pendingRequests[fingerprint]){jqXhr.done(done).fail(fail)}else{if(pendingRequestsCount<maxPendingRequests){pendingRequestsCount++;pendingRequests[fingerprint]=this._send(o).done(done).fail(fail).always(always)}else{this.onDeckRequestArgs=[].slice.call(arguments,0)}}function done(resp){cb(null,resp);that._cache.set(fingerprint,resp)}function fail(){cb(true)}function always(){pendingRequestsCount--;delete pendingRequests[fingerprint];if(that.onDeckRequestArgs){that._get.apply(that,that.onDeckRequestArgs);that.onDeckRequestArgs=null}}},get:function(o,cb){var resp,fingerprint;cb=cb||$.noop;o=_.isString(o)?{url:o}:o||{};fingerprint=this._fingerprint(o);this.cancelled=false;this.lastReq=fingerprint;if(resp=this._cache.get(fingerprint)){cb(null,resp)}else{this._get(o,cb)}},cancel:function(){this.cancelled=true}});return Transport}();var SearchIndex=window.SearchIndex=function(){var CHILDREN="c",IDS="i";function SearchIndex(o){o=o||{};if(!o.datumTokenizer||!o.queryTokenizer){$.error("datumTokenizer and queryTokenizer are both required")}this.identify=o.identify||_.stringify;this.datumTokenizer=o.datumTokenizer;this.queryTokenizer=o.queryTokenizer;this.matchAnyQueryToken=o.matchAnyQueryToken;this.reset()}_.mixin(SearchIndex.prototype,{bootstrap:function bootstrap(o){this.datums=o.datums;this.trie=o.trie},add:function(data){var that=this;data=_.isArray(data)?data:[data];_.each(data,function(datum){var id,tokens;that.datums[id=that.identify(datum)]=datum;tokens=normalizeTokens(that.datumTokenizer(datum));_.each(tokens,function(token){var node,chars,ch;node=that.trie;chars=token.split("");while(ch=chars.shift()){node=node[CHILDREN][ch]||(node[CHILDREN][ch]=newNode());node[IDS].push(id)}})})},get:function get(ids){var that=this;return _.map(ids,function(id){return that.datums[id]})},search:function search(query){var that=this,tokens,matches;tokens=normalizeTokens(this.queryTokenizer(query));_.each(tokens,function(token){var node,chars,ch,ids;if(matches&&matches.length===0&&!that.matchAnyQueryToken){return false}node=that.trie;chars=token.split("");while(node&&(ch=chars.shift())){node=node[CHILDREN][ch]}if(node&&chars.length===0){ids=node[IDS].slice(0);matches=matches?getIntersection(matches,ids):ids}else{if(!that.matchAnyQueryToken){matches=[];return false}}});return matches?_.map(unique(matches),function(id){return that.datums[id]}):[]},all:function all(){var values=[];for(var key in this.datums){values.push(this.datums[key])}return values},reset:function reset(){this.datums={};this.trie=newNode()},serialize:function serialize(){return{datums:this.datums,trie:this.trie}}});return SearchIndex;function normalizeTokens(tokens){tokens=_.filter(tokens,function(token){return !!token});tokens=_.map(tokens,function(token){return token.toLowerCase()});return tokens}function newNode(){var node={};node[IDS]=[];node[CHILDREN]={};return node}function unique(array){var seen={},uniques=[];for(var i=0,len=array.length;i<len;i++){if(!seen[array[i]]){seen[array[i]]=true;uniques.push(array[i])}}return uniques}function getIntersection(arrayA,arrayB){var ai=0,bi=0,intersection=[];arrayA=arrayA.sort();arrayB=arrayB.sort();var lenArrayA=arrayA.length,lenArrayB=arrayB.length;while(ai<lenArrayA&&bi<lenArrayB){if(arrayA[ai]<arrayB[bi]){ai++}else{if(arrayA[ai]>arrayB[bi]){bi++}else{intersection.push(arrayA[ai]);ai++;bi++}}}return intersection}}();var Prefetch=function(){var keys;keys={data:"data",protocol:"protocol",thumbprint:"thumbprint"};function Prefetch(o){this.url=o.url;this.ttl=o.ttl;this.cache=o.cache;this.prepare=o.prepare;this.transform=o.transform;this.transport=o.transport;this.thumbprint=o.thumbprint;this.storage=new PersistentStorage(o.cacheKey)}_.mixin(Prefetch.prototype,{_settings:function settings(){return{url:this.url,type:"GET",dataType:"json"}},store:function store(data){if(!this.cache){return}this.storage.set(keys.data,data,this.ttl);this.storage.set(keys.protocol,location.protocol,this.ttl);this.storage.set(keys.thumbprint,this.thumbprint,this.ttl)},fromCache:function fromCache(){var stored={},isExpired;if(!this.cache){return null}stored.data=this.storage.get(keys.data);stored.protocol=this.storage.get(keys.protocol);stored.thumbprint=this.storage.get(keys.thumbprint);isExpired=stored.thumbprint!==this.thumbprint||stored.protocol!==location.protocol;return stored.data&&!isExpired?stored.data:null},fromNetwork:function(cb){var that=this,settings;if(!cb){return}settings=this.prepare(this._settings());this.transport(settings).fail(onError).done(onResponse);function onError(){cb(true)}function onResponse(resp){cb(null,that.transform(resp))}},clear:function clear(){this.storage.clear();return this}});return Prefetch}();var Remote=function(){function Remote(o){this.url=o.url;this.prepare=o.prepare;this.transform=o.transform;this.indexResponse=o.indexResponse;this.transport=new Transport({cache:o.cache,limiter:o.limiter,transport:o.transport})}_.mixin(Remote.prototype,{_settings:function settings(){return{url:this.url,type:"GET",dataType:"json"}},get:function get(query,cb){var that=this,settings;if(!cb){return}query=query||"";settings=this.prepare(query,this._settings());return this.transport.get(settings,onResponse);function onResponse(err,resp){err?cb([]):cb(that.transform(resp))}},cancelLastRequest:function cancelLastRequest(){this.transport.cancel()}});return Remote}();var oParser=function(){return function parse(o){var defaults,sorter;defaults={initialize:true,identify:_.stringify,datumTokenizer:null,queryTokenizer:null,matchAnyQueryToken:false,sufficient:5,indexRemote:false,sorter:null,local:[],prefetch:null,remote:null};o=_.mixin(defaults,o||{});!o.datumTokenizer&&$.error("datumTokenizer is required");!o.queryTokenizer&&$.error("queryTokenizer is required");sorter=o.sorter;o.sorter=sorter?function(x){return x.sort(sorter)}:_.identity;o.local=_.isFunction(o.local)?o.local():o.local;o.prefetch=parsePrefetch(o.prefetch);o.remote=parseRemote(o.remote);return o};function parsePrefetch(o){var defaults;if(!o){return null}defaults={url:null,ttl:24*60*60*1000,cache:true,cacheKey:null,thumbprint:"",prepare:_.identity,transform:_.identity,transport:null};o=_.isString(o)?{url:o}:o;o=_.mixin(defaults,o);!o.url&&$.error("prefetch requires url to be set");o.transform=o.filter||o.transform;o.cacheKey=o.cacheKey||o.url;o.thumbprint=VERSION+o.thumbprint;o.transport=o.transport?callbackToDeferred(o.transport):$.ajax;return o}function parseRemote(o){var defaults;if(!o){return}defaults={url:null,cache:true,prepare:null,replace:null,wildcard:null,limiter:null,rateLimitBy:"debounce",rateLimitWait:300,transform:_.identity,transport:null};o=_.isString(o)?{url:o}:o;o=_.mixin(defaults,o);!o.url&&$.error("remote requires url to be set");o.transform=o.filter||o.transform;o.prepare=toRemotePrepare(o);o.limiter=toLimiter(o);o.transport=o.transport?callbackToDeferred(o.transport):$.ajax;delete o.replace;delete o.wildcard;delete o.rateLimitBy;delete o.rateLimitWait;return o}function toRemotePrepare(o){var prepare,replace,wildcard;prepare=o.prepare;replace=o.replace;wildcard=o.wildcard;if(prepare){return prepare}if(replace){prepare=prepareByReplace}else{if(o.wildcard){prepare=prepareByWildcard}else{prepare=idenityPrepare}}return prepare;function prepareByReplace(query,settings){settings.url=replace(settings.url,query);return settings}function prepareByWildcard(query,settings){settings.url=settings.url.replace(wildcard,encodeURIComponent(query));return settings}function idenityPrepare(query,settings){return settings}}function toLimiter(o){var limiter,method,wait;limiter=o.limiter;method=o.rateLimitBy;wait=o.rateLimitWait;if(!limiter){limiter=/^throttle$/i.test(method)?throttle(wait):debounce(wait)}return limiter;function debounce(wait){return function debounce(fn){return _.debounce(fn,wait)}}function throttle(wait){return function throttle(fn){return _.throttle(fn,wait)}}}function callbackToDeferred(fn){return function wrapper(o){var deferred=$.Deferred();fn(o,onSuccess,onError);return deferred;function onSuccess(resp){_.defer(function(){deferred.resolve(resp)})}function onError(err){_.defer(function(){deferred.reject(err)})}}}}();var Bloodhound=function(){var old;old=window&&window.Bloodhound;function Bloodhound(o){o=oParser(o);this.sorter=o.sorter;this.identify=o.identify;this.sufficient=o.sufficient;this.indexRemote=o.indexRemote;this.local=o.local;this.remote=o.remote?new Remote(o.remote):null;this.prefetch=o.prefetch?new Prefetch(o.prefetch):null;this.index=new SearchIndex({identify:this.identify,datumTokenizer:o.datumTokenizer,queryTokenizer:o.queryTokenizer});o.initialize!==false&&this.initialize()}Bloodhound.noConflict=function noConflict(){window&&(window.Bloodhound=old);return Bloodhound};Bloodhound.tokenizers=tokenizers;_.mixin(Bloodhound.prototype,{__ttAdapter:function ttAdapter(){var that=this;return this.remote?withAsync:withoutAsync;function withAsync(query,sync,async){return that.search(query,sync,async)}function withoutAsync(query,sync){return that.search(query,sync)}},_loadPrefetch:function loadPrefetch(){var that=this,deferred,serialized;deferred=$.Deferred();if(!this.prefetch){deferred.resolve()}else{if(serialized=this.prefetch.fromCache()){this.index.bootstrap(serialized);deferred.resolve()}else{this.prefetch.fromNetwork(done)}}return deferred.promise();function done(err,data){if(err){return deferred.reject()}that.add(data);that.prefetch.store(that.index.serialize());deferred.resolve()}},_initialize:function initialize(){var that=this,deferred;this.clear();(this.initPromise=this._loadPrefetch()).done(addLocalToIndex);return this.initPromise;function addLocalToIndex(){that.add(that.local)}},initialize:function initialize(force){return !this.initPromise||force?this._initialize():this.initPromise},add:function add(data){this.index.add(data);return this},get:function get(ids){ids=_.isArray(ids)?ids:[].slice.call(arguments);return this.index.get(ids)},search:function search(query,sync,async){var that=this,local;sync=sync||_.noop;async=async||_.noop;local=this.sorter(this.index.search(query));sync(this.remote?local.slice():local);if(this.remote&&local.length<this.sufficient){this.remote.get(query,processRemote)}else{if(this.remote){this.remote.cancelLastRequest()}}return this;function processRemote(remote){var nonDuplicates=[];_.each(remote,function(r){!_.some(local,function(l){return that.identify(r)===that.identify(l)})&&nonDuplicates.push(r)});that.indexRemote&&that.add(nonDuplicates);async(nonDuplicates)}},all:function all(){return this.index.all()},clear:function clear(){this.index.reset();return this},clearPrefetchCache:function clearPrefetchCache(){this.prefetch&&this.prefetch.clear();return this},clearRemoteCache:function clearRemoteCache(){Transport.resetCache();return this},ttAdapter:function ttAdapter(){return this.__ttAdapter()}});return Bloodhound}();return Bloodhound});(function(root,factory){if(typeof define==="function"&&define.amd){define(["jquery"],function(a0){return factory(a0)})}else{if(typeof exports==="object"){module.exports=factory(require("jquery"))}else{factory(jQuery)}}})(this,function($){var _=function(){return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:false},isBlankString:function(str){return !str||/^\s*$/.test(str)},escapeRegExChars:function(str){return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(obj){return typeof obj==="string"},isNumber:function(obj){return typeof obj==="number"},isArray:$.isArray,isFunction:$.isFunction,isObject:$.isPlainObject,isUndefined:function(obj){return typeof obj==="undefined"},isElement:function(obj){return !!(obj&&obj.nodeType===1)},isJQuery:function(obj){return obj instanceof $},toStr:function toStr(s){return _.isUndefined(s)||s===null?"":s+""},bind:$.proxy,each:function(collection,cb){$.each(collection,reverseArgs);function reverseArgs(index,value){return cb(value,index)}},map:$.map,filter:$.grep,every:function(obj,test){var result=true;if(!obj){return result}$.each(obj,function(key,val){if(!(result=test.call(null,val,key,obj))){return false}});return !!result},some:function(obj,test){var result=false;if(!obj){return result}$.each(obj,function(key,val){if(result=test.call(null,val,key,obj)){return false}});return !!result},mixin:$.extend,identity:function(x){return x},clone:function(obj){return $.extend(true,{},obj)},getIdGenerator:function(){var counter=0;return function(){return counter++}},templatify:function templatify(obj){return $.isFunction(obj)?obj:template;function template(){return String(obj)}},defer:function(fn){setTimeout(fn,0)},debounce:function(func,wait,immediate){var timeout,result;return function(){var context=this,args=arguments,later,callNow;later=function(){timeout=null;if(!immediate){result=func.apply(context,args)}};callNow=immediate&&!timeout;clearTimeout(timeout);timeout=setTimeout(later,wait);if(callNow){result=func.apply(context,args)}return result}},throttle:function(func,wait){var context,args,timeout,result,previous,later;previous=0;later=function(){previous=new Date();timeout=null;result=func.apply(context,args)};return function(){var now=new Date(),remaining=wait-(now-previous);context=this;args=arguments;if(remaining<=0){clearTimeout(timeout);timeout=null;previous=now;result=func.apply(context,args)}else{if(!timeout){timeout=setTimeout(later,remaining)}}return result}},stringify:function(val){return _.isString(val)?val:JSON.stringify(val)},noop:function(){}}}();var WWW=function(){var defaultClassNames={wrapper:"twitter-typeahead",input:"tt-input",hint:"tt-hint",menu:"tt-menu",dataset:"tt-dataset",suggestion:"tt-suggestion",selectable:"tt-selectable",empty:"tt-empty",open:"tt-open",cursor:"tt-cursor",highlight:"tt-highlight"};return build;function build(o){var www,classes;classes=_.mixin({},defaultClassNames,o);www={css:buildCss(),classes:classes,html:buildHtml(classes),selectors:buildSelectors(classes)};return{css:www.css,html:www.html,classes:www.classes,selectors:www.selectors,mixin:function(o){_.mixin(o,www)}}}function buildHtml(c){return{wrapper:'<span class="'+c.wrapper+'"></span>',menu:'<div class="'+c.menu+'"></div>'}}function buildSelectors(classes){var selectors={};_.each(classes,function(v,k){selectors[k]="."+v});return selectors}function buildCss(){var css={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},menu:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};if(_.isMsie()){_.mixin(css.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"})}return css}}();var EventBus=function(){var namespace,deprecationMap;namespace="typeahead:";deprecationMap={render:"rendered",cursorchange:"cursorchanged",select:"selected",autocomplete:"autocompleted"};function EventBus(o){if(!o||!o.el){$.error("EventBus initialized without el")}this.$el=$(o.el)}_.mixin(EventBus.prototype,{_trigger:function(type,args){var $e;$e=$.Event(namespace+type);(args=args||[]).unshift($e);this.$el.trigger.apply(this.$el,args);return $e},before:function(type){var args,$e;args=[].slice.call(arguments,1);$e=this._trigger("before"+type,args);return $e.isDefaultPrevented()},trigger:function(type){var deprecatedType;this._trigger(type,[].slice.call(arguments,1));if(deprecatedType=deprecationMap[type]){this._trigger(deprecatedType,[].slice.call(arguments,1))}}});return EventBus}();var EventEmitter=function(){var splitter=/\s+/,nextTick=getNextTick();return{onSync:onSync,onAsync:onAsync,off:off,trigger:trigger};function on(method,types,cb,context){var type;if(!cb){return this}types=types.split(splitter);cb=context?bindContext(cb,context):cb;this._callbacks=this._callbacks||{};while(type=types.shift()){this._callbacks[type]=this._callbacks[type]||{sync:[],async:[]};this._callbacks[type][method].push(cb)}return this}function onAsync(types,cb,context){return on.call(this,"async",types,cb,context)}function onSync(types,cb,context){return on.call(this,"sync",types,cb,context)}function off(types){var type;if(!this._callbacks){return this}types=types.split(splitter);while(type=types.shift()){delete this._callbacks[type]}return this}function trigger(types){var type,callbacks,args,syncFlush,asyncFlush;if(!this._callbacks){return this}types=types.split(splitter);args=[].slice.call(arguments,1);while((type=types.shift())&&(callbacks=this._callbacks[type])){syncFlush=getFlush(callbacks.sync,this,[type].concat(args));asyncFlush=getFlush(callbacks.async,this,[type].concat(args));syncFlush()&&nextTick(asyncFlush)}return this}function getFlush(callbacks,context,args){return flush;function flush(){var cancelled;for(var i=0,len=callbacks.length;!cancelled&&i<len;i+=1){cancelled=callbacks[i].apply(context,args)===false}return !cancelled}}function getNextTick(){var nextTickFn;if(window.setImmediate){nextTickFn=function nextTickSetImmediate(fn){setImmediate(function(){fn()})}}else{nextTickFn=function nextTickSetTimeout(fn){setTimeout(function(){fn()},0)}}return nextTickFn}function bindContext(fn,context){return fn.bind?fn.bind(context):function(){fn.apply(context,[].slice.call(arguments,0))}}}();var highlight=function(doc){var defaults={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:false,caseSensitive:false};return function hightlight(o){var regex;o=_.mixin({},defaults,o);if(!o.node||!o.pattern){return}o.pattern=_.isArray(o.pattern)?o.pattern:[o.pattern];regex=getRegex(o.pattern,o.caseSensitive,o.wordsOnly);traverse(o.node,hightlightTextNode);function hightlightTextNode(textNode){var match,patternNode,wrapperNode;if(match=regex.exec(textNode.data)){wrapperNode=doc.createElement(o.tagName);o.className&&(wrapperNode.className=o.className);patternNode=textNode.splitText(match.index);patternNode.splitText(match[0].length);wrapperNode.appendChild(patternNode.cloneNode(true));textNode.parentNode.replaceChild(wrapperNode,patternNode)}return !!match}function traverse(el,hightlightTextNode){var childNode,TEXT_NODE_TYPE=3;for(var i=0;i<el.childNodes.length;i++){childNode=el.childNodes[i];if(childNode.nodeType===TEXT_NODE_TYPE){i+=hightlightTextNode(childNode)?1:0}else{traverse(childNode,hightlightTextNode)}}}};function getRegex(patterns,caseSensitive,wordsOnly){var escapedPatterns=[],regexStr;for(var i=0,len=patterns.length;i<len;i++){escapedPatterns.push(_.escapeRegExChars(patterns[i]))}regexStr=wordsOnly?"\\b("+escapedPatterns.join("|")+")\\b":"("+escapedPatterns.join("|")+")";return caseSensitive?new RegExp(regexStr):new RegExp(regexStr,"i")}}(window.document);var Input=function(){var specialKeyCodeMap;specialKeyCodeMap={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"};function Input(o,www){o=o||{};if(!o.input){$.error("input is missing")}www.mixin(this);this.$hint=$(o.hint);this.$input=$(o.input);this.query=this.$input.val();this.queryWhenFocused=this.hasFocus()?this.query:null;this.$overflowHelper=buildOverflowHelper(this.$input);this._checkLanguageDirection();if(this.$hint.length===0){this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=_.noop}}Input.normalizeQuery=function(str){return _.toStr(str).replace(/^\s*/g,"").replace(/\s{2,}/g," ")};_.mixin(Input.prototype,EventEmitter,{_onBlur:function onBlur(){this.resetInputValue();this.trigger("blurred")},_onFocus:function onFocus(){this.queryWhenFocused=this.query;this.trigger("focused")},_onKeydown:function onKeydown($e){var keyName=specialKeyCodeMap[$e.which||$e.keyCode];this._managePreventDefault(keyName,$e);if(keyName&&this._shouldTrigger(keyName,$e)){this.trigger(keyName+"Keyed",$e)}},_onInput:function onInput(){this._setQuery(this.getInputValue());this.clearHintIfInvalid();this._checkLanguageDirection()},_managePreventDefault:function managePreventDefault(keyName,$e){var preventDefault;switch(keyName){case"up":case"down":preventDefault=!withModifier($e);break;default:preventDefault=false}preventDefault&&$e.preventDefault()},_shouldTrigger:function shouldTrigger(keyName,$e){var trigger;switch(keyName){case"tab":trigger=!withModifier($e);break;default:trigger=true}return trigger},_checkLanguageDirection:function checkLanguageDirection(){var dir=(this.$input.css("direction")||"ltr").toLowerCase();if(this.dir!==dir){this.dir=dir;this.$hint.attr("dir",dir);this.trigger("langDirChanged",dir)}},_setQuery:function setQuery(val,silent){var areEquivalent,hasDifferentWhitespace;areEquivalent=areQueriesEquivalent(val,this.query);hasDifferentWhitespace=areEquivalent?this.query.length!==val.length:false;this.query=val;if(!silent&&!areEquivalent){this.trigger("queryChanged",this.query)}else{if(!silent&&hasDifferentWhitespace){this.trigger("whitespaceChanged",this.query)}}},bind:function(){var that=this,onBlur,onFocus,onKeydown,onInput;onBlur=_.bind(this._onBlur,this);onFocus=_.bind(this._onFocus,this);onKeydown=_.bind(this._onKeydown,this);onInput=_.bind(this._onInput,this);this.$input.on("blur.tt",onBlur).on("focus.tt",onFocus).on("keydown.tt",onKeydown);if(!_.isMsie()||_.isMsie()>9){this.$input.on("input.tt",onInput)}else{this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function($e){if(specialKeyCodeMap[$e.which||$e.keyCode]){return}_.defer(_.bind(that._onInput,that,$e))})}return this},focus:function focus(){this.$input.focus()},blur:function blur(){this.$input.blur()},getLangDir:function getLangDir(){return this.dir},getQuery:function getQuery(){return this.query||""},setQuery:function setQuery(val,silent){this.setInputValue(val);this._setQuery(val,silent)},hasQueryChangedSinceLastFocus:function hasQueryChangedSinceLastFocus(){return this.query!==this.queryWhenFocused},getInputValue:function getInputValue(){return this.$input.val()},setInputValue:function setInputValue(value){this.$input.val(value);this.clearHintIfInvalid();this._checkLanguageDirection()},resetInputValue:function resetInputValue(){this.setInputValue(this.query)},getHint:function getHint(){return this.$hint.val()},setHint:function setHint(value){this.$hint.val(value)},clearHint:function clearHint(){this.setHint("")},clearHintIfInvalid:function clearHintIfInvalid(){var val,hint,valIsPrefixOfHint,isValid;val=this.getInputValue();hint=this.getHint();valIsPrefixOfHint=val!==hint&&hint.indexOf(val)===0;isValid=val!==""&&valIsPrefixOfHint&&!this.hasOverflow();!isValid&&this.clearHint()},hasFocus:function hasFocus(){return this.$input.is(":focus")},hasOverflow:function hasOverflow(){var constraint=this.$input.width()-2;this.$overflowHelper.text(this.getInputValue());return this.$overflowHelper.width()>=constraint},isCursorAtEnd:function(){var valueLength,selectionStart,range;valueLength=this.$input.val().length;selectionStart=this.$input[0].selectionStart;if(_.isNumber(selectionStart)){return selectionStart===valueLength}else{if(document.selection){range=document.selection.createRange();range.moveStart("character",-valueLength);return valueLength===range.text.length}}return true},destroy:function destroy(){this.$hint.off(".tt");this.$input.off(".tt");this.$overflowHelper.remove();this.$hint=this.$input=this.$overflowHelper=$("<div>")}});return Input;function buildOverflowHelper($input){return $('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:$input.css("font-family"),fontSize:$input.css("font-size"),fontStyle:$input.css("font-style"),fontVariant:$input.css("font-variant"),fontWeight:$input.css("font-weight"),wordSpacing:$input.css("word-spacing"),letterSpacing:$input.css("letter-spacing"),textIndent:$input.css("text-indent"),textRendering:$input.css("text-rendering"),textTransform:$input.css("text-transform")}).insertAfter($input)}function areQueriesEquivalent(a,b){return Input.normalizeQuery(a)===Input.normalizeQuery(b)}function withModifier($e){return $e.altKey||$e.ctrlKey||$e.metaKey||$e.shiftKey}}();var Dataset=function(){var keys,nameGenerator;keys={val:"tt-selectable-display",obj:"tt-selectable-object"};nameGenerator=_.getIdGenerator();function Dataset(o,www){o=o||{};o.templates=o.templates||{};o.templates.notFound=o.templates.notFound||o.templates.empty;if(!o.source){$.error("missing source")}if(!o.node){$.error("missing node")}if(o.name&&!isValidName(o.name)){$.error("invalid dataset name: "+o.name)}www.mixin(this);this.highlight=!!o.highlight;this.name=o.name||nameGenerator();this.limit=o.limit||5;this.displayFn=getDisplayFn(o.display||o.displayKey);this.templates=getTemplates(o.templates,this.displayFn);this.source=o.source.__ttAdapter?o.source.__ttAdapter():o.source;this.async=_.isUndefined(o.async)?this.source.length>2:!!o.async;this._resetLastSuggestion();this.$el=$(o.node).addClass(this.classes.dataset).addClass(this.classes.dataset+"-"+this.name)}Dataset.extractData=function extractData(el){var $el=$(el);if($el.data(keys.obj)){return{val:$el.data(keys.val)||"",obj:$el.data(keys.obj)||null}}return null};_.mixin(Dataset.prototype,EventEmitter,{_overwrite:function overwrite(query,suggestions){suggestions=suggestions||[];if(suggestions.length){this._renderSuggestions(query,suggestions)}else{if(this.async&&this.templates.pending){this._renderPending(query)}else{if(!this.async&&this.templates.notFound){this._renderNotFound(query)}else{this._empty()}}}this.trigger("rendered",this.name,suggestions,false)},_append:function append(query,suggestions){suggestions=suggestions||[];if(suggestions.length&&this.$lastSuggestion.length){this._appendSuggestions(query,suggestions)}else{if(suggestions.length){this._renderSuggestions(query,suggestions)}else{if(!this.$lastSuggestion.length&&this.templates.notFound){this._renderNotFound(query)}}}this.trigger("rendered",this.name,suggestions,true)},_renderSuggestions:function renderSuggestions(query,suggestions){var $fragment;$fragment=this._getSuggestionsFragment(query,suggestions);this.$lastSuggestion=$fragment.children().last();this.$el.html($fragment).prepend(this._getHeader(query,suggestions)).append(this._getFooter(query,suggestions))},_appendSuggestions:function appendSuggestions(query,suggestions){var $fragment,$lastSuggestion;$fragment=this._getSuggestionsFragment(query,suggestions);$lastSuggestion=$fragment.children().last();this.$lastSuggestion.after($fragment);this.$lastSuggestion=$lastSuggestion},_renderPending:function renderPending(query){var template=this.templates.pending;this._resetLastSuggestion();template&&this.$el.html(template({query:query,dataset:this.name}))},_renderNotFound:function renderNotFound(query){var template=this.templates.notFound;this._resetLastSuggestion();template&&this.$el.html(template({query:query,dataset:this.name}))},_empty:function empty(){this.$el.empty();this._resetLastSuggestion()},_getSuggestionsFragment:function getSuggestionsFragment(query,suggestions){var that=this,fragment;fragment=document.createDocumentFragment();_.each(suggestions,function getSuggestionNode(suggestion){var $el,context;context=that._injectQuery(query,suggestion);$el=$(that.templates.suggestion(context)).data(keys.obj,suggestion).data(keys.val,that.displayFn(suggestion)).addClass(that.classes.suggestion+" "+that.classes.selectable);fragment.appendChild($el[0])});this.highlight&&highlight({className:this.classes.highlight,node:fragment,pattern:query});return $(fragment)},_getFooter:function getFooter(query,suggestions){return this.templates.footer?this.templates.footer({query:query,suggestions:suggestions,dataset:this.name}):null},_getHeader:function getHeader(query,suggestions){return this.templates.header?this.templates.header({query:query,suggestions:suggestions,dataset:this.name}):null},_resetLastSuggestion:function resetLastSuggestion(){this.$lastSuggestion=$()},_injectQuery:function injectQuery(query,obj){return _.isObject(obj)?_.mixin({_query:query},obj):obj},update:function update(query){var that=this,canceled=false,syncCalled=false,rendered=0;this.cancel();this.cancel=function cancel(){canceled=true;that.cancel=$.noop;that.async&&that.trigger("asyncCanceled",query)};this.source(query,sync,async);!syncCalled&&sync([]);function sync(suggestions){if(syncCalled){return}syncCalled=true;suggestions=(suggestions||[]).slice(0,that.limit);rendered=suggestions.length;if(suggestions.length){that._overwrite(query,suggestions)}if(rendered<that.limit&&that.async){that.trigger("asyncRequested",query)}}function async(suggestions){suggestions=suggestions||[];if(!canceled&&rendered<that.limit){that.cancel=$.noop;if(rendered===0){that._overwrite(query,suggestions.slice(0,that.limit-rendered))}else{that._append(query,suggestions.slice(0,that.limit-rendered))}rendered+=suggestions.length;that.async&&that.trigger("asyncReceived",query)}}},cancel:$.noop,clear:function clear(){this._empty();this.cancel();this.trigger("cleared")},isEmpty:function isEmpty(){return this.$el.is(":empty")},destroy:function destroy(){this.$el=$("<div>")}});return Dataset;function getDisplayFn(display){display=display||_.stringify;return _.isFunction(display)?display:displayFn;function displayFn(obj){return obj[display]}}function getTemplates(templates,displayFn){return{notFound:templates.notFound&&_.templatify(templates.notFound),pending:templates.pending&&_.templatify(templates.pending),header:templates.header&&_.templatify(templates.header),footer:templates.footer&&_.templatify(templates.footer),suggestion:templates.suggestion||suggestionTemplate};function suggestionTemplate(context){return $("<div>").text(displayFn(context))}}function isValidName(str){return/^[_a-zA-Z0-9-]+$/.test(str)}}();var Menu=function(){function Menu(o,www){var that=this;o=o||{};if(!o.node){$.error("node is required")}www.mixin(this);this.$node=$(o.node);this.query=null;this.datasets=_.map(o.datasets,initializeDataset);this.datasetsSelectOrder=o.datasetsSelectOrder;function initializeDataset(oDataset){var node=that.$node.find(oDataset.node).first();oDataset.node=node.length?node:$("<div>").appendTo(that.$node);return new Dataset(oDataset,www)}}_.mixin(Menu.prototype,EventEmitter,{_onSelectableClick:function onSelectableClick($e){this.trigger("selectableClicked",$($e.currentTarget))},_onRendered:function onRendered(type,dataset,suggestions,async){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty());this.trigger("datasetRendered",dataset,suggestions,async)},_onCleared:function onCleared(){this.$node.toggleClass(this.classes.empty,this._allDatasetsEmpty());this.trigger("datasetCleared")},_propagate:function propagate(){this.trigger.apply(this,arguments)},_allDatasetsEmpty:function allDatasetsEmpty(){return _.every(this.datasets,isDatasetEmpty);function isDatasetEmpty(dataset){return dataset.isEmpty()}},_getSelectables:function getSelectables(){if(this.datasetsSelectOrder!==undefined&&this.datasetsSelectOrder!==null&&Array.isArray&&Array.isArray(this.datasetsSelectOrder)){var result=[];for(var i=0;i<this.datasetsSelectOrder.length;i+=1){var selectableSet=this.$node.find(this.selectors.dataset+"-"+this.datasetsSelectOrder[i]+" "+this.selectors.selectable).toArray();result=result.concat(selectableSet)}return $(result)}return this.$node.find(this.selectors.selectable)},_removeCursor:function _removeCursor(){var $selectable=this.getActiveSelectable();$selectable&&$selectable.removeClass(this.classes.cursor)},_ensureVisible:function ensureVisible($el){var elTop,elBottom,nodeScrollTop,nodeHeight;elTop=$el.position().top;elBottom=elTop+$el.outerHeight(true);nodeScrollTop=this.$node.scrollTop();nodeHeight=this.$node.height()+parseInt(this.$node.css("paddingTop"),10)+parseInt(this.$node.css("paddingBottom"),10);if(elTop<0){this.$node.scrollTop(nodeScrollTop+elTop)}else{if(nodeHeight<elBottom){this.$node.scrollTop(nodeScrollTop+(elBottom-nodeHeight))}}},bind:function(){var that=this,onSelectableClick;onSelectableClick=_.bind(this._onSelectableClick,this);this.$node.on("click.tt",this.selectors.selectable,onSelectableClick);this.$node.on("mouseover",this.selectors.selectable,function(){that.setCursor($(this))});_.each(this.datasets,function(dataset){dataset.onSync("asyncRequested",that._propagate,that).onSync("asyncCanceled",that._propagate,that).onSync("asyncReceived",that._propagate,that).onSync("rendered",that._onRendered,that).onSync("cleared",that._onCleared,that)});return this},isOpen:function isOpen(){return this.$node.hasClass(this.classes.open)},open:function open(){this.$node.scrollTop(0);this.$node.addClass(this.classes.open)},close:function close(){this.$node.removeClass(this.classes.open);this._removeCursor()},setLanguageDirection:function setLanguageDirection(dir){this.$node.attr("dir",dir)},selectableRelativeToCursor:function selectableRelativeToCursor(delta){var $selectables,$oldCursor,oldIndex,newIndex;$oldCursor=this.getActiveSelectable();$selectables=this._getSelectables();oldIndex=$oldCursor?$selectables.index($oldCursor):-1;newIndex=oldIndex+delta;newIndex=(newIndex+1)%($selectables.length+1)-1;newIndex=newIndex<-1?$selectables.length-1:newIndex;return newIndex===-1?null:$selectables.eq(newIndex)},setCursor:function setCursor($selectable){this._removeCursor();if($selectable=$selectable&&$selectable.first()){$selectable.addClass(this.classes.cursor);this._ensureVisible($selectable)}},getSelectableData:function getSelectableData($el){return $el&&$el.length?Dataset.extractData($el):null},getActiveSelectable:function getActiveSelectable(){var $selectable=this._getSelectables().filter(this.selectors.cursor).first();return $selectable.length?$selectable:null},getTopSelectable:function getTopSelectable(){var $selectable=this._getSelectables().first();return $selectable.length?$selectable:null},update:function update(query){var isValidUpdate=query!==this.query;if(isValidUpdate){this.query=query;_.each(this.datasets,updateDataset)}return isValidUpdate;function updateDataset(dataset){dataset.update(query)}},empty:function empty(){_.each(this.datasets,clearDataset);this.query=null;this.$node.addClass(this.classes.empty);function clearDataset(dataset){dataset.clear()}},destroy:function destroy(){this.$node.off(".tt");this.$node=$("<div>");_.each(this.datasets,destroyDataset);function destroyDataset(dataset){dataset.destroy()}}});return Menu}();var DefaultMenu=function(){var s=Menu.prototype;function DefaultMenu(){Menu.apply(this,[].slice.call(arguments,0))}_.mixin(DefaultMenu.prototype,Menu.prototype,{open:function open(){!this._allDatasetsEmpty()&&this._show();return s.open.apply(this,[].slice.call(arguments,0))},close:function close(){this._hide();return s.close.apply(this,[].slice.call(arguments,0))},_onRendered:function onRendered(){if(this._allDatasetsEmpty()){this._hide()}else{this.isOpen()&&this._show()}return s._onRendered.apply(this,[].slice.call(arguments,0))},_onCleared:function onCleared(){if(this._allDatasetsEmpty()){this._hide()}else{this.isOpen()&&this._show()}return s._onCleared.apply(this,[].slice.call(arguments,0))},setLanguageDirection:function setLanguageDirection(dir){this.$node.css(dir==="ltr"?this.css.ltr:this.css.rtl);return s.setLanguageDirection.apply(this,[].slice.call(arguments,0))},_hide:function hide(){this.$node.hide()},_show:function show(){this.$node.css("display","block")}});return DefaultMenu}();var Typeahead=function(){function Typeahead(o,www){var onFocused,onBlurred,onEnterKeyed,onTabKeyed,onEscKeyed,onUpKeyed,onDownKeyed,onLeftKeyed,onRightKeyed,onQueryChanged,onWhitespaceChanged;o=o||{};if(!o.input){$.error("missing input")}if(!o.menu){$.error("missing menu")}if(!o.eventBus){$.error("missing event bus")}www.mixin(this);this.eventBus=o.eventBus;this.minLength=_.isNumber(o.minLength)?o.minLength:1;this.input=o.input;this.menu=o.menu;this.enabled=true;this.active=false;this.input.hasFocus()&&this.activate();this.dir=this.input.getLangDir();this._hacks();this.menu.bind().onSync("selectableClicked",this._onSelectableClicked,this).onSync("asyncRequested",this._onAsyncRequested,this).onSync("asyncCanceled",this._onAsyncCanceled,this).onSync("asyncReceived",this._onAsyncReceived,this).onSync("datasetRendered",this._onDatasetRendered,this).onSync("datasetCleared",this._onDatasetCleared,this);onFocused=c(this,"activate","open","_onFocused");onBlurred=c(this,"deactivate","_onBlurred");onEnterKeyed=c(this,"isActive","isOpen","_onEnterKeyed");onTabKeyed=c(this,"isActive","isOpen","_onTabKeyed");onEscKeyed=c(this,"isActive","_onEscKeyed");onUpKeyed=c(this,"isActive","open","_onUpKeyed");onDownKeyed=c(this,"isActive","open","_onDownKeyed");onLeftKeyed=c(this,"isActive","isOpen","_onLeftKeyed");onRightKeyed=c(this,"isActive","isOpen","_onRightKeyed");onQueryChanged=c(this,"_openIfActive","_onQueryChanged");onWhitespaceChanged=c(this,"_openIfActive","_onWhitespaceChanged");this.input.bind().onSync("focused",onFocused,this).onSync("blurred",onBlurred,this).onSync("enterKeyed",onEnterKeyed,this).onSync("tabKeyed",onTabKeyed,this).onSync("escKeyed",onEscKeyed,this).onSync("upKeyed",onUpKeyed,this).onSync("downKeyed",onDownKeyed,this).onSync("leftKeyed",onLeftKeyed,this).onSync("rightKeyed",onRightKeyed,this).onSync("queryChanged",onQueryChanged,this).onSync("whitespaceChanged",onWhitespaceChanged,this).onSync("langDirChanged",this._onLangDirChanged,this)}_.mixin(Typeahead.prototype,{_hacks:function hacks(){var $input,$menu;$input=this.input.$input||$("<div>");$menu=this.menu.$node||$("<div>");$input.on("blur.tt",function($e){var active,isActive,hasActive;active=document.activeElement;isActive=$menu.is(active);hasActive=$menu.has(active).length>0;if(_.isMsie()&&(isActive||hasActive)){$e.preventDefault();$e.stopImmediatePropagation();_.defer(function(){$input.focus()})}});$menu.on("mousedown.tt",function($e){$e.preventDefault()})},_onSelectableClicked:function onSelectableClicked(type,$el){this.select($el)},_onDatasetCleared:function onDatasetCleared(){this._updateHint()},_onDatasetRendered:function onDatasetRendered(type,dataset,suggestions,async){this._updateHint();this.eventBus.trigger("render",suggestions,async,dataset)},_onAsyncRequested:function onAsyncRequested(type,dataset,query){this.eventBus.trigger("asyncrequest",query,dataset)},_onAsyncCanceled:function onAsyncCanceled(type,dataset,query){this.eventBus.trigger("asynccancel",query,dataset)},_onAsyncReceived:function onAsyncReceived(type,dataset,query){this.eventBus.trigger("asyncreceive",query,dataset)},_onFocused:function onFocused(){this._minLengthMet()&&this.menu.update(this.input.getQuery())},_onBlurred:function onBlurred(){if(this.input.hasQueryChangedSinceLastFocus()){this.eventBus.trigger("change",this.input.getQuery())}},_onEnterKeyed:function onEnterKeyed(type,$e){var $selectable;if($selectable=this.menu.getActiveSelectable()){this.select($selectable)&&$e.preventDefault()}},_onTabKeyed:function onTabKeyed(type,$e){var $selectable;if($selectable=this.menu.getActiveSelectable()){this.select($selectable)&&$e.preventDefault()}else{if($selectable=this.menu.getTopSelectable()){this.autocomplete($selectable)&&$e.preventDefault()}}},_onEscKeyed:function onEscKeyed(){this.close()},_onUpKeyed:function onUpKeyed(){this.moveCursor(-1)},_onDownKeyed:function onDownKeyed(){this.moveCursor(+1)},_onLeftKeyed:function onLeftKeyed(){if(this.dir==="rtl"&&this.input.isCursorAtEnd()){this.autocomplete(this.menu.getActiveSelectable()||this.menu.getTopSelectable())}},_onRightKeyed:function onRightKeyed(){if(this.dir==="ltr"&&this.input.isCursorAtEnd()){this.autocomplete(this.menu.getActiveSelectable()||this.menu.getTopSelectable())}},_onQueryChanged:function onQueryChanged(e,query){this._minLengthMet(query)?this.menu.update(query):this.menu.empty()},_onWhitespaceChanged:function onWhitespaceChanged(){this._updateHint()},_onLangDirChanged:function onLangDirChanged(e,dir){if(this.dir!==dir){this.dir=dir;this.menu.setLanguageDirection(dir)}},_openIfActive:function openIfActive(){this.isActive()&&this.open()},_minLengthMet:function minLengthMet(query){query=_.isString(query)?query:this.input.getQuery()||"";return query.length>=this.minLength},_updateHint:function updateHint(){var $selectable,data,val,query,escapedQuery,frontMatchRegEx,match;$selectable=this.menu.getTopSelectable();data=this.menu.getSelectableData($selectable);val=this.input.getInputValue();if(data&&!_.isBlankString(val)&&!this.input.hasOverflow()){query=Input.normalizeQuery(val);escapedQuery=_.escapeRegExChars(query);frontMatchRegEx=new RegExp("^(?:"+escapedQuery+")(.+$)","i");match=frontMatchRegEx.exec(data.val);match&&this.input.setHint(val+match[1])}else{this.input.clearHint()}},isEnabled:function isEnabled(){return this.enabled},enable:function enable(){this.enabled=true},disable:function disable(){this.enabled=false},isActive:function isActive(){return this.active},activate:function activate(){if(this.isActive()){return true}else{if(!this.isEnabled()||this.eventBus.before("active")){return false}else{this.active=true;this.eventBus.trigger("active");return true}}},deactivate:function deactivate(){if(!this.isActive()){return true}else{if(this.eventBus.before("idle")){return false}else{this.active=false;this.close();this.eventBus.trigger("idle");return true}}},isOpen:function isOpen(){return this.menu.isOpen()},open:function open(){if(!this.isOpen()&&!this.eventBus.before("open")){this.menu.open();this._updateHint();this.eventBus.trigger("open")}return this.isOpen()},close:function close(){if(this.isOpen()&&!this.eventBus.before("close")){this.menu.close();this.input.clearHint();this.input.resetInputValue();this.eventBus.trigger("close")}return !this.isOpen()},setVal:function setVal(val){this.input.setQuery(_.toStr(val))},getVal:function getVal(){return this.input.getQuery()},select:function select($selectable){var data=this.menu.getSelectableData($selectable);if(data&&!this.eventBus.before("select",data.obj)){this.input.setQuery(data.val,true);this.eventBus.trigger("select",data.obj);this.close();return true}return false},autocomplete:function autocomplete($selectable){var query,data,isValid;query=this.input.getQuery();data=this.menu.getSelectableData($selectable);isValid=data&&query!==data.val;if(isValid&&!this.eventBus.before("autocomplete",data.obj)){this.input.setQuery(data.val);this.eventBus.trigger("autocomplete",data.obj);return true}return false},moveCursor:function moveCursor(delta){var query,$candidate,data,payload,cancelMove;query=this.input.getQuery();$candidate=this.menu.selectableRelativeToCursor(delta);data=this.menu.getSelectableData($candidate);payload=data?data.obj:null;cancelMove=this._minLengthMet()&&this.menu.update(query);if(!cancelMove&&!this.eventBus.before("cursorchange",payload)){this.menu.setCursor($candidate);if(data){this.input.setInputValue(data.val)}else{this.input.resetInputValue();this._updateHint()}this.eventBus.trigger("cursorchange",payload);return true}return false},destroy:function destroy(){this.input.destroy();this.menu.destroy()}});return Typeahead;function c(ctx){var methods=[].slice.call(arguments,1);return function(){var args=[].slice.call(arguments);_.each(methods,function(method){return ctx[method].apply(ctx,args)})}}}();(function(){var old,keys,methods;old=$.fn.typeahead;keys={www:"tt-www",attrs:"tt-attrs",typeahead:"tt-typeahead"};methods={initialize:function initialize(o,datasets){var www;datasets=_.isArray(datasets)?datasets:[].slice.call(arguments,1);o=o||{};www=WWW(o.classNames);return this.each(attach);function attach(){var $input,$wrapper,$hint,$menu,defaultHint,defaultMenu,eventBus,input,menu,typeahead,MenuConstructor;_.each(datasets,function(d){d.highlight=!!o.highlight});$input=$(this);$wrapper=$(www.html.wrapper);$hint=$elOrNull(o.hint);$menu=$elOrNull(o.menu);defaultHint=o.hint!==false&&!$hint;defaultMenu=o.menu!==false&&!$menu;defaultHint&&($hint=buildHintFromInput($input,www));defaultMenu&&($menu=$(www.html.menu).css(www.css.menu));$hint&&$hint.val("");$input=prepInput($input,www);if(defaultHint||defaultMenu){$wrapper.css(www.css.wrapper);$input.css(defaultHint?www.css.input:www.css.inputWithNoHint);$input.wrap($wrapper).parent().prepend(defaultHint?$hint:null).append(defaultMenu?$menu:null)}MenuConstructor=defaultMenu?DefaultMenu:Menu;eventBus=new EventBus({el:$input});input=new Input({hint:$hint,input:$input},www);menu=new MenuConstructor({node:$menu,datasets:datasets,datasetsSelectOrder:o.datasetsSelectOrder},www);typeahead=new Typeahead({input:input,menu:menu,eventBus:eventBus,minLength:o.minLength},www);$input.data(keys.www,www);$input.data(keys.typeahead,typeahead)}},isEnabled:function isEnabled(){var enabled;ttEach(this.first(),function(t){enabled=t.isEnabled()});return enabled},enable:function enable(){ttEach(this,function(t){t.enable()});return this},disable:function disable(){ttEach(this,function(t){t.disable()});return this},isActive:function isActive(){var active;ttEach(this.first(),function(t){active=t.isActive()});return active},activate:function activate(){ttEach(this,function(t){t.activate()});return this},deactivate:function deactivate(){ttEach(this,function(t){t.deactivate()});return this},isOpen:function isOpen(){var open;ttEach(this.first(),function(t){open=t.isOpen()});return open},open:function open(){ttEach(this,function(t){t.open()});return this},close:function close(){ttEach(this,function(t){t.close()});return this},select:function select(el){var success=false,$el=$(el);ttEach(this.first(),function(t){success=t.select($el)});return success},autocomplete:function autocomplete(el){var success=false,$el=$(el);ttEach(this.first(),function(t){success=t.autocomplete($el)});return success},moveCursor:function moveCursoe(delta){var success=false;ttEach(this.first(),function(t){success=t.moveCursor(delta)});return success},val:function val(newVal){var query;if(!arguments.length){ttEach(this.first(),function(t){query=t.getVal()});return query}else{ttEach(this,function(t){t.setVal(_.toStr(newVal))});return this}},destroy:function destroy(){ttEach(this,function(typeahead,$input){revert($input);typeahead.destroy()});return this}};$.fn.typeahead=function(method){if(methods[method]){return methods[method].apply(this,[].slice.call(arguments,1))}else{return methods.initialize.apply(this,arguments)}};$.fn.typeahead.noConflict=function noConflict(){$.fn.typeahead=old;return this};function ttEach($els,fn){$els.each(function(){var $input=$(this),typeahead;(typeahead=$input.data(keys.typeahead))&&fn(typeahead,$input)})}function buildHintFromInput($input,www){return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly",true).removeAttr("id name placeholder required").attr({autocomplete:"off",spellcheck:"false",tabindex:-1})}function prepInput($input,www){$input.data(keys.attrs,{dir:$input.attr("dir"),autocomplete:$input.attr("autocomplete"),spellcheck:$input.attr("spellcheck"),style:$input.attr("style")});$input.addClass(www.classes.input).attr({autocomplete:"off",spellcheck:false});try{!$input.attr("dir")&&$input.attr("dir","auto")}catch(e){}return $input}function getBackgroundStyles($el){return{backgroundAttachment:$el.css("background-attachment"),backgroundClip:$el.css("background-clip"),backgroundColor:$el.css("background-color"),backgroundImage:$el.css("background-image"),backgroundOrigin:$el.css("background-origin"),backgroundPosition:$el.css("background-position"),backgroundRepeat:$el.css("background-repeat"),backgroundSize:$el.css("background-size")}}function revert($input){var www,$wrapper;www=$input.data(keys.www);$wrapper=$input.parent().filter(www.selectors.wrapper);_.each($input.data(keys.attrs),function(val,key){_.isUndefined(val)?$input.removeAttr(key):$input.attr(key,val)});$input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input);if($wrapper.length){$input.detach().insertAfter($wrapper);$wrapper.remove()}}function $elOrNull(obj){var isValid,$el;isValid=_.isJQuery(obj)||_.isElement(obj);$el=isValid?$(obj).first():[];return $el.length?$el:null}})()});(function(){var typeahead=jQuery.fn.typeahead.noConflict();jQuery.fn._typeahead=typeahead;function defaultPrepare(data){var result=[];for(var i=0;i<data.items.length;i+=1){var item=data.items[i];result.push(item)}return result}function addName(name,data){var result=[];for(var i=0;i<data.length;i+=1){result.push({name:name,meta:data[i]})}return result}var searchBox=GravityRD.extend(Object,{config:{name:null,inputSelector:null,minLength:1,count:null,rateLimitWait:150,searchKey:"searchQuery",placeholder:"",startValue:null,hint:true,highlight:true,css:null,datasets:[],datasetsSelectOrder:null,datasetTemplate:{recommendation:{scenarioId:null,resultNames:null,numberLimit:null},render:{display:null,templates:{},onselect:null,css:null,onRenderDone:null,prepare:defaultPrepare}},onenter:null},_data:[],_destination:null,constructor:function(conf){var c=jQuery.extend({},this.config,conf);c.datasets=conf.datasets;this.config=c;this.initComponents()},initComponents:function(){this._destination=jQuery(this.config.inputSelector);this.inputDesign();this.dataInformation();var opts=this._data.slice();opts.unshift({hint:this.config.hint,highlight:this.config.highlight,minLength:this.config.minLength,datasetsSelectOrder:this.config.datasetsSelectOrder});var oldTypeAhead=jQuery.fn.typeahead;jQuery.fn.typeahead=typeahead;this._destination.typeahead.apply(this._destination,opts);this.setupInteraction();jQuery.fn.typeahead=oldTypeAhead},dataInformation:function(){var self=this;for(var i=0;i<this.config.datasets.length;i+=1){var conf=this.config.datasets[i];var source=new Bloodhound({initialize:true,datumTokenizer:Bloodhound.tokenizers.obj.whitespace("value"),queryTokenizer:Bloodhound.tokenizers.whitespace,sufficient:conf.recommendation.numberLimit,remote:{url:"%Q"+conf.name+".json",wildcard:"%Q",rateLimitWait:this.config.rateLimitWait,transport:(function(prepare,recommendation,name){return function(request,onSuccess,onError){function done(data){onSuccess(addName(name,prepare(data)))}var recoObject=jQuery.extend({type:"recommendation",callback:done,numberLimit:recommendation.numberLimit},recommendation);var key=decodeURIComponent(request.url.substring(0,request.url.length-(name+".json").length));recoObject[self.config.searchKey]=key;_gravity.push(recoObject)}}(conf.render.prepare!==null&&conf.render.prepare!==undefined?conf.render.prepare:defaultPrepare,conf.recommendation,conf.name))}});var typeaheadConfig={source:source.ttAdapter(),limit:conf.recommendation.numberLimit,async:true,name:conf.name,templates:conf.render.templates,baseSource:source};if(conf.render.display!==null&&conf.render.display!==undefined){typeaheadConfig.display=conf.render.display}this.addCss(conf.render.css);this._data.push(typeaheadConfig)}},inputDesign:function(){this._destination.attr("placeholder",this.config.placeholder);this._destination.removeAttr("onblur");this._destination.removeAttr("onfocus");this._destination.removeAttr("onkeydown");this._destination.removeAttr("readonly");this._destination.removeAttr("style");this._destination.attr("autocomplete","off");this._destination.attr("spellcheck","false");this._destination.val(this.config.startValue===null||this.config.startValue===undefined?"":this.config.startValue);this.addCss(this.config.css)},addCss:function(css){if(css!==null&&css!==undefined){jQuery('<style type="text/css">'+css+"</style>").appendTo("head")}},setupInteraction:function(){var self=this;function defaultOnClick(itemId){_gravity.push({type:"event",eventType:"REC_CLICK",itemId:itemId})}this._destination.on("typeahead:select",function(event,selected){if(selected===null||selected===undefined){return}var found=false;for(var i=0;i<self.config.datasets.length;i+=1){var conf=self.config.datasets[i];if(selected.name==conf.name){if(conf.render.onselect===null||conf.render.onselect===undefined){break}else{found=true;conf.render.onselect(event,selected,self.config)}}}if(!found){defaultOnClick(selected.meta.itemId)}});this._destination.on("typeahead:render",function(event,suggestion,isAsync,datasetName){if(suggestion===null||suggestion===undefined){return}for(var i=0;i<self.config.datasets.length;i+=1){var conf=self.config.datasets[i];if(suggestion.name==conf.name){if(conf.render.onRenderDone===null||conf.render.onRenderDone===undefined){break}else{conf.render.onRenderDone(event,suggestion,conf)}}}});this._destination.on("typeahead:cursorchange",function(event,suggestion){if(suggestion===null||suggestion===undefined){return}for(var i=0;i<self.config.datasets.length;i+=1){var conf=self.config.datasets[i];if(suggestion.name==conf.name){if(conf.render.onsuggestion===null||conf.render.onsuggestion===undefined){break}else{conf.render.onsuggestion(event,suggestion,self.config,self._data,self._destination)}}}});this._destination.keypress(function(e){if(e.which==13){if(self.config.onenter!==null){var oldTypeAhead=jQuery.fn.typeahead;jQuery.fn.typeahead=typeahead;self.config.onenter(self._destination.typeahead("val"),self._destination);jQuery.fn.typeahead=oldTypeAhead}return true}})}});var GravityRD_Search=GravityRD.Base.extend({__public__:["install"],entities:{},install:function(config){try{if(this.entities.hasOwnProperty(config.name)){GravityRD.Log.error("search with name "+config.name+" already exists",[config]);return}this.entities[config.name]=new searchBox(config)}catch(e){GravityRD.Log.error("Exception in search init",[e,config])}}});GravityRD.register("GravityRD","Search",new GravityRD_Search())})()};GravityRD.init({debug:true,mode:"PROD",persistUserId:true,trackLocation:true,trackReferrer:true,retargetingTrack:true,overlays:{"worldgravity.com":{retargetingTrack:false,retargeting:true}},allowOverride:["trackReferrer","trackLocation","cookieDomain","sessionStorage","mode"]},"a3e29c2");domready(function(){GravityRD.start()})})();