var kernel={debug_:!1,version_:"2015-03-29",cdrid_:"",localkernelversion_:"",localkernel_:null,localclient_:null,disableSyncPeer_:!0,maxlognum_:100,lastlogs_:[],debuglogs_:[],lasterror_:"",log:function(b){this.lastlogs_.push((new Date).toString()+" "+b);this.lastlogs_.length>this.maxlognum_&&this.lastlogs_.splice(0,1);this.debug_&&(this.localkernel_?this.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/store/log/"+this.formatDate(new Date),{},function(){},b):console.log((new Date).toString()+
" "+b))},debug:function(b){this.debug_&&(this.debuglogs_.push((new Date).toString()+" "+b),this.debuglogs_.length>this.maxlognum_&&this.debuglogs_.splice(0,1),console.log((new Date).toString()+" "+b))},readLocalStorage:function(b,c){var e=localStorage.getItem(b);if(null==e)return c;try{return JSON.parse(e)}catch(d){return localStorage.removeItem(b),c}},sendLocalKernelRequest:function(b,c){this.sendRequest("http://127.0.0.1:"+appconf.localClientPort+b,{},c)},sendRequest:function(b,c,e,d){typeof c==
"undefined"&&(c={});typeof d!="undefined"?jQuery.ajax({type:"POST",url:b,data:d,dataType:"text",headers:c,success:function(b){e(b)},error:function(){e(null)}}):jQuery.ajax({type:"GET",url:b,dataType:"text",headers:c,success:function(b){e(b)},error:function(){e(null)}})},selectArray:function(b,c,e,d){for(a in b)if(b[a][c]==e)return b[a][d];return null},diffArray:function(b,c,e){for(var b=b.sort(),c=c.sort(),d=[],f=[],g=0,h=0,i,l;;){if(g>=b.length||h>=c.length)break;e?(i=b[g][e],l=c[h][e]):(i=b[g],
l=c[h]);i==l?(g++,h++):i<l?(d.push(b[g]),g++):(f.push(c[h]),h++)}g>=b.length?f=f.concat(c.slice(h)):h>=c.length&&(d=d.concat(b.slice(g)));return{num:b.length,added:d,removed:f}},uniqueSort:function(b){var c={},e=[],d;for(s in b)d=b[s],d in c||(c[d]=!0,e.push(d));return e},uniqueSortObject:function(b,c){var b=b.sort(function(b,d){return b[c]<d[c]?-1:b[c]>d[c]?1:0}),e=[],d=null;for(s in b)d&&d[c]==b[s][c]||(d=b[s],d!=""&&e.push(d));return e},parseDivHtml:function(b,c,e,d){c=b.indexOf(e,c);if(c<0)return null;
for(var d=typeof d!="undefined"?d:1,f=c;;){e=b.indexOf("</div>",f);f=b.indexOf("<div",f);if(e<0&&f<0)return null;if(e>0&&(e<f||f<0))if(d--,0==d)return{text:b.substr(c,e-c),end:e};else f=e+6;else if(f>0&&(f<e||e<0))d++,f+=4;else return null}},parseInnerText:function(b,c,e,d){typeof e=="string"&&(e=[e]);for(var f=0;f<e.length;f++){c=b.indexOf(e[f],c);if(c<0)return null;c+=e[f].length}if(typeof d=="undefined")return b.substring(c);var e=-1,g;typeof d=="string"&&(d=[d]);for(f=0;f<d.length;f++)if(g=d[f],
null!=g){if(e=b.indexOf(g,c),e>=0)break}else{e=b.length;break}return e<0?null:{text:b.substring(c,e),end:e+(g==null?0:g.length)}},parseHtmlList:function(b,c,e,d){try{for(var f=0,g=null,h,i;;){f=b.indexOf(c,f);if(f<0)break;f+=c.length;if(typeof d=="number")h=b.substr(f,d),i=0;else if(typeof d=="string"){var l=b.indexOf(d,f);l>0?(h=b.substring(f,l),i=0,f=l+d.length):(h=b,i=f,f=b.length)}else h=b,i=f;for(var k=e,j={},m=0;m<k.length;m++)if(typeof k[m]!="undefined"){var t=k[m][0],o=this.parseInnerText(h,
i,k[m][1],k[m][2]);if(null==o)if(k[m].length==4){var q=k[m][3];if(q=="optional")o={text:"",end:i};else{for(var p=[],n=0,n=0;n<m;n++)p.push(k[n]);for(var r=0;r<q.length;r++)p.push(q[r]);for(n++;n<k.length;n++)p.push(k[n]);k=p;m--;continue}}else{j=null;break}j[t]=o.text;i=o.end}null!=j&&(null==g&&(g=[]),g.push(j))}return g}catch(u){return this.debug_&&this.log("parseHtmlList exception: "+u),null}},processCommandLastTimestamp_:0,processCommand:function(b,c,e){var d=this,f=(new Date).getTime();if(d.processCommandLastTimestamp_+
6E3>f)d.debug_&&d.log("waiting last process command completion"),setTimeout(function(){d.processCommand(b,c,e)},1E3);else if(d.debug_&&d.log("to invoke "+b+" for "+c),d.processCommandLastTimestamp_=f,window.cdworker_params=c,window.cdworker_callback=function(b){try{e(b)}catch(d){}},typeof window[b+"_run"]!="undefined")window[b+"_run"]();else f=document.getElementById("tempscript"),f=document.createElement("script"),f.src=b+".js",document.body.appendChild(f)},pulllocalport:function(b){var c=this,e=
new Date;dianshangji_bg.sendRequest(c.localkernel_,{},function(d){if(d){if(d!="TIMEOUT"){c.debug("kernel.js: pulllocalport at "+(new Date).toString()+" returns  "+d);try{var f=d.indexOf("\n"),g=d.substr(0,f);f++;var h=d.indexOf("\n",f),i=d.substr(f,h-f),l=d.substr(h+1);c.debug("kernel.js: clientchannel = "+g+", msg = "+i+", data = "+l);b(g,i,l)}catch(k){c.log(k)}}c.pulllocalport(b)}else c.debug("kernel.js: v is null"),d=new Date,e.getTime()+2E3>d.getTime()?setTimeout(function(){c.pulllocalport(b)},
1E4):c.pulllocalport(b)})},initlocalport:function(b){var c=this,e=dianshangji_bg;e.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/clientid/",{},function(d){null==d?c.log("local dianshangji kernel is NOT running"):e.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/version?_"+(new Date).getTime(),{},function(d){c.localkernelversion_=d;c.log("local dianshangji kernel (version = "+d+") is running at "+appconf.localHttpPort);c.localkernel_="http://127.0.0.1:"+appconf.localHttpPort+
"/channel/localkernel?timeout=30";c.localclient_="http://127.0.0.1:"+appconf.localClientPort+"/channel/";c.pulllocalport(b)})},e.clientid_)},postlocalport:function(b,c,e){dianshangji_bg.sendRequest(this.localclient_+b,{},function(){},c+"\n"+e)},idb_:null,closedb:function(){},opendb:function(b){var c=this;if(c.idb_)b(c.idb_);else if("indexedDB"in window){var e=indexedDB.open("kerneldb",1);e.onupgradeneeded=function(b){taobao.initdb(b.target.result)};e.onsuccess=function(d){d=d.target.result;c.idb_=
d;b(d)};e.onerror=function(){b(null)}}else b(null)},lastStoreTimestamps_:[],uniquePost:function(b,c,e){typeof c!="string"&&(c=JSON.stringify(c));this.lastStoreTimestamps_[b]=(new Date).getTime();this.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/store/"+b+"?comparemode=unique",{},function(b){e&&e(b)},c)},appendPost:function(b,c,e){typeof c!="string"&&(c=JSON.stringify(c));this.lastStoreTimestamps_[b]=(new Date).getTime();this.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/store/"+
b,{},function(b){e&&e(b)},c)},getLocalStore:function(b,c,e){this.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/selectdate/"+b+"/"+c,{},function(b){e&&e(b)})},reboot:function(){var b=this;taobao.running_=!1;setTimeout(function(){b.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/reboot",{},function(){},"")},5E3)},updateCode:function(b){var c=this;(b.match(/^ext\//)||b.match(/^ext2\//))&&dianshangji_bg.getCodeUpdate(b,function(e){e?c.sendRequest("http://127.0.0.1:"+appconf.localClientPort+
"/updatecode/"+b,{},function(){},e):c.log("getCodeUpdate failed: path = "+b)})},updateRuntime:function(b,c){var e=this;if(!b.match(/^[a-z0-9A-Z]+$/))return-1;if(b in window&&"version"in window[b]&&window[b].version==c)return 0;var d="runtime/"+b+".js";dianshangji_bg.getCodeUpdate(d,function(b){if(b)try{eval(b)}catch(c){e.log("updateRuntime exception: path = "+d+", e = "+c)}else e.log("getCodeUpdate failed: path = "+d)},kernel.debug_);return 1},checkRuntime:function(b){return b.match(/^[a-z0-9A-Z]+$/)?
b in window&&"version"in window[b]?window[b].version:0:-1},restart:function(){var b=this;b.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/startchrome?_="+(new Date).getTime(),{},function(c){b.lasterror_=c});return 0},kernelexit:function(){var b=this;b.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/kernelexit?_="+(new Date).getTime(),{},function(c){b.lasterror_=c});return 0},extupgrade:function(){var b=this;b.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/extupgrade?_="+
(new Date).getTime(),{},function(c){b.lasterror_=c});return 0},kernelupgrade:function(){var b=this;b.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/kernelupgrade?_="+(new Date).getTime(),{},function(c){b.lasterror_=c});return 0},formatDate:function(b){var c="";c+=b.getFullYear();c+="-";c+=b.getMonth()<9?"0"+(b.getMonth()+1):b.getMonth()+1;c+="-";c+=b.getDate()<10?"0"+b.getDate():b.getDate();return c},formatDateTime:function(b){var c="";c+=b.getFullYear();c+="-";c+=b.getMonth()<9?"0"+(b.getMonth()+
1):b.getMonth()+1;c+="-";c+=b.getDate()<10?"0"+b.getDate():b.getDate();c+=" ";c+=b.getHours()<10?"0"+b.getHours():b.getHours();c+=":";c+=b.getMinutes()<10?"0"+b.getMinutes():b.getMinutes();c+=":";c+=b.getSeconds()<10?"0"+b.getSeconds():b.getSeconds();return c},invoke:function(b,c,e,d){var f=c.indexOf(" "),g="";f>0&&(g=c.substr(f+1),c=c.substr(0,f));switch(c){case "eval":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}try{var h=eval(e);d({code:0,result:h})}catch(i){d({code:-3,
exception:i})}break;case "tail":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}try{kernel.sendRequest("http://127.0.0.1:"+appconf.localClientPort+"/tail/"+e,{},function(b){d({code:0,result:b})})}catch(l){d({code:-3,exception:l})}break;case "updateruntime":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}e=e.split(" ");b=e[0];d({code:0,res:kernel.updateRuntime(b,e[1])});break;case "checkruntime":d({code:0,version:kernel.checkRuntime(e)});
break;case "callruntime":try{var k=JSON.parse(e),j=window[k.component];if(typeof j=="undefined"){d({code:-2});break}j.call(k,d);break}catch(m){d({code:-1});break}case "lastlog":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}d({code:0,taobaoWorkload:taobao.getWorkload(),result:this.lastlogs_});break;case "setconfig":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}j=JSON.parse(e);e=localStorage.getItem("myconfig");
if(!e){localStorage.setItem("myconfig",JSON.stringify(j));d({code:0});break}e=JSON.parse(e);if(j.version<=e.version){d({code:-3});break}localStorage.setItem("myconfig",JSON.stringify(j));d({code:0});break;case "getconfig":b=localStorage.getItem("grant");if(null==b){d({code:-2});break}if(b!=g){d({code:-1});break}j=(j=localStorage.getItem("myconfig"))?JSON.parse(j):{version:0};d({code:0,res:j});break;case "getgrant":if(!b.match(/^localclient_/)){d("");break}b=localStorage.getItem("grant");if(null==
b){d("");break}cdform.invokeMaster("setgrant "+b,function(b){kernel.debug("updated kernel grant to master: "+b)});e=b.split(" ");d(e[0]);break;case "setgrant":if(!b.match(/^localclient_/)){d("");break}localStorage.getItem("grant")?d(localStorage.getItem("grant")):(localStorage.setItem("grant",e),d(e),cdform.invokeMaster("setgrant "+e,function(b){kernel.debug("master setgrant returns: "+b)}));break;case "removegrant":b=localStorage.getItem("grant");if(null==b){d({code:0});break}if(b!=g){d({code:-1});
break}kernel.debug("removegrant from "+e);localStorage.removeItem("grant");d({code:0});break;case "sync":if(g!=localStorage.getItem("grant")){d("");break}g=JSON.parse(e);h=localStorage.getItem("profile");j=null==h?{version:1}:JSON.parse(h);j.version>g.version?(kernel.debug("my profile version = "+j.version+", while peer "+b+" profile version = "+g.version),d(h)):j.version<g.version?typeof g.data!="undefined"?(localStorage.setItem("profile",e),kernel.debug("updated profile version = "+j.version+" to peer "+
b+" profile version = "+g.version),d(e)):(kernel.debug("wait for peer "+b+" sync with data of version = "+g.version),d(JSON.stringify({version:j.version}))):(kernel.debug("peer "+b+" has same version of "+j.version),d(JSON.stringify({version:j.version})));break;case "connect":kernel.debug("peer "+b+" connect");d(JSON.stringify({version:this.version_}));break;default:this.debug("kernel unknown command:"+c),d("")}},keepalive:function(){var b=this;setTimeout(function(){b.keepalive()},6E4);b.syncAll()},
syncAll:function(){if(cdform.isopened()){var b=localStorage.getItem("grant");null==b||b.length==0||b.indexOf(" ")<0||cdform.invokeMaster("setgrant "+b,function(){})}},sync:function(b,c){var e=this,d=b[c];kernel.debug("sync with peer["+c+"], cid = "+d);cdform.resolvePeer(d,function(f){if(null==f||f.length==0)kernel.debug("peer "+d+" is not available now");else{var g=localStorage.getItem("profile"),h;h=null==g?{version:1}:JSON.parse(g);cdform.invokeNode(d,"/kernel/sync "+localStorage.getItem("grant"),
JSON.stringify({version:h.version}),function(i){try{if(null==i)kernel.debug("peer "+d+" cdr = "+f+" timeout on sync");else if(i.length==0)kernel.debug("peer "+d+" cdr = "+f+" sync with 0 length");else if(peerprofile=JSON.parse(i),peerprofile.version>h.version)kernel.debug("updated my version "+h.version+" to peer "+d+" larger version "+peerprofile.version),localStorage.setItem("profile",i),h=peerprofile,g=i;else if(peerprofile.version<h.version){kernel.debug("force peer "+d+" version = "+peerprofile.version+
" to sync data with my version = "+h.version);cdform.invokeNode(d,"/kernel/sync "+localStorage.getItem("grant"),g,function(g){null==g?kernel.debug("peer "+d+" cdr = "+f+" timeout on sync"):g.length==0?kernel.debug("peer "+d+" cdr = "+f+" sync with 0 length"):(peerprofile=JSON.parse(g),peerprofile.version==h.version?kernel.debug("peer "+d+" cdr = "+f+" has synced with me of version = "+h.version):kernel.debug("peer "+d+" cdr = "+f+" failed sync with me of version = "+h.version));c+1<b.length?e.sync(b,
c+1):kernel.debug("all peers should have synced to version = "+h.version)});return}}catch(l){kernel.debug("sync with peer "+d+" exception: "+l)}c+1<b.length?e.sync(b,c+1):kernel.debug("all peers synced to version = "+h.version)})}})},fixsettings:function(){chrome.contentSettings.images.set({primaryPattern:"<all_urls>",setting:"allow"});chrome.webRequest.onBeforeSendHeaders.addListener(function(b){if(b.url.match(/^http:\/\/127.0.0.1/))return b.requestHeaders.push({name:"Referer",value:"http://www.dianshangji.com/"}),
{requestHeaders:b.requestHeaders};if(b.url.indexOf("taobao.com")<0&&b.url.indexOf("tmall.com")<0)return{};if(b.url.indexOf("_ksTS=")>0&&(b.url.match(/^http:\/\/ext.mdskip.taobao.com\/extension\/dealRecords.htm/)||b.url.match(/^http:\/\/rate.tmall.com\/list_detail_rate.htm/)||b.url.match(/http:\/\/rate.taobao.com\/feedRateList.htm/)))return{cancel:!0};for(var c=[],e,d,f=0;f<b.requestHeaders.length;++f)e=b.requestHeaders[f].name,d=b.requestHeaders[f].value,e.match(/^fixh-/)?c.push({name:e.substr(5),
value:d}):e=="User-Agent"&&(b.url.match(/^http:\/\/m\.taobao\.com/)||b.url.match(/^http:\/\/[a-z0-9\.]*\.m\.taobao\.com\//))?c.push({name:e,value:"Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.133 Mobile Safari/535.19"}):c.push(b.requestHeaders[f]);return{requestHeaders:c}},{urls:["<all_urls>"]},["blocking","requestHeaders"]);chrome.webRequest.onHeadersReceived.addListener(function(b){if("type"in b&&b.type=="other"&&(b=b.url,
b.match(/\.flv?/)||b.match(/\.flv$/)||b.match(/\.swf?/)||b.match(/\.swf$/)))return{cancel:!0}},{urls:["<all_urls>"]},["blocking"])},run:function(){var b=this,c=dianshangji_bg;b.fixsettings();c.kernel_=b;b.keepalive();var e=function(c,d,e){typeof d!="string"&&(d=JSON.stringify(d));typeof e!="string"&&(e=JSON.stringify(e));c.match(/^localclient_/)?b.postlocalport(c,d,e):cdform.postpeer(c,"msg "+d,e)},d=function(d,c,h){if(c=="/probe")e(d,c,JSON.stringify({code:1}));else if(b.debug("kernel.js: from = "+
d+", msg = "+c+", data = "+h),c.match(/^\/kernel\//)){var i=c.substr(8);b.invoke(d,i,h,function(b){e(d,c,b)})}else c.match(/^\/taobao\//)?(i=c.substr(8),taobao.invoke(d,i,h,function(b){e(d,c,b)})):e(d,c,"echo "+h)};cdform.init(c.clientid_,function(c){b.cdrid_=c;b.debug("kernel.js: my cdrid = "+c)},function(c,e,h){e.match(/^msg /)?d(c,e.substr(4),h):b.debug("invalid msg: "+e)});b.initlocalport(d);b.opendb(function(){kernel.debug("kerneldb opened");setTimeout(function(){taobao.run()},1E4)})}};
dianshangji_bg.clientid_==""?setTimeout(function(){kernel.run()},3E3):kernel.run();
