/* vim:set expandtab tabstop=4 shiftwidth=4 softtabstop=4 cinoptions=\:0,g0: */
var extEnabledStatus = true;
;(function () {
    //add event listener for all links
    (function initialize() {
        //var mimetype = navigator.mimeTypes["application/npxf-qqdownload"];
        //if ( typeof(mimetype) == "undefined" ) {
        //    console.error("Initialize Failed: QQDownload Plugin for chrome is not installed");
        //    return;
        //}
        chrome.extension.onMessage.addListener(function (request, sender, sendResponse) {
            extEnabledStatus = request.status;
        });
        

        for (var i = 0; i < document.links.length; i++) {
            if (document.links[i].getAttribute("qhref") != null) {
                document.links[i].onclick = onLinkClicked;
                document.links[i].href = document.links[i].getAttribute("qhref");
                continue;
            }
            document.links[i].addEventListener("click", onLinkClicked, false);
        }
    })();

    //Rule class constructor
    function Rule(regx, processResult) {
        this.regx = new RegExp(regx, "i");
        if (typeof(processResult) == "undefined") {
            processResult = process;
        }
        this.processResult = processResult;
    }
    Rule.prototype.process = function (url) {
        result = this.regx.exec(url);
        //console.log(result);
        return this.processResult(url, result);
    }

    function process(url, result) {
        return url == result ? {
            cmd : "Invoke_QQDownload",
            src : result
        }
         : null;
    }
    function processWithSubUrl(url, result) {
        return result != null && result.length == 2 ? {
            cmd : "Invoke_QQDownload",
            src : result[1]
        }
         : null;
    }
    function processUnsupportUrl(url, result) {
        return url == result ? {
            cmd : "Do_Not_Handle"
        }
         : null;
    }

    //construct rules
    var special_link_rules = new Array();
    //TODO x.soso.com
    special_link_rules.push(new Rule(".+sina.com.*\\/d_load.php\\?.+"));
    special_link_rules.push(new Rule(".+pcpop.com.*\\/redose.aspx\\?.+"));
    special_link_rules.push(new Rule(".+pconline.com.cn\\/filedown.jsp\\?.+"));
    special_link_rules.push(new Rule(".+zol.com.*\\/down.php\\?.+"));
    special_link_rules.push(new Rule(".+zol.com.*\\?.*url=([^\\&]+).*", processWithSubUrl));
    special_link_rules.push(new Rule(".+crsky.com.*\\?down_url=([^\\&]+).*", processWithSubUrl));
    special_link_rules.push(new Rule(".+skycn.com.*\\/down.php\\?uri=(.+)", processWithSubUrl));
    special_link_rules.push(new Rule("http.+\\?.*url=.+", processUnsupportUrl));
    special_link_rules.push(new Rule("http.+\\?.*uri=.+", processUnsupportUrl));

    //extensions QQDownload supported
    var support_extension_list = [".torrent", ".avi", ".rmvb", ".rm", ".exe", ".rar", ".mp4", ".mkv", ".wmv", ".mp3",
        ".zip", ".iso", ".7z", ".3gp", ".pdf", ".mpg", ".flv", ".mov", ".swf", ".ape", ".mpeg", ".wma", ".msi", ".gz", ".gzip", ".tar", ".chm", ".apk", ".ipa"];

    String.prototype.endWith = function (sub_string) {
        var index = this.lastIndexOf(sub_string);
        return index != -1 && index == this.length - sub_string.length;
    }

    //link clicked callback
    function onLinkClicked(e) {
        //console.log("Link Clicked: " + this.href);
        //link for QQDownload
        var qhref = this.getAttribute("qhref");
        if (qhref != null && !!extEnabledStatus) {
            //console.log("QQDownload Link Matched: " + qhref);
            invokeQQDownload(qhref);
            return e.preventDefault();
        }

        //special links
        for (var i = 0; i < special_link_rules.length; i++) {
            var result = special_link_rules[i].process(this.href);
            if (result != null && !!extEnabledStatus) {
                //console.log("Special Link Matched: " + special_link_rules[i].regx);
                if (result.cmd == "Do_Not_Handle")
                    return;
                invokeQQDownload(result.src);
                return e.preventDefault();
            }
        }

        //file extensions
        for (var i = 0; i < support_extension_list.length; i++) {
            var myqqhref = this.href;
			var substring = myqqhref.split("#");
			substring = substring[0];
			substring = substring.split("?");
			substring = substring[0];
		
          if ( substring.toLowerCase().endWith(support_extension_list[i].toLowerCase())  && !!extEnabledStatus) {
              //console.log("Extension Matched: " + support_extension_list[i]);
              invokeQQDownload(substring);
              return e.preventDefault();
          }
        }
    }

    function invokeQQDownload(url) {
        //console.log("invokeQQDownload: " + url);
        //chrome.extension.sendRequest({cmd: "start_task", json: json});
        var single_task_config = {
            "addto_offline" : 0,
            "silence_create" : 0,
            "url_list" : [{
                    "url" : encodeURIComponent(url),
                    //"file_name":encodeURIComponent(filename,
                    "custom_id" : 22002,
                    "cookie" : document.cookie,
                    "file_size" : "",
                    "ref" : encodeURIComponent(document.URL),
                    //"remark":remark,
                    "hash" : "",
                    "p2p_rate" : 0
                }
            ]
        };
        chrome.extension.sendRequest({
            cmd : "start_task",
            json : JSON.stringify(single_task_config)
        });
    }

    //left custom_id=22002 right custom_id=22003
    chrome.extension.onConnect.addListener(function (port) {
        //alert(port.name);
        //console.log(port.name);
        port.onMessage.addListener(function (msg) {

            port.postMessage(msg);

            if (msg.cmd == "download_single") {
                var single_task_config = {
                    "addto_offline" : 0,
                    "silence_create" : 0,
                    "url_list" : [{
                            "url" : encodeURIComponent(msg.url),
                            //"file_name":filename,
                            "custom_id" : 22003,
                            "cookie" : document.cookie,
                            "file_size" : "",
                            "ref" : encodeURIComponent(document.URL),
                            //"remark":remark,
                            "hash" : "",
                            "p2p_rate" : 0
                        }
                    ]
                };
                chrome.extension.sendRequest({
                    cmd : "start_task",
                    json : JSON.stringify(single_task_config)
                });
            } else if (msg.cmd == "download_offline") {
                //var json = '{"addto_offline":0,"silence_create":0,"url_list":[{"url":"http://dl_dir2.qq.com/invc/qqpcmgr/setup/QDeskSetup_23_1192.exe","file_name":"test_01.exe","custom_id":10800,"cookie":"123","file_size":"12345678","ref":"http://pc.qq.com","remark":"??","hash":"fasdfasdfasdfadsf","p2p_rate":543}]}';

                var single_task_config = {
                    "addto_offline" : 2,
                    "silence_create" : 0,
                    "url_list" : [{
                            "url" : encodeURIComponent(msg.url),
                            //"file_name":filename,
                            "custom_id" : 22003,
                            "cookie" : document.cookie,
                            "file_size" : "",
                            "ref" : encodeURIComponent(document.URL),
                            //"remark":remark,
                            "hash" : "",
                            "p2p_rate" : 0
                        }
                    ]
                };
                chrome.extension.sendRequest({
                    cmd : "start_task",
                    json : JSON.stringify(single_task_config)
                });
            } else if (msg.cmd == "download_topspeed") {
                //var json = '{"addto_offline":0,"silence_create":0,"url_list":[{"url":"http://dl_dir2.qq.com/invc/qqpcmgr/setup/QDeskSetup_23_1192.exe","file_name":"test_01.exe","custom_id":10800,"cookie":"123","file_size":"12345678","ref":"http://pc.qq.com","remark":"??","hash":"fasdfasdfasdfadsf","p2p_rate":543}]}';

                var single_task_config = {
                    "addto_offline" : 1,
                    "silence_create" : 0,
                    "url_list" : [{
                            "url" : encodeURIComponent(msg.url),
                            //"file_name":filename,
                            "custom_id" : 22003,
                            "cookie" : document.cookie,
                            "file_size" : "",
                            "ref" : encodeURIComponent(document.URL),
                            //"remark":remark,
                            "hash" : "",
                            "p2p_rate" : 0
                        }
                    ]
                };
                chrome.extension.sendRequest({
                    cmd : "start_task",
                    json : JSON.stringify(single_task_config)
                });
            } else if (msg.cmd == "download_all") {
                var batch_task_config = {
                    "addto_offline" : 0,
                    "silence_create" : 0,
                    "url_list" : []
                };
                var all_links = document.links;
                for (var i = 0; i < all_links.length; i++) {
                    var url;
                    if (all_links[i].getAttribute("qhref") != null) {
                        url = document.links[i].getAttribute("qhref");
                    } else {
                        url = all_links[i].href;
                    }

                    var items_obj = {
                        "url" : encodeURIComponent(url),
                        //"file_name":tasklist[i].file_name||"",
                        "custom_id" : 22003,
                        "cookie" : document.cookie || "",
                        "file_size" : "",
                        "ref" : encodeURIComponent(document.URL),
                        "remark" : "",
                        "hash" : "",
                        "p2p_rate" : 0
                    };
                    batch_task_config.url_list.push(items_obj);
                }
                chrome.extension.sendRequest({
                    cmd : "start_task",
                    json : JSON.stringify(batch_task_config)
                });
            }

        });
    });
})();
