var taobao={fullspeed_:{listShopMilliSeconds_:1E4,waitSecondsPerShop_:10,waitSecondsPerItemRelated_:12,waitSecondsPerItem_:3,waitDealSeconds_:5},opentabs_:{},listShopMilliSeconds_:1E4,waitSecondsPerShop_:10,waitSecondsPerItemRelated_:12,waitSecondsPerItem_:3,waitDealSeconds_:5,maxPageCount_:100,maxCategoryCount_:100,running_:!0,disableShopCategory_:!1,disableShopModule_:!1,cookie_:"",version_:"2015-05-16_2",itemDealAccessTime_:{},shoptypes_:{},numericHash:function(a){for(var a=parseInt(a),b=0;a>0;)b+=
a%100,b>=100&&(b%=100),a=Math.floor(a/100);return b},setSpeedRatio:function(a){this.listShopMilliSeconds_=this.fullspeed_.listShopMilliSeconds_*(1/a);this.waitSecondsPerShop_=this.fullspeed_.waitSecondsPerShop_*(1/a);this.waitSecondsPerItemRelated_=this.fullspeed_.waitSecondsPerItemRelated_*(1/a);this.waitSecondsPerItem_=this.fullspeed_.waitSecondsPerItem_*(1/a)},getShopIds:function(){return kernel.readLocalStorage("taobao_shops",[])},getWorkload:function(){return Math.floor(this.dealQueue_.length*
this.waitDealSeconds_)},getSpeedRatio:function(){return parseFloat(localStorage.getItem("_speedratio"))},invoke:function(a,b,d,e){var g=b.indexOf(" "),f="",h="";g>0&&(f=h=b.substr(g+1),b=b.substr(0,g));switch(b){case "stat":a={running:this.running_,shops:this.getShops(),workload:this.getWorkload(),speedratio:localStorage.getItem("_speedratio")};e(JSON.stringify(a));break;case "getshopdata":var d=h.split(" "),a=d[0],j=d[1],d=d[2],g="shop"+j;typeof d!="undefined"&&(g+="/"+d);kernel.getLocalStore(a,
g,function(a){kernel.log(b+" "+h+" returns "+a);e(a)});break;case "selectshop":taobaoquery.query(h,e,a);break;case "run":if(f!=localStorage.getItem("grant")){e("");break}kernel.log("taobao runs now");this.running_=!0;e("run ok");break;case "setspeed":if(f!=localStorage.getItem("grant")){e("");break}kernel.log("set speed as "+d);a=parseFloat(d);this.setSpeedRatio(a);localStorage.setItem("_speedratio",a.toString());e("speed ok");break;case "stop":if(f!=localStorage.getItem("grant")){e("");break}kernel.log("taobao stops now");
this.running_=!1;e("stop ok");break;case "addShop":if(f!=localStorage.getItem("grant")){e("");break}kernel.log("add shop "+d+" and run now");this.running_=!0;e(JSON.stringify(this.addShop(d)));break;case "removeShop":if(f!=localStorage.getItem("grant")){e("");break}e(JSON.stringify(this.removeShop(d)));break;case "findshopbyitem":if(f!=localStorage.getItem("grant")){e("");break}this.findshopbyitem(d,e);break;case "findshop":if(f!=localStorage.getItem("grant")){e("");break}this.findshop(d,e);break;
case "getMobileShopPage":if(f!=localStorage.getItem("grant")){e("");break}j=d;kernel.sendRequest("http://shop.m.taobao.com/shop/shopIndex.htm?shop_id="+j,{},function(a){kernel.log("shop "+j+" returns html of "+a.length+" bytes");e(JSON.stringify({shop:j,html:a}))});break;default:kernel.log("taobao unknown command: from = "+a+", cmd = "+b),e("unknown command")}},initdb:function(a){a.objectStoreNames.contains("taobaoshop")||(a=a.createObjectStore("taobaoshop",{autoIncrement:!0}),a.createIndex("shop",
"shop",{unique:!1}),a.createIndex("timestamp","timestamp",{unique:!1}));kernel.log("kerneldb taobao inited")},addShop:function(a){var a=parseInt(a),b=this.getShops(),d=[];for(s in b){if(b[s].shopid==a)return b;d.push(b[s].shopid)}d.push(a);localStorage.setItem("taobao_shops",JSON.stringify(d));kernel.log("add shopid = "+a+", nick = "+localStorage.getItem("shop"+a));for(s in d)a=d[s],b=localStorage.getItem("shop"+a),d[s]=b?{shopid:a,nick:b}:{shopid:a,nick:""};return d},getShops:function(){var a=this.getShopIds(),
b=[];for(s in a){var d=localStorage.getItem("shop"+a[s]);d?b.push({shopid:a[s],nick:d}):b.push({shopid:a[s],nick:""})}return b},removeShop:function(a){var a=parseInt(a),b=this.getShopIds(),d=[];for(s in b)b[s]!=a&&d.push(b[s]);localStorage.setItem("taobao_shops",JSON.stringify(d));kernel.log("remove shopid = "+a);return this.getShops()},starttime_:0,endtime_:0,iterationShopPeriod_:600,iterateShops:function(){var a=this;if(a.running_){var b=a.getShopIds();if(b.length==0)a.running_=!1,setTimeout(function(){a.iterateShops()},
5E3);else{a.starttime_=(new Date).getTime();kernel.log("iterateShops begin");var d=function(b,g){if(g+1<b.length)setTimeout(function(){a.iterateShop(b,g+1,d)},a.listShopMilliSeconds_);else if(a.endtime_=(new Date).getTime(),kernel.log("iterateShops completed"),a.starttime_>a.endtime_||a.starttime_+a.iterationShopPeriod_*1E3<=a.endtime_)a.iterateShops();else{var f=(a.starttime_+a.iterationShopPeriod_*1E3-a.endtime_)/1E3;kernel.log("next iterateShops will be "+f+" seconds later");setTimeout(function(){a.iterateShops()},
f*1E3)}};a.iterateShop(b,0,d)}}else setTimeout(function(){a.iterateShops()},5E3)},createtab:function(a,b){var d=this;try{var e=0,g=(new Date).getTime();for(t in d.opentabs_)d.opentabs_[t]+3E5<g?(kernel.log("remove too old tab: "+t),d.removetab(t)):e++;e>4?(kernel.log("total opened tab num = "+e+", wait 5 seconds for "+JSON.stringify(a)),setTimeout(function(){d.createtab(a,b)},5E3)):chrome.tabs.create(a,function(a){var e=a.id;e in d.opentabs_&&(kernel.log("recycle tabId = "+e+" opened at "+d.opentabs_[e]),
delete d.opentabs_[e]);d.opentabs_[e]=g;b(a)})}catch(f){kernel.log("createtab options = "+JSON.stringify(a)+", exception: "+f),b(null)}},removetab:function(a){try{chrome.tabs.remove(parseInt(a),function(){}),a in this.opentabs_&&delete this.opentabs_[a]}catch(b){kernel.log("removetab tabid = "+a+", exception = "+b)}},retrieveShopNewon:function(a,b){var d=this;kernel.log("retrieveShopNewon: shop = "+a);var e="http://shop"+a+".taobao.com/search.htm?search=y&orderType=newOn_desc&tsearch=y";try{d.createtab({url:e},
function(e){if(null==e)b(!1,[]);else{var g=e.id;d.queryCookie(g,2);setTimeout(function(){try{chrome.tabs.executeScript(g,{code:"var a = {html:document.body.outerHTML};a;",allFrames:!1},function(e){d.removetab(g);try{var f=e[0].html;if(f){var j=d.parseShopListPage(0,f,!1);j?b(!0,j.itemids):(kernel.log("parseShopListPage fatal for newon: shop = "+a),b(!1,[]))}else kernel.log("retrieveShopNewon: shop = "+a+", html = null"),b(!1,[])}catch(o){kernel.log("retrieveShopNewon exception2: "+o),b(!1,[])}})}catch(e){kernel.log("retrieveShopNewon executeScript exception: "+
e),d.removetab(g),b(!1,[])}},5E3)}})}catch(g){kernel.log("retrieveShopNewon exception: "+g.toString()+", url = "+e),b(!1,[])}},retrieveShopHome:function(a,b){var d=this;kernel.log("retrieveShopHome: shop = "+a);var e;try{d.createtab({url:"http://shop"+a+".taobao.com"},function(e){if(null==e)b(!0,{});else{var g=e.id;setTimeout(function(){chrome.tabs.executeScript(g,{code:"scroll(0,window.innerHeight)",allFrames:!1})},7E3);setTimeout(function(){chrome.tabs.executeScript(g,{code:"scroll(0,window.innerHeight * 2)",
allFrames:!1})},8E3);setTimeout(function(){chrome.tabs.executeScript(g,{code:"scroll(0,window.innerHeight * 3)",allFrames:!1})},9E3);setTimeout(function(){try{chrome.tabs.executeScript(g,{code:'scroll(0,0);var links = document.links;var a=[];for(l in links) {var link=links[l];if(typeof(link.getBoundingClientRect) == "undefined" || typeof(link.href) == "undefined") continue;  a.push(link.href);} a;',allFrames:!1},function(e){try{d.removetab(g);var f=e[0],e=[],j=[],o=[];for(l in f){var y=f[l],A=d.parseChannel(y);
if(A)e.push(d.refineHref(A));else{var v=d.parseCategory(y);if(v)j.push(d.refineHref(v));else{var p=d.parseItemid(y);if(p)try{o.push(parseInt(p))}catch(w){}}}}b(!0,{channels:kernel.uniqueSort(e),categories:kernel.uniqueSort(j),items:kernel.uniqueSort(o)})}catch(x){kernel.log("retrieveShopHome shop = "+a+", exception = "+x),b(!1,{})}})}catch(e){kernel.log("retrieveShopHome shop = "+a+", exception = "+e),d.removetab(g),b(!1,{})}},1E4)}})}catch(g){b(!1,{})}},retrieveShopAllPages:function(a,b,d){var e=
this,g=a[b],f={blocks:[],itemids:[],itemtable:{}},h=function(j,k,m){0==k&&f.itemids.length>0&&e.retrieveShopSeller(g,f.itemids[0],function(){});if(m)if(k+1<j&&k+1<e.maxPageCount_)setTimeout(function(){e.retrieveShopPage(g,k+1,f,h)},e.listShopMilliSeconds_);else{kernel.log("shop = "+g+", item count = "+f.itemids.length);kernel.uniquePost("shop"+g+"/list",f.itemids);var j=!1,n=e.itemqueue_;for(i in n)if(n[i].shop==g){n[i].itemids=kernel.uniqueSort(n[i].itemids.concat(f.itemids));j=!0;break}j||e.itemqueue_.push({shop:g,
itemids:f.itemids});j=!1;n=e.shopqueue_;for(i in n)if(n[i].shop==g){j=!0;break}j||e.shopqueue_.push({shop:g,blocks:f.blocks,items:[]});j=!1;n=e.itemrelatedqueue_;for(i in n)if(n[i].shop==g){j=!0;break}j||e.itemrelatedqueue_.push({shop:g,items:f.itemids});d(a,b,m)}else d(a,b,!1)};e.retrieveShopPage(g,0,f,h)},iterateShop:function(a,b,d){var e=this;if(e.running_){kernel.log("iterateShop: shopindex = "+b);var g=a[b];e.retrieveShopHome(g,function(f,h){f&&(kernel.log("shop "+g+" channels = "+("channels"in
h?h.channels.length:0)+", categories = "+("categories"in h?h.categories.length:0)+", items = "+("items"in h?h.items.length:0)),kernel.uniquePost("shop"+g,h));e.retrieveShopNewon(g,function(f,h){f&&(kernel.log("shop "+g+" newon items = "+h.length),kernel.uniquePost("shop"+g+"/newon",h));e.retrieveShopAllPages(a,b,d)})})}else setTimeout(function(){e.iterateShop(a,b,d)},5E3)},iterateList:function(a,b,d,e,g){if(b.length==0)e(!0);else{var f=function(h,j){j?h+1<b.length?g?setTimeout(function(){d(a,b,h+
1,f)},g*1E3):d(a,b,h+1,f):e(!0):e(!1)};d(a,b,0,f)}},retrieveShopModule:function(a,b,d,e){var g=this;if(g.running_)if(g.disableShopModule_)e(d,!0);else{kernel.log("retrieveShopModule: module title = "+b[d].title+", index = "+d);var f=b[d],h={shopid:a,modules:b};!("channels"in f)||0==f.channels.length?e(d,!0):g.iterateList(h,f.channels,function(a,b,d,e){g.retrieveShopChannel(a,b,d,e)},function(a){e(d,a)},2)}else setTimeout(function(){g.retrieveShopModule(a,b,d,e)},5E3)},parseShopModule:function(a,b){for(var d=
[],e=0;;){var g=kernel.parseDivHtml(a,e,'class="J_TModule');if(!g)break;var e=g.end,f=g.text;if(!(f.indexOf("<a")<0)){var h=kernel.parseInnerText(f,0,'data-title="','"');h||(h="\u81ea\u5b9a\u4e49");h=h.text.trim();if(h.length!=0&&h!="\u641c\u7d22\u5217\u8868"){var j=kernel.parseInnerText(f,0,'data-widgetid="','"');if(j){if(j=j.text.trim(),j.length!=0){(g=kernel.parseInnerText(f,0,'myrect="','"'))&&(g=this.parseMyrect(g.text));var k=kernel.parseInnerText(f,0,["<h3>","<span",">"],"</span>"),k=k?k.text.trim():
"";if(h!="\u81ea\u5b9a\u4e49\u5185\u5bb9\u533a"){var m=!1;for(em in b)if(b[em].title==h&&b[em].htitle==k){m=!0;break}if(m)continue}var n=kernel.parseHtmlList(f,"<a",[["href",'href="','"']]),f=[],m=[];for(l in n){var o=n[l].href,y=this.parseChannel(o);if(y)f.push(this.refineHref(y));else if(o=this.parseItemid(o))try{m.push(parseInt(o))}catch(A){kernel.log("parse J_TMOdule invalid itemid: "+o)}}f=kernel.uniqueSort(f);m=kernel.uniqueSort(m);if(!(m.length==0&&f.length==0)){h={title:h,widgetid:j,htitle:k};
if(m.length>0)h.itemids=m;if(f.length>0)h.channels=f;if(g)h.rect=g;d.push(h)}}}else kernel.log("parse J_TModule data-widgetid not found")}}}return d},retrieveShopChannel:function(a,b,d,e){var g=this;kernel.log("retrieveShopChannel: channel href = "+b[d]+", index = "+d);var f=b[d];kernel.sendRequest(f,{},function(h){h?(b[d]={href:f,modules:g.parseShopModule(h,a.modules)},e(d,!0)):e(d,!1)})},iterateShopCategory:function(a,b,d){var e=this;if(e.disableShopCategory_)d(!0);else{var g=function(f,h){kernel.log("iterateShopCategory return categoryIndex = "+
f+", ok = "+h);if(h){var j=b[f];kernel.uniquePost("shop"+a+"/category/"+j.id,kernel.uniqueSort(j.itemids));delete j.itemids;f+1<b.length&&f+1<e.maxCategoryCount_?(f++,setTimeout(function(){e.iterateShopCategoryPage(a,b[f],f,g)},e.listShopMilliSeconds_)):d(!0)}else d(!1)};e.iterateShopCategoryPage(a,b[0],0,g)}},iterateShopCategoryPage:function(a,b,d,e){var g=this;kernel.log("iterateShopCategoryPage: shop = "+a+", category.id = "+b.id+", category.title = "+b.title);b.itemids=[];var f=function(h,j,k){kernel.log("iterateShopCategoryPage return shop = "+
a+", category.id = "+b.id+", category.title = "+b.title+", itemids = "+b.itemids.length+", pagecount = "+h+", pageindex = "+j+", ok = "+k);k?j+1<h?setTimeout(function(){g.retrieveShopCategoryPage(a,b,j+1,f)},g.listShopMilliSeconds_):e(d,k):e(d,!1)};g.retrieveShopCategoryPage(a,b,0,f)},retrieveShopCategoryPage:function(a,b,d,e){var g=this;if(g.running_){kernel.log("retrieveShopCategoryPage: shop = "+a+", category.id = "+b.id+", category.title = "+b.title+", pageindex = "+d);var f=d+1,h=[],j="http://shop"+
a+".taobao.com/category-"+b.id+".htm?pageNo="+(d+1);try{g.createtab({url:j},function(j){if(null==j)e(f,d,!1);else{var n=j.id;g.queryCookie(n,2);setTimeout(function(){try{chrome.tabs.executeScript(n,{code:"var a = {html:document.body.outerHTML};a;",allFrames:!1},function(j){g.removetab(n);try{try{var m=g.parseShopListPage(d,j[0].html,!1);if(m){f=m.pagecount;h=m.itemids;for(i in h)b.itemids.push(h[i]);e(f,d,!0)}else kernel.log("retrieveShopCategoryPage parseShopListPage fatal: shop = "+a+", pageindex = "+
d),e(f,d,!1)}catch(k){kernel.log("retrieveShopCategoryPage exception: "+k),e(f,d,!1)}}catch(o){kernel.log("retrieveShopCategoryPage exception2: "+o),e(f,d,!1)}})}catch(j){kernel.log("retrieveShopCategoryPage exception: "+j),g.removetab(n),e(f,d,!1)}},5E3)}})}catch(k){kernel.log("retrieveShopCategoryPage exception: "+k.toString()+", url = "+j),e(f,d,!1)}}else setTimeout(function(){g.retrieveShopCategoryPage(a,b,d,e)},5E3)},retrieveShopPage:function(a,b,d,e){var g=this;if(g.running_){kernel.log("retrieveShopPage: shop = "+
a+", pageindex = "+b+", shopdata.itemids.length = "+d.itemids.length);var f=b+1,h=[],j="http://shop"+a+".taobao.com/search.htm?viewType=grid&scene=taobao_shop&keyword=&search=y&orderType=&tsearch=y&pageNo="+(b+1);try{g.createtab({url:j},function(j){if(null==j)e(f,b,!1);else{var k=j.id;g.queryCookie(k,2);setTimeout(function(){try{chrome.tabs.executeScript(k,{code:"var a = {html:document.body.outerHTML};a;",allFrames:!1},function(j){g.removetab(k);try{var m=j[0].html;if(m){var o;o=b==0?!0:!1;var p=
g.parseShopListPage(b,m,o);if(p){if(o&&"blocks"in p)d.blocks=p.blocks;f=p.pagecount;h=p.itemids;var w;for(i in h)w=h[i],w in d.itemtable||(d.itemtable[w]=!0,d.itemids.push(w));e(f,b,!0)}else kernel.log("parseShopListPage fatal: shop = "+a+", pageindex = "+b),e(f,b,!1)}else kernel.log("retrieveShopListPage: shop = "+a+", pageindex = "+b+", html = null"),e(b+1,b,!1)}catch(x){kernel.log("retrieveShopPage exception2: "+x),e(f,b,!1)}})}catch(j){kernel.log("retrieveShopPage executeScript exception: "+j),
g.removetab(k),e(f,b,!1)}},5E3)}})}catch(k){kernel.log("retrieveShopPage exception: "+k.toString()+", url = "+j),e(f,b,!1)}}else setTimeout(function(){g.retrieveShopPage(a,b,d,e)},5E3)},parseMyrect:function(a){a=a.split(",");return[parseInt(a[0]),parseInt(a[1]),parseInt(a[2]),parseInt(a[3])]},refineHref:function(a){var b,d=a.indexOf("?");if(d<0)return a;b=a.substr(d+1);a=a.substr(0,d)+"?";b=b.split("&");for(var d=[],e=0;e<b.length;e++){var g=b[e];g.match(/^spm=/)||g.match(/^_tb_token_=/)||d.push(g)}return a+
d.join("&")},parseChannel:function(a){if(a.indexOf(".com/p/rd")<0&&a.indexOf(".com/campaign.htm")<0)return null;var b=a.indexOf("?");b>0&&(a=a.substr(0,b));return a},parseCategory:function(a){if(a.indexOf(".com/category.htm?")>0)return null;else if(a.indexOf(".com/category-")>0){var b=a.indexOf("?");b>0&&(a=a.substr(0,b));return a}else return null},parseItemid:function(a){if(a.indexOf("/item.htm")<0)return null;a=a.replace(/&amp;/g,"&");0==a.indexOf("http://")?a=a.substr(7):0==a.indexOf("https://")&&
(a=a.substr(8));var b="mallstItemId=",d=a.indexOf(b);if(d<0&&(b="itemId=",d=a.indexOf(b),d<0&&(b="item_id=",d=a.indexOf(b),d<0&&(b="&id=",d=a.indexOf(b),d<0&&(b="?id=",d=a.indexOf(b),d<0)))))return null;d+=b.length;b=a.indexOf("&",d);b<0&&(b=a.indexOf("#",d));if(b<0)b=a.length;a=parseInt(a.substring(d,b));return null==a?null:a},parseShopListPageBlock:function(a){var b={},d=kernel.parseHtmlList(a,"/category",[["id","-",".htm"],["title",">","<"]]);if(d)try{var e=[];for(c in d){var g=parseInt(d[c].id);
isNaN(g)||e.push(g+"_"+d[c].title.trim())}e=kernel.uniqueSort(e);for(c in e){var f=e[c],h=f.indexOf("_");e[c]={id:parseInt(f.substr(0,h)),title:f.substr(h+1)}}if(e.length>0)b.categories=e}catch(j){}b.modules=this.parseShopModule(a,[]);return b},parseShopListPage:function(a,b,d){try{var e={pagecount:0,itemids:[]},g=kernel.parseInnerText(b,0,'"J_TItems"','"pagination"');g||(g=kernel.parseInnerText(b,0,'"shop-filter"','"pagination"'));if(!g){if(b.indexOf('class="item-not-found"')>0)return e;if(b.indexOf("\u6ca1\u627e\u5230\u7b26\u5408\u6761\u4ef6\u7684\u5546\u54c1")>
0)return e;kernel.log("item list not found: pageindex = "+a);return null}var g=g.text,f=kernel.parseHtmlList(g,'class="item',[["itemid",'data-id="','"']]);if(!f)return e;try{for(i in f)f[i]=parseInt(f[i].itemid)}catch(h){return kernel.log("parseShopListPage parse itemid exception"),e}e.itemids=kernel.uniqueSort(f);e.pagecount=b.indexOf(">"+(a+1)+"/"+(a+1)+"<")>0||b.indexOf('<a class="disable">\u4e0b\u4e00\u9875</a>')>0?a+1:a+2;if(d)try{e.blocks=this.parseShopListPageBlock(b)}catch(j){kernel.log("parseShopListPageOptional exception: "+
j)}return e}catch(k){return kernel.log("parseShopListPage exception: "+k),null}},itemrelatedqueue_:[],iterateItemRelatedQueue:function(){var a=this;if(a.itemrelatedqueue_.length==0||!a.running_)setTimeout(function(){a.iterateItemRelatedQueue()},5E3);else{var b=a.itemrelatedqueue_.splice(0,1)[0];b.items.length==0?setTimeout(function(){a.iterateItemRelatedQueue()},5E3):(setTimeout(function(){a.iterateItemRelatedQueue()},(b.items.length*(a.waitSecondsPerItemRelated_+1)+1)*1E3),a.iterateList(b.shop,b.items,
function(d,e,g,f){a.retrieveItemRelated(b.shop,e[g],g==0?!0:!1);f(g,!0)},function(a){kernel.log("iterateItemRelated ok = "+a+": shop = "+b.shop+", itemids = "+b.items.length)},a.waitSecondsPerItemRelated_))}},shopqueue_:[],iterateShopQueue:function(){var a=this;if(a.shopqueue_.length==0||!a.running_)setTimeout(function(){a.iterateShopQueue()},5E3);else{var b=a.shopqueue_.splice(0,1)[0];a.iterateShopBlock(b.shop,b.blocks,function(b){b?setTimeout(function(){a.iterateShopQueue()},a.waitSecondsPerShop_*
1E3):setTimeout(function(){a.iterateShopQueue()},6E4)})}},iterateShopModule:function(a,b,d){var e=this;e.iterateList(a,b,function(a,b,d,j){e.retrieveShopModule(a,b,d,j)},function(e){e&&kernel.uniquePost("shop"+a+"/shopmodule",b);d(e)},1)},iterateShopBlock:function(a,b,d){var e=this;"categories"in b?(kernel.uniquePost("shop"+a+"/category",b.categories),e.iterateShopCategory(a,b.categories,function(g){g?"modules"in b&&e.iterateShopModule(a,b.modules,d):d(g)})):"modules"in b&&e.iterateShopModule(a,b.modules,
d)},itemqueue_:[],iterateItemQueue:function(){var a=this;if(a.itemqueue_.length==0||!a.running_)setTimeout(function(){a.iterateItemQueue()},5E3);else{var b=a.itemqueue_.splice(0,1)[0];a.iterateShopItem(b.shop,b.itemids,function(){setTimeout(function(){a.iterateItemQueue()},5E3)})}},iterateShopItem:function(a,b,d){kernel.log("iterateShopItem start: shop = "+a+", itemids = "+b.length);var e=this;e.iterateList(a,b,function(a,b,d,j){e.retrieveShopItem(a,b,d,function(a){j(d,a)})},function(e){kernel.log("iterateShopItem ok = "+
e+": shop = "+a+", itemids = "+b.length);d(e)},e.waitSecondsPerItem_)},queryCookie:function(a,b){var d=this;setTimeout(function(){chrome.tabs.executeScript(a,{code:"document.cookie;",allFrames:!1},function(a){d.cookie_=a})},b*1E3)},scrollTab:function(a,b,d){setTimeout(function(){chrome.tabs.executeScript(a,{code:"scrollTo(0,window.innerHeight*"+b+");",allFrames:!1})},d*1E3)},scrollBottom:function(a,b){setTimeout(function(){chrome.tabs.executeScript(a,{code:"scrollTo(0,document.body.clientHeight);",
allFrames:!1})},b*1E3)},parseItemRecommends:function(a){a=kernel.parseDivHtml(a,0,">\u770b\u4e86\u53c8\u770b<",3);if(!a)return[];var a=kernel.parseHtmlList(a.text,"<a",[["href",'href="','"']]),b=[];for(l in a){var d=this.parseItemid(a[l].href);if(d)try{b.push(parseInt(d))}catch(e){kernel.log("parse item recommends invalid itemid: "+d)}}return kernel.uniqueSort(b)},parseItemRelated:function(a){a=kernel.parseDivHtml(a,0,">\u4e70\u4e86\u8be5\u5b9d\u8d1d\u7684\u4eba\u8fd8\u4e70\u4e86<");if(!a)return[];
var a=kernel.parseHtmlList(a.text,"<a",[["href",'href="','"']]),b=[];for(l in a){var d=this.parseItemid(a[l].href);if(d)try{b.push(parseInt(d))}catch(e){kernel.log("parse item related invalid itemid: "+d)}}return kernel.uniqueSort(b)},parseQueryString:function(a){var b=a.indexOf("?");if(b<0)return{};for(var a=a.substr(b+1).split("&"),b={},d=0;d<a.length;d++){var e=a[d].split("=");e.length==2&&(b[e[0]]=e[1])}return b},parseQueryStringByAmp:function(a){var b=a.indexOf("?");if(b<0)return{};for(var a=
a.substr(b+1).split("&amp;"),b={},d=0;d<a.length;d++){var e=a[d].split("=");e.length==2&&(b[e[0]]=e[1])}return b},parseItemShelve:function(a){var b=kernel.parseInnerText(a,0,"dealRecords.htm",'"');if(!b&&(b=kernel.parseInnerText(a,0,"show_buyer_list.htm",'"'),!b))return null;a=this.parseQueryStringByAmp(b.text);return"starts"in a&&"ends"in a?{starts:a.starts,ends:a.ends}:null},parseItemDescription:function(a){a=kernel.parseDivHtml(a,0,'id="description"');return!a?null:a.text},retrieveItemCombo:function(a,
b,d){var e=this;kernel.log("retrieveItemCombo: shop = "+a+", item = "+b);kernel.sendRequest("http://ext.mdskip.taobao.com/extension/queryTmallCombo.do?itemId="+b,{},function(a){if(!a||a.length==0)d(null);else{var f;try{f=JSON.parse(a)}catch(h){kernel.log("retrieveItemCombo: JSON.parse (item = "+b+") exception: "+h);d(null);return}if(typeof f.combos=="undefined")kernel.log("comboobj.combos is undefined: item = "+b),d(null);else if(f.combos.length==0)kernel.log("no combo: item = "+b),d([]);else{var j=
[];for(c in f.combos)j.push({name:f.combos[c].name,id:f.combos[c].id});e.iterateList(j,j,function(a,d,e,g){var f=d[e];kernel.sendRequest("http://ext.mdskip.taobao.com/extension/queryTmallCombo.do?comboId="+f.id+"&itemId="+b,{},function(a){if(!a||a.length==0)g(e,!1);else{var d;try{d=JSON.parse(a)}catch(h){kernel.log("retrieveItemCombo: JSON.parse(comboId = "+f.id+", item = "+b+") exception:"+h);g(e,!1);return}if(typeof d.currentCombo=="undefined")kernel.log("retrieveItemCombo: no currentCombo comboId = "+
f.id+", item = "+b),g(e,!0);else if(d.currentCombo.id!=f.id)kernel.log("retrieveItemCombo: currentCombo.id ("+d.currentCombo.id+") != combo.id ("+f.id+") itemid = "+b),g(e,!1);else{a=[];for(c in d.currentCombo.items)try{a.push(parseInt(c))}catch(j){kernel.log("retrieveItemCombo: parseInt("+c+") exception:"+j);g(e,!1);return}f.itemids=a;g(e,!0)}}})},function(a){a?d(j):d(null)},e.waitSecondsPerItem_/j.length)}}})},dealQueue_:[],iterateDealQueue:function(){var a=this;if(a.dealQueue_.length==0||!a.running_)setTimeout(function(){a.iterateDealQueue()},
a.waitDealSeconds_*1E3);else{var b=a.dealQueue_.splice(0,1)[0];a.retrieveItemDeal(b.seller,b.item,b.info.lastdeal,function(d,e){if(d){b.shop in a.itemDealAccessTime_||(a.itemDealAccessTime_[b.shop]={});var g=0;e.length>0&&(g=Date.parse(e[0][4]));a.itemDealAccessTime_[b.shop][b.item]=[(new Date).getTime(),g];if(e.length==0)kernel.log("retrieveItemDeal ok: item = "+b.item+", no records"),setTimeout(function(){a.iterateDealQueue()},a.waitDealSeconds_*1E3);else{b.info.lastdeal={buyer:e[0][0],timestamp:e[0][4]};
e.sort(function(a,b){return a[4]<b[4]?-1:a[4]>b[4]?1:a[0]<b[0]?-1:a[0]>b[0]?1:0});var f=[],g=[0,0,0,0,0];for(s in e)g[0]==e[s][0]&&g[4]==e[s][4]||(g=e[s],f.push(g));kernel.log("retrieveItemDeal ok: item = "+b.item+", unique new deals = "+f.length+" in total "+e.length);kernel.appendPost("shop"+b.shop+"/items/"+a.numericHash(b.item)+"/"+b.item+"/deal",JSON.stringify(f),function(d){null==d?(kernel.log("appendPost fail: item = "+b.item+", deal num = "+f.length),setTimeout(function(){a.iterateDealQueue()},
6E4)):(localStorage.setItem("ii_"+b.item,JSON.stringify(b.info)),setTimeout(function(){a.iterateDealQueue()},a.waitDealSeconds_*1E3))})}}else kernel.log("retrieveItemDeal error: "+b.item),setTimeout(function(){a.iterateDealQueue()},6E4)})}},retrieveItemDeal:function(a,b,d,e){var g=this,f=a,h=[],j=1,k=function(m){if(g.running_){a=f;kernel.log("go retrieve deal: seller = "+a+", item = "+b+", page = "+m+", total records = "+h.length);var n="jsonp"+(new Date).getTime(),o="http://ext.mdskip.taobao.com/extension/dealRecords.htm?callback="+
n+"&pageSize=15&isStart=false&ends="+(2417398265E3+Math.floor(Math.random()*1E4))+"&itemId="+b+"&sellerNumId="+a+"&isFromDetail=yes&bidPage="+m;kernel.sendRequest(o,{"fixh-Cookie":g.cookie_,"fixh-Referer":"http://item.taobao.com/item.htm?id="+b},function(f){if(!f||f.length<10||f.indexOf(n)<0)f&&f.length>200&&(f=f.substr(0,200)),kernel.log("[ERROR] dealRecords.htm returns empty, may be blocked: seller = "+a+", item = "+b+", page = "+m+", text = "+f),e(!1,h);else{n+="(";var o=f.indexOf(n)+n.length,
v;for(v=f.length-1;v>0;v--)if(f[v]==")")break;f=f.substr(o,v-o);try{var p=eval("a="+f);if(typeof p.html=="undefined"&&typeof p.url!="undefined")kernel.log("[ERROR] obj.html returned from eval is invalid: text = "+f.substr(0,200)),e(!1,h);else{var w=p.html.indexOf('<th class="th-buyer">');if(w<0)kernel.log("th-buyer not found: seller = "+a+", item = "+b+", page = "+m),e(!1,h);else{var x=p.html.substr(w);if(x.indexOf("<tr")>0){var u=kernel.parseHtmlList(x,"<tr",[["buyer",['<td class="cell-align-l buyer">',
'<div class="line">'],"</div>"],["rank",["/newrank/"],".gif","optional"],["vip",["vip.taobao.com",'title="'],"\u4f1a\u5458","optional"],["style",['<td class="cell-align-l style">'],"</td>"],["quantity",['<td class="quantity">'],"</td>"],["price",['<td class="price">'],"</td>","optional"],["datetime",['<td class="dealtime">'],"</td>"]],"</tr>");if(!u){kernel.log("parse deal record error: seller = "+a+", item = "+b+", page = "+m);e(!1,h);return}j=m+1;for(r in u){var C=u[r].buyer.replace(/<[^>]*>/g,
"").trim(),G=u[r].style.replace(/<[^>]*>/g,"").trim(),H=u[r].quantity.replace(/<[^>]*>/g,"").trim(),D=u[r].price,z;D==""?z="\u9690\u85cf\u4ef7\u683c":D.indexOf("\u4e13\u5c5e\u4f18\u60e0")>0?z="\u4e13\u5c5e\u4f18\u60e0":D.indexOf("\u805a\u5212\u7b97\u4ef7")>0?z="\u805a\u5212\u7b97\u4ef7":(z=u[r].price.replace(/<[^>]*>/g,"").trim(),z=z.replace(/&yen;/,""));var B=u[r].datetime.replace(/<[^>]*>/g,"").trim();if(B<d.timestamp){e(!0,h);return}p=[C,G,H,z,B];u[r].rank&&(p.push(u[r].rank),u[r].vip&&p.push(u[r].vip));
if(B>d.timestamp)h.push(p);else if(B==d.timestamp)if(C!=d.buyer)h.push(p);else{j=m;kernel.log("item "+b+" same timestamp of last deal = "+JSON.stringify(d)+" at page "+m);break}else{kernel.log("item "+b+" smaller timestamp "+B+" to last deal = "+JSON.stringify(d)+" at page "+m);j=m;break}}}else m=j;var E=new Date,F=new Date;F.setTime(E.getTime()-864E5);var I=kernel.formatDate(E),J=kernel.formatDate(F);if(m>=100||h.length==0||h[h.length-1][4].indexOf(I)<0&&h[h.length-1][4].indexOf(J)<0)j=m;m==j?e(!0,
h):(m++,setTimeout(function(){k(m)},g.waitDealSeconds_*1E3))}}}catch(K){kernel.log("retrieve deal exception: seller = "+a,NaN+b+", page = "+m+", exception = "+K),e(!1,h)}}})}else setTimeout(function(){k(m)},5E3)};k(1)},probeItemDeal:function(a,b,d){try{if(d.data.apiStack[0].name!="esi")kernel.log('wdetailobj.data.apiStack[0].name != "esi": item = '+b);else{var e=JSON.parse(d.data.apiStack[0].value);d.data.esi=e;var g=e.data.itemInfoModel,f=g.totalSoldQuantity,h=g.quantity;if(f==0)kernel.log("item totalSoldQuantity is 0: item = "+
b);else{var j,k=localStorage.getItem("ii_"+b);if(k){k=JSON.parse(k);if(f+"_"+h==k.totalSoldQuantity+"_"+k.quantity){kernel.log("item quantity not changed: item = "+b+", totalSoldQuantity = "+f+", quantity = "+h);a in this.itemDealAccessTime_||(this.itemDealAccessTime_[a]={});d=0;k.lastdeal.buyer.length>0&&(d=Date.parse(k.lastdeal.timestamp));this.itemDealAccessTime_[a][b]=[(new Date).getTime(),d];return}j=k.lastdeal}else j={buyer:"",timestamp:"2000-00-00 00:00:01"};var m=this.dealQueue_;for(q in m)if(m[q].item==
b)return;this.dealQueue_.push({shop:a,seller:d.data.seller.userNumId,item:b,info:{totalSoldQuantity:f,quantity:h,lastdeal:j}})}}}catch(n){kernel.log("probeItemDeal: item = "+b)}},compactItemWdetail:function(a){try{var b={},d=a.data.esi.data.itemInfoModel;b.priceUnits=d.priceUnits;if(typeof a.data.esi.data.shopPromotion!="undefined")b.shopPromotion=a.data.esi.data.shopPromotion,delete a.data.esi.data.shopPromotion;if(typeof a.data.esi.data.delivery!="undefined")d=a.data.esi.data.delivery,b.delivery=
{areaId:d.areaId,deliveryFees:d.deliveryFees,destination:d.destination},delete a.data.esi.data.delivery;d=a.data.itemInfoModel;if(d.sku==!0)b.skuModel=a.data.skuModel;b.title=d.title;b.picsPath=d.picsPath;b.stuffStatus=d.stuffStatus;b.location=d.location;b.saleLine=d.saleLine;b.categoryId=d.categoryId;b.guaranteeInfo=a.data.guaranteeInfo;b.props=a.data.props;return b}catch(e){return kernel.log("compactItemWdetail exception: "+e),null}},retrieveShopSeller:function(a,b,d){kernel.log("retrieveShopSeller: shop = "+
a+", item = "+b);kernel.sendRequest("http://hws.m.taobao.com/cache/wdetail/5.0/?id="+b+"&ttid=2013@taobao_h5_1.0.0&exParams={}",{},function(e){if(!e||e.length==0)d(!0);else try{var g=JSON.parse(e);if(typeof g.data=="undefined"||typeof g.data.seller=="undefined"||typeof g.data.seller.type=="undefined")kernel.log("obj.data.seller.type not defined: item = "+b),d(!1);else{var f=g.data.seller;typeof f.fansCount!="undefined"&&delete f.fansCount;delete f.actionUnits;for(ei in f.evaluateInfo)delete f.evaluateInfo[ei].highGap;
kernel.uniquePost("shop"+a+"/seller",f)}}catch(h){kernel.log("retrieveShopSeller exception:"+h),d(!1)}})},retrieveShopItem:function(a,b,d,e){var g=this;if(g.running_){kernel.log("retrieveShopItem shop = "+a+", item["+d+"] = "+b[d]);var f=b[d];kernel.sendRequest("http://hws.m.taobao.com/cache/wdetail/5.0/?id="+f+"&ttid=2013@taobao_h5_1.0.0&exParams={}",{},function(b){if(!b||b.length==0)e(!0,null);else try{var d=JSON.parse(b);if(typeof d.data=="undefined"||typeof d.data.seller=="undefined"||typeof d.data.seller.type==
"undefined")kernel.log("obj.data.seller.type not defined: item = "+f);else{g.probeItemDeal(a,f,d);g.shoptypes_[a]=d.data.seller.type=="B"?"b":"c";var k=g.compactItemWdetail(d);k&&kernel.uniquePost("shop"+a+"/items/"+g.numericHash(f)+"/"+f,k);var m={itemInfoModel:d.data.esi.data.itemInfoModel};if(typeof d.data.esi.data.skuModel!="undefined"&&(m.skuModel=d.data.esi.data.skuModel,typeof m.skuModel.skus!="undefined")){var n=m.skuModel.skus;for(s in n){var o=n[s];delete o.quantityText;try{if(o.priceUnits[0].display==
"1")o.price=o.priceUnits[0].price,delete o.priceUnits}catch(y){}}}kernel.uniquePost("shop"+a+"/items/"+g.numericHash(f)+"/"+f+"/sale",m);if(typeof d.data.rateInfo!="undefined"){var A=d.data.rateInfo,v={rateCounts:A.rateCounts,tagList:A.tagList};kernel.uniquePost("shop"+a+"/items/"+g.numericHash(f)+"/"+f+"/rate",v)}}e(!0,null)}catch(p){kernel.log("wdetail JSON.parse exception: item = "+f+", exception: "+p),e(!1,null)}})}else setTimeout(function(){g.retrieveShopItem(a,b,d,e)},5E3)},retrieveItemRelated:function(a,
b,d){var e=this;if(e.running_){kernel.log("retrieve item related: shop = "+a+", item = "+b);e.shoptypes_[a]=="b"&&e.retrieveItemCombo(a,b,function(d){d&&(kernel.log("shop "+a+" item "+b+" combo = "+JSON.stringify(d)),kernel.uniquePost("shop"+a+"/items/"+e.numericHash(b)+"/"+b+"/combo",d))});var g="http://item.taobao.com/item.htm?id="+b;kernel.log("retrieveItemRelated: item "+b);try{e.createtab({url:g},function(f){if(null!=f){var g=f.id;try{e.queryCookie(g,2);for(f=0;f<(e.waitSecondsPerItemRelated_-
8)/1;f++)e.scrollTab(g,f+1,3+f*1);e.scrollBottom(g,e.waitSecondsPerItemRelated_-3);setTimeout(function(){try{chrome.tabs.executeScript(g,{code:'scroll(0, 0);var desc=document.getElementById("description");if(desc) desc=desc.innerText;else desc="";var a={html:document.body.outerHTML,desc:desc};a;',allFrames:!1},function(f){e.removetab(g);try{try{var h=f[0],m=h.desc.trim().replace(/[\n]+/g,"\n");kernel.uniquePost("shop"+a+"/items/"+e.numericHash(b)+"/"+b+"/description",{text:m});var k=h.html;if(d){var v=
e.parseShopModule(k,[]);kernel.log("shop = "+a+", item = "+b+", modules = "+JSON.stringify(v));kernel.uniquePost("shop"+a+"/itemmodule",v)}var p=e.parseItemRecommends(k),w=e.parseItemRelated(k),x=e.parseItemShelve(k);kernel.log("item modules: shop = "+a+", item = "+b+", recommends = "+JSON.stringify(p)+", related = "+JSON.stringify(w)+", shelve = "+JSON.stringify(x));f={recommends:p,related:w,shelve:x};kernel.uniquePost("shop"+a+"/items/"+e.numericHash(b)+"/"+b+"/related",f)}catch(u){kernel.log("process item = "+
b+" desc and html exception: "+u)}}catch(C){kernel.log("retrieveItemRelated item = "+b+", exception: "+C)}})}catch(f){e.removetab(g),kernel.log("retrieveItemRelated item = "+b+", exception = "+f)}},(e.waitSecondsPerItemRelated_-1)*1E3)}catch(k){e.removetab(g),kernel.log("retrieveItemRelated item = "+b+", exception: "+k)}}})}catch(f){kernel.log("retrieveItemRelated shop = "+a+", item = "+b+", exception = "+f)}}},findshopbyitem:function(a,b){kernel.sendRequest("http://item.taobao.com/item.htm?id="+
a,{},function(a){if(null==a||a.length==0)b("");else{var e=kernel.parseInnerText(a,0,"shopId=",";");if(null==e)b("");else{var e=e.text,g=kernel.parseInnerText(a,0,'seller_nickname" value="','"');g||(g=kernel.parseInnerText(a,0,'data-nick="','"'));g?(g.text=decodeURIComponent(g.text),localStorage.setItem("shop"+e,g.text),g=g.text):g="";b({shopid:e,nick:g})}}})},findshop:function(a,b){kernel.sendRequest(a,{},function(d){if(null==d||d.length==0)b("");else{d.indexOf("\u5b89\u5168\u63a7\u4ef6\u767b\u5f55")>
0&&kernel.log("\u91c7\u96c6\u7f51\u9875"+a+"\u9047\u5230\u5b89\u5168\u63a7\u4ef6\u767b\u5f55\u969c\u788d");var e=kernel.parseInnerText(d,0,"shopId=",";");null==e?b(""):(e=e.text,(d=kernel.parseInnerText(d,0,['user_nick":','"'],'"'))?(d=decodeURIComponent(d.text),localStorage.setItem("shop"+e,d)):d="",b({shopid:e,nick:d}))}})},checkopenedtab:function(){var a=this;ontabupdated(function(b){a.opentabs_[b]=(new Date).getTime()})},runcalled_:!1,run:function(){var a=this;if(!a.runcalled_)if(a.running_){a.runcalled_=
!0;var b=localStorage.getItem("_speedratio");null==b?localStorage.setItem("_speedratio","1.0"):a.setSpeedRatio(parseFloat(b));a.running_=a.getShopIds().length==0?!1:!0;this.iterateShops();this.iterateItemQueue();this.iterateDealQueue();this.iterateShopQueue();this.iterateItemRelatedQueue()}else setTimeout(function(){a.run()},1E4)}};window.taobao=taobao;taobao.checkopenedtab();
