(function(window){
	Array.prototype.remove=function(dx){
		if(isNaN(dx)||dx>this.length){return false;}
		for(var i=0,n=0;i<this.length;i++){
			if(this[i]!=this[dx]){
			　　this[n++]=this[i]
			}
		}
		this.length-=1;
	}
	
	function pad(num, n) { 
		var len = num.toString().length; 
		while(len < n) { 
			num = "0" + num; 
			len++; 
		} 
		return num; 
	}
	if(typeof ssNo == 'undefined' || typeof str == 'undefined'){
		alert('当前网页不支持下载');
		return;
	}
	if(window['mzprogress']){
		return;
	}
	
	var domain = document.location.href.replace(/^(https?:\/\/[^\/]*?)(\/.*)?$/ig, '$1');	
	var urlPre = domain+'/n/'+str, urlLists = [], runThread = [], maxThread = parseInt(external.appconfig('duxiu', 'thread', '3'), 10);
	
	var div = document.createElement("div");
		div.style.cssText = "POSITION:absolute;right:50px;TOP:50px;z-index:999;background:#000000;color:#FFF;padding:5px 10px;";
	document.getElementsByTagName('body')[0].appendChild(div);
	
	window['mzprogress'] = div;
	
	for(var i = spage; i <= epage; i++){
		var urlImg = urlPre + pad(i, 6)+'?.&uf=ssr&zoom=0';
		urlLists.push({url:urlImg, index:pad(i, 6)});
	}
	
	
	function log(msg){
		div.innerHTML = msg;
	}
	
	for(var i = 0; i < maxThread; i++){
		createDownload();
	}
	
	function createDownload(){
		if(urlLists.length > 0 ){
			var obj = urlLists.shift();
			var tid = external.run({
				'_name'      : 'duxiudownload_'+urlLists.length,
				'_file'      : 'duxiu.com/download',
				'_runover'   : function(sender, dir){
					createDownload();
					for(var i in runThread){
						if (runThread[i] == sender){
							runThread.remove(i);
						}
					}
					if(runThread.length == 0){
						log('<a href="javascript:external.opendirectory(\''+dir.replace(/\\/ig, '/')+'\');void 0">下载完毕！点击打开保存目录</a>');
					}
				},
				'_runecho'   : function(sender,msg){
					log(msg);
				},
				'cookie'     : external.cookie(),
				'title'      : document.title + ssNo,
				'url'        : obj.url,
				'idx'        : obj.index,
				'len'        : urlLists.length
			});
			
			runThread.push(tid);
		}
	}
})(window);