/*************************************************************************
* Copyright (c) 2011 im007boy@gmail.com. All rights reserved.            *
* Use of this source code is governed by a BSD-style license that can be *
* found in the LICENSE file.                                             *
*************************************************************************/


var im007boy_thunder = {};


im007boy_thunder.compress = function(g){
	/**
	 * 接受一个数组参数，合并数组中的重复项并返回此数组
	 **/
	var i = 0;
	var t = 0;
	for (i = 0;i < g.length;i++)
	{
		for (t = i+1;t < g.length;t++)
		{
			if (g[i] == g[t])
			{
				g.splice(t,1);
				t --;
			}	
		}			
	}
	 
	return g; 
}

im007boy_thunder.copy = function(str){
	/**
	 *吧str字符串复制到剪贴板
	 *
	 **/;
		
}
im007boy_thunder.autocopy = function(){
	/**
	 *给页面中的href="*.exe"之流加入监听事件
	 *
	 **/;
	 var len = document.links.length;
	 var i =0;
	 var url = [];
	 for (i = 0;i < len;i++)
	 {
		try{
			url = im007boy_thunder.getDirectLink(document.links[i].getAttribute("href"));
		}catch(e){}	
		if (url.length == 1)
		{
			//添加监听
		}
	 }
	 
}

var convert = {};
var ui = {};
function autoreporterror(){
    return;
	chrome.extension.sendRequest({"hope": "reportConvertError","method":"auto","url":location.href,"title":document.title},function(response){
	});
}
//convert.RegExpDateLibrary = "";
//各种转换模式
convert.resetDom = function(dom,href){
	var title;
	dom.setAttribute("href",href);
	dom.removeAttribute("oncontextmenu");
	dom.removeAttribute("onclick");
	title = dom.getAttribute("title")||"";
	if (title == "[破解失败。请先在此点击右键，然后\n手动点击工具栏图标再次破解]" ||
		title.indexOf("[此链接可能并非您需要的连接]") > -1 ||
		title.indexOf("[已被迅雷破解扩展破解]") > -1)
		title = "";
		
	if (title.indexOf('安装') >= 0 && title.indexOf('快车') >= 0 ){
		dom.setAttribute("title","[此链接可能并非您需要的连接]\n"+title);
	}else{
		dom.setAttribute("title","[已被迅雷破解扩展破解]\n"+title);
	}
}
convert.label_simple = function(){
	/**
	 *从a标签和script标签中匹配加密链接的函数
	 *
	 **/
	var i = 0,t = 0;
	var currentdom;
	var domInfo = {};
	var newstr = {};
	var success = 0;
	var title = '';
	//var error = 1;
	//console.log("convert "+document.links.length+" links;");
	for (i = 0;i < document.links.length;i++){
		success = 0;
		if (document.links[i].attributes == 'undefined')
			continue;
		//一级匹配 直接专用连	
		for (t= 0;t < document.links[i].attributes.length;t++){
			newstr = decodeOnce(document.links[i].attributes[t].value);
			if (newstr.ifchange == 1){
				convert.resetDom(document.links[i],newstr.toStr);
				success = 1;
				//error = 0;
				break;
			}
		}
		if (success == 0){
			//二级匹配 特征库
			for (t= 0;t < document.links[i].attributes.length;t++){
				newstr = detectPhpLink(document.links[i].attributes[t].value);
				if (newstr.length >= 1){
					convert.resetDom(document.links[i],newstr[0]);
					success = 1;
					//error = 0;
					break;
				}
			}
			if (success == 0){
				//三级匹配 直接连接
				for (t= 0;t < document.links[i].attributes.length;t++){
					if (document.links[i].attributes[t].name == "href"){
						if (/^\s*http:\/\/|https:\/\/|ftp:\/\/|mms:\/\//.test(document.links[i].attributes[t].value)){
							success =  1;
							//console.log("直接连接："+document.links[i].attributes[t].value);
							break;
						}
					}
					newstr = detectSoftLink(document.links[i].attributes[t].value,1);
					if (newstr.length == 1){
						convert.resetDom(document.links[i],newstr[0]);
						success = 1;
						//error = 0;
						break;
					}
				}
				
			}
			if (success == 0){
				//仍然无法破解
				newstr = document.links[i].innerHTML;
				if (typeof newstr == "string" && newstr.indexOf("快车")>-1 && newstr.indexOf("高速")>-1){
					document.links[i].setAttribute("title","[破解失败。请先在此点击右键，然后\n手动点击工具栏图标再次破解]");
				}
				
			}
		}
		
	}
	//if (error == 1)
	//	autoreporterror();
}
convert.page_advance = function(){
	/**
	 *从DOM或页面源文件中匹配加密连接或真实链接
	 *
	 *先执行DOM全局匹配，保存
	 *
	 *然后执行源代码匹配，保存
	 *执行破解
	 *输出
	 **/
	var v_1 = [];
	var v_2 = [];
	var i ;
	var newstr = {};
	var html = document.documentElement.innerHTML + "";
	var links = [];
	//创建页面弹出层
	var ht = '<div style="position:absolute;left:100px;top:100px;padding:10px;min-height: 200px;text-align:left;-webkit-border-radius: 12px;font-size:12px;color:black;background-color: #E7F1FB; border: solid 1px #527DE0;z-index:999999;cursor:move;"><div style="height: 1.5em;"><span style="cursor:pointer" onclick=\'dom = document.getElementById(\"im007boy-thunder-gmpl\").parentNode;dom.removeEventListener(\"mousedown\");dom.parentNode.removeChild(dom)\'>关闭</span><span>  <span><a href="http://goo.gl/M83h" target="_blank">提交建议或错误</a></div><div id="im007boy-thunder-gmpl">正在探测...8</div><div>';
	document.body.innerHTML += ht;
	document.getElementById("im007boy-thunder-gmpl").parentNode.style.top = document.body.scrollTop + 100 + "px";
	if (document.addEventListener)
		document.getElementById("im007boy-thunder-gmpl").parentNode.addEventListener("mousedown",function(){drag(this)},true);
		
		
	//查询 Body.innerHTML
	
	//console.log("查询Body.innerHTML结束");
	//console.log("V_1",v_1);
	//请求源代码
	ui.countdowntime = 8;
	try{
		clearInterval(ui.countdown);
	}catch(e){}
	
	ui.countdown = setInterval(function(){
		ui.countdowntime--;
		document.getElementById("im007boy-thunder-gmpl").innerHTML = "正在探测..."+ui.countdowntime;
	},1000);
	chrome.extension.sendRequest({"hope": "getPageSource","innerHTML":html,"url":location.href},function(response){
				//console.log(response);
				var output = "";
				var html = response.innerHTML;
				//检测加密链
				html += response.responseText;
				if (typeof html != "string")
					html = "";
				html = html.replace(new RegExp(' ','g'),'');
				html = html.replace(new RegExp('\n','g'),'');
				//检测加密链
				do{
					newstr = decodeOnce(html);
					if (newstr.ifchange == 0)
						break;
					else{
						newstr.fromStr = newstr.fromStr.replace(/\+/g,'\\+');
						html = html.replace(new RegExp(newstr.fromStr,'g'),'');
						links.push(newstr.toStr);
					}
				}while(1);
				//console.log(links);
				//检测直接连接
				newstr = detectSoftLink(html,0);
				if (newstr.length >= 1){
					for (i = 0;i < newstr.length;i++){
						links.push(newstr[i]);
					}
				}
					
				//console.log(links);
				//合并
				links = compress(links);
				//console.log(links);
				
				//console.log("探测结束",v_1);
				try{
					clearInterval(ui.countdown);
					ui.countdowntime = 10;
				}catch(e){}
				if ( links.length > 0)
				{
					//显示数组
					//console.log(v_1);
					document.getElementById("im007boy-thunder-gmpl").innerHTML = "正在处理...";
					output = '<ul style="list-style:none;padding:0px;">';
					for (i = 0;i < links.length;i++)
					{
						output += ui.popup_template(links[i]);
					}
					document.getElementById("im007boy-thunder-gmpl").innerHTML = output + "</ul>";
				}	
				else{
					document.getElementById("im007boy-thunder-gmpl").innerHTML = '没有探测到链接';
					autoreporterror();
				}	
				
		//console.log("合并后台结束");
		});	 
	 
}
function drag(elementToDrag) {
    var startX = event.clientX, startY = event.clientY;
    var origX = elementToDrag.offsetLeft, origY = elementToDrag.offsetTop;
    var deltaX = startX - origX, deltaY = startY - origY;
    if (document.addEventListener) {  // DOM Level 2 event model
        document.addEventListener("mousemove", moveHandler, true);
        document.addEventListener("mouseup", upHandler, true);
    }
    if (event.stopPropagation) event.stopPropagation( );  // DOM Level 2
    if (event.preventDefault) event.preventDefault( );   // DOM Level 2
    function moveHandler(e) {
        elementToDrag.style.left = (e.clientX - deltaX) + "px";
        elementToDrag.style.top = (e.clientY - deltaY) + "px";
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
    }
    function upHandler(e) {
        if (!e) e = window.event;  // IE Event Model
        if (document.removeEventListener) {  // DOM event model
            document.removeEventListener("mouseup", upHandler, true);
            document.removeEventListener("mousemove", moveHandler, true);
        }
        if (e.stopPropagation) e.stopPropagation( );  // DOM Level 2
    }
}


ui.popup_template = function(link){
	var pre = link;
	if (link.length> 35)
		pre = pre.slice(0,10)+"..."+link.substring(link.length-35);
	var s = '<li><a href=\"'+link+'\" title=\"'+link+'\" style="height: 2em;line-height: 2em;cursor:pointer;">地址:'+pre+'</a></li>';
	return s;
}

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
		//console.log("收到");
		switch(request.hope)
		{
		case "simple":
			convert.label_simple();
			break;
		case "fromsource":
			convert.page_advance();
			break;
		}
		sendResponse({});
	}
 );
 
chrome.extension.sendRequest({"hope": "checkAutoReplaceEnable"}, function(response) {
	if(response.checkAutoReplaceEnable == "true")
		convert.label_simple();
});
