/*
Ime plugin
@author zhangyaochun
@data 2012-3-14
@info 
*/
(function(window, undefined) {

    imePlugin = window.imePlugin || { version: "1.0.0" };

    imePlugin.consts = {
        template: {
            'pluginTpl': '<div id="&{ID}" class="clearfix pluginCon"><img class="fl pImg" src="&{icon_path}"/><div class="fr detailInfo"><p class="first clearfix"><span class="fb mr9 fl">&{Caption}</span><span class="Version mr9 fl">&{CurVersion}</span><a class="quickA fl" pid="&{ID}">&{HotLinkTxt}</a><span class="noinstall statusInfo fr">未安装</span></p><p class="pInfo clearfix"><span class="fl">&{Tip}</span> <span class="processStatus fr"></span></p><div class="btnCon clearfix"><a class="btn mr108 use" pid="&{ID}">使用</a><a class="btn update" pid="&{ID}">升级</a><a class="btn start" pId="&{ID}">启用</a><a class="btn stop" pid="&{ID}">禁用</a><a class="btn unstall" pid="&{ID}">卸载</a><a class="btn stall" pid="&{ID}">安装</a><a class="btn cancel" pid="&{ID}">取消</a></div></div></div>',
            // 'processTpl':'<div class="Progress"><div class="ProgressBar"></div></div><span class="percentage">0%</span>'
            'processTpl': '<div class="ProgressBar"></div>'
        },
        noUpdateInfo: '已是最新版本',
        hasUpdateInfo: '有新版本',
        updatingInfo: '升级中...',
        stallingInfo: '安装中...',
        noinstall: '',
        stopUseInfo: '禁用插件',
        unstallSucInfo: '卸载成功',
        stallSucInfo: '安装成功',
        updateSucInfo: '升级成功',
        stallErrInfo: '安装失败，请重试',
        updateErrInfo: '升级失败，请重试',
        useInfo: '启用插件',
        hotKey: '快捷键'
    }

    //core
    imePlugin.core = imePlugin.core || {};

    //tpl
    imePlugin.core.tpl = function(template, data, label) {
        var tmp = String(template),
			  s = label || /&\{([^}]*)\}/mg;
        return tmp.replace(s, function(value, name) {
            //11-23 暂时这样处理模板中的空值
            if (data[imePlugin.string.trim(name)] == '') {
                return value = '&nbsp';
            }
            return value = data[imePlugin.string.trim(name)];
        });
    };


    //string的namespace
    imePlugin.string = imePlugin.string || {};

    //trim
    imePlugin.string.trim = function(source) {
        return source.replace(/^\s+/, '').replace(/\s+$/, '');
    };

    //escapeReg
    imePlugin.string.escapeReg = function(source) {
        return String(source)
            .replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\\x241');
    };

    //browser
    imePlugin.browser = imePlugin.browser || {};

    imePlugin.browser.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || +RegExp['\x241']) : undefined;

    //dom的namespace
    imePlugin.dom = imePlugin.dom || {};

    //g
    imePlugin.dom.g = function(id) {
        if ("string" == typeof id || id instanceof String) {
            return document.getElementById(id);
        } else {
            if (id && id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) {
                return id;
            }
        }
        return null;
    };

    //q
    imePlugin.dom.q = function(className, el, tagName) {
        var result = [],
			trim = function(source) {
			    var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
			    return String(source).replace(trimer, "")
			},
			len,
			i,
			elements,
			node;
        if (!(className = trim(className))) { return result }
        if ("undefined" == typeof el) { el = document } else {
            el = $MyIme.tools.g(el);
            if (!el) { return result }
        }
        if (tagName) {
            tagName = trim(tagName).toUpperCase()
        }
        if (el.getElementsByClassName) {
            elements = el.getElementsByClassName(className);
            len = elements.length;
            for (i = 0; i < len; i++) {
                node = elements[i];
                if (tagName && node.tagName != tagName) {
                    continue
                }
                result[result.length] = node
            }
        } else {
            className = new RegExp("(^|\\s)" + imePlugin.string.escapeReg(className) + "(\\s|\x24)");
            elements = tagName ? el.getElementsByTagName(tagName) : (el.all || el.getElementsByTagName("*"));
            len = elements.length;
            for (i = 0; i < len; i++) {
                node = elements[i];
                if (className.test(node.className)) {
                    result[result.length] = node
                }
            }
        }
        return result;
    };

    //hasClass
    imePlugin.dom.hasClass = function(el, className) {
        el = imePlugin.dom.g(el);
        var classArr = imePlugin.string.trim(className).split(/\s+/),
	      len = classArr.length;
        className = el.className.split(/\s+/).join(" ");
        while (len--) {
            if (!(new RegExp("(^| )" + classArr[len] + "( |\x24)")).test(className)) {
                return false;
            }
        }
        return true;
    }

    //addClass
    imePlugin.dom.addClass = function(el, className) {
        el = imePlugin.dom.g(el);
        var classArr = className.split(/\s+/),
	      result = el.className,
		  classMatch = " " + result + " ",
		  i = 0,
		  l = classArr.length;
        for (; i < l; i++) {
            if (classMatch.indexOf(" " + classArr[i] + " ") < 0) {
                result += (result ? ' ' : '') + classArr[i];
            }
        }
        el.className = result;
        return el;
    };

    //removeClass
    imePlugin.dom.removeClass = function(el, className) {
        el = imePlugin.dom.g(el);
        var oldClasses = el.className.split(/\s+/),
	      newClasses = className.split(/\s+/),
		  lenOld,
		  lenDel = newClasses.length,
		  j,
		  i = 0;
        for (; i < lenDel; ++i) {
            for (j = 0, lenOld = oldClasses.length; j < lenOld; ++j) {
                if (oldClasses[j] == newClasses[i]) {
                    oldClasses.splice(j, 1);
                    break;
                }
            }
        }
        el.className = oldClasses.join(' ');
        return el;
    };

    //hide
    imePlugin.dom.hide = function(el) {
        el = imePlugin.dom.g(el);
        el.style.display = "none";
    };

    //show
    imePlugin.dom.show = function(el) {
        el = imePlugin.dom.g(el);
        el.style.display = '';
    };

    //_NAME_ATTRS
    imePlugin.dom._NAME_ATTRS = (function() {
        var result = {
            'cellpadding': 'cellPadding',
            'cellspacing': 'cellSpacing',
            'colspan': 'colSpan',
            'rowspan': 'rowSpan',
            'valign': 'vAlign',
            'usemap': 'useMap',
            'frameborder': 'frameBorder'
        }
        if (imePlugin.browser.ie < 8) {
            result['for'] = 'htmlFor';
            result['class'] = 'className';
        } else {
            result['htmlFor'] = 'for';
            result['className'] = 'class';
        }
        return result;
    })();

    //getAttr
    imePlugin.dom.getAttr = function(el, key) {
        el = imePlugin.dom.g(el);
        if (key == 'style') {
            return el.style.cssText;
        }
        key = imePlugin.dom._NAME_ATTRS[key] || key;
        return el.getAttribute(key);
    };

    //setAttr
    imePlugin.dom.setAttr = function(el, key, value) {
        el = imePlugin.dom.g(el);
        if (key == 'style') {
            el.style.cssText = value;
        } else {
            key = imePlugin.dom._NAME_ATTRS[key] || key;
            el.setAttribute(key, value);
        }
        return el;
    };

    //setAttrs
    imePlugin.dom.setAttrs = function(el, attrs) {
        el = imePlugin.dom.g(el);
        for (var k in attrs) {
            imePlugin.dom.setAttr(el, k, attrs[k]);
        }
        return el;
    };

    //create
    imePlugin.dom.create = function(tagName, ops) {
        var el = document.createElement(tagName),
		    ops = ops || {};
        return imePlugin.dom.setAttrs(el, ops);
    };

    //children
    imePlugin.dom.children = function(el) {
        el = imePlugin.dom.g(el);
        for (var children = [], tmp = el.firstChild; tmp; tmp = tmp.nextSibling) {
            if (tmp.nodeType == 1) {
                children[children.length] = tmp;
            }
        }
        return children;
    }

    //insertBefore
    imePlugin.dom.insertBefore = function(newEl, existEl) {
        var g, existP;
        existP = existEl.parentNode;
        if (existP) {
            existP.insertBefore(newEl, existEl);
        }
        return newEl;
    };

    //insertAfter
    imePlugin.dom.insertAfter = function(newEl, existEl) {
        var g, existP;
        existP = existEl.parentNode;
        if (existP) {
            existP.insertBefore(newEl, existEl.nextSibling);
        }
        return newEl;
    }

    //remove
    imePlugin.dom.remove = function(el) {
        el = imePlugin.dom.g(el);
        var tmp = el.parentNode;
        tmp && tmp.removeChild(el);
    };

    /*
    find
    isP --true or false 表明当前el是父节点还是子节点,默认是true
    */
    imePlugin.dom.find = function(el, className, isP) {
        el = imePlugin.dom.g(el);
        if (isP == undefined) {
            isP = true;
        }
        var result,
		    childrenArr;
        if (!isP) {
            var elP = el.parentNode,
			childrenArr = imePlugin.dom.children(elP);
        } else {
            childrenArr = imePlugin.dom.children(el);
        }
        imePlugin.each(childrenArr, function(v, i) {
            if (imePlugin.dom.hasClass(v, className)) {
                result = v;
                return false;
            }
        });
        return result;
    };


    //event
    imePlugin.event = imePlugin.event || {};

    //addEvent
    imePlugin.event.addEvent = function(el, type, handler) {
        if (document.attachEvent) {
            el.attachEvent('on' + type, handler);
        } else if (document.addEventListener) {
            el.addEventListener(type, handler, false);
        }
    };

    imePlugin.event.preventDefault = function(event) {
        if (event.preventDefault) {
            event.preventDefault();
        } else {
            event.returnValue = false;
        }
    };

    //stopPropagation
    imePlugin.event.stopPropagation = function(e) {
        //        if (e.stopPropagation) {
        //            e.stopPropagation();
        //        } else {
        //            e.cancelBubble = true;
        //        }
    };

    imePlugin.event.getTarget = function(e) {
        return e.target || e.srcElement;
    };

    //each
    imePlugin.each = function(object, fn, context) {
        if (object) {
            var key,
				val,
				i = 0,
				length = object && object.length,
				isObj = length === undefined || typeof object === 'function';

            context = context || this;

            if (isObj) {
                for (key in object) {
                    if (fn.call(context, object[key], key, object) === 'false') {
                        break;
                    }
                }
            } else {
                for (val = object[0];
					 i < length && fn.call(context, val, i, object) !== 'false'; val = object[++i]) {
                }
            }
        }
        return object;
    };





    //render
    imePlugin.render = function(data, container) {
        var data = eval('(' + data + ')');
        var total = data.total,
           str = '';
        imePlugin.each(data['plugins'], function(val, i) {
            str += imePlugin.core.tpl(imePlugin.consts.template.pluginTpl, val);
        });
        imePlugin.dom.g(container).innerHTML = str;

        var useBtn,
	       updateBtn,
		   startBtn,
		   stopBtn,
		   unstallBtn,
		   stallBtn,
		   cancelBtn,
		   quickAs,
		   addClass = imePlugin.dom.addClass,
		   removeClass = imePlugin.dom.removeClass,
		   hasClass = imePlugin.dom.hasClass,
		   q = imePlugin.dom.q,
		   show = imePlugin.dom.show,
		   hide = imePlugin.dom.hide,
		   addEvent = imePlugin.event.addEvent,
		   stopPropagation = imePlugin.event.stopPropagation,
		   getTarget = imePlugin.event.getTarget,
		   getAttr = imePlugin.dom.getAttr,
		   statusInfo;
        //根据状态
        imePlugin.each(data['plugins'], function(val, i) {
            useBtn = q('use')[i];
            updateBtn = q('update')[i];
            startBtn = q('start')[i];
            stopBtn = q('stop')[i];
            unstallBtn = q('unstall')[i];
            stallBtn = q('stall')[i];
            cancelBtn = q('cancel')[i];
            statusInfo = q('statusInfo')[i];
            processStatus = q('processStatus')[i];
            quickAs = q('quickA')[i];
            hide(cancelBtn);
            hide(stopBtn);
            //zyc4-5
            if (i == 0) {
                var firstBox = imePlugin.getPluginBox(val['ID']);
                addClass(firstBox, 'selected');
            }

            if (val['Status'] == 0) {
                //NOTINSTALL
                hide(unstallBtn);
                addClass(useBtn, 'disabled');
                addClass(startBtn, 'disabled');
                addClass(updateBtn, 'disabled');
                addClass(stopBtn, 'disabled');
                hide(quickAs);
                processStatus.innerHTML = imePlugin.consts.noinstall

            } else if (val['Status'] == 1) {
                //INSTALLED
                hide(stallBtn);
                hide(startBtn);
                show(stopBtn);
                removeClass(stopBtn, 'disabled');
                statusInfo.innerHTML = '已启用';
                addClass(statusInfo, 'isStart');
                removeClass(statusInfo, 'noinstall');

                //是否有新版本
                if (val['HasNewVersion']) {
                    removeClass(updateBtn, 'disabled');
                    processStatus.innerHTML = imePlugin.consts.hasUpdateInfo;
                } else {
                    addClass(updateBtn, 'disabled');
                    processStatus.innerHTML = imePlugin.consts.noUpdateInfo;
                }

            } else if (val['Status'] == 2) {
                //FORBIDDEN
                hide(stallBtn);
                hide(quickAs);
                statusInfo.innerHTML = '未启用';
                addClass(statusInfo, 'noStart');
                removeClass(statusInfo, 'noinstall');
                addClass(useBtn, 'disabled');

                //是否有新版本
                if (val['HasNewVersion']) {
                    removeClass(updateBtn, 'disabled');
                    processStatus.innerHTML = imePlugin.consts.hasUpdateInfo;
                } else {
                    addClass(updateBtn, 'disabled');
                    processStatus.innerHTML = imePlugin.consts.stopUseInfo;
                }
            }

        });

        //绑事件
        //容器绑
        var pluginCon = q('pluginCon');
        var pluginConclickHandler = function(e) {
            //先removeClass
            for (var i = 0; i < pluginCon.length; i++) {
                removeClass(pluginCon[i], 'selected');
            }
            //再addClass
            var target = (e && e.srcElement) ? e.srcElement : this;
            if (!hasClass(target, 'pluginCon')) {
                target = target.parentNode;
                if (!hasClass(target, 'pluginCon')) {
                    target = target.parentNode;
                    if (!hasClass(target, 'pluginCon')) {
                        target = target.parentNode;
                    }
                }
            }
            addClass(target, 'selected');
        }

        for (var i = 0; i < pluginCon.length; i++) {
            imePlugin.event.addEvent(pluginCon[i], 'click', pluginConclickHandler);
            imePlugin.event.addEvent(pluginCon[i], 'dblclick', pluginConclickHandler);
        }

        //快捷键绑事件
        var quickAs = q('quickA');
        var quickAsclickHandler = function(e) {
            var that = getTarget(e);
            var pId = getAttr(that, 'pid');
            window.external.PluginCmd(pId, "快捷键");

            imePlugin.event.preventDefault(e);
            stopPropagation(e);
        };
        for (var i = 0; i < quickAs.length; i++) {
            addEvent(quickAs[i], 'click', quickAsclickHandler);
            addEvent(quickAs[i], 'dblclick', quickAsclickHandler);
        }


        //使用按钮绑
        var UseBtns = q('use');
        var UseBtnsclickHandler = function(e) {
            var that = getTarget(e);
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            var pId = getAttr(that, 'pid');
            window.external.PluginCmd(pId, '使用');
            stopPropagation(e);

        };
        for (var i = 0; i < UseBtns.length; i++) {
            addEvent(UseBtns[i], 'click', UseBtnsclickHandler);
            addEvent(UseBtns[i], 'dblclick', UseBtnsclickHandler);
        };

        //升级按钮绑
        var UpdateBtns = q('update');
        var UpdateBtnsclickHandler = function(e) {
            var that = getTarget(e),
		       container = that.parentNode;

            //初始化限制在这边吧
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            var pId = getAttr(that, 'pid');
            var pStatus = imePlugin.getProcessStatus(pId);
            pStatus.innerHTML = imePlugin.consts.updatingInfo;
            window.external.PluginCmd(pId, '升级');

            var cancel = imePlugin.dom.find(that, 'cancel', false);
            imePlugin.dom.removeClass(cancel, 'disable');
            imePlugin.renderProcessBar(container, cancel);
            stopPropagation(e);
        };
        for (var i = 0; i < UpdateBtns.length; i++) {
            addEvent(UpdateBtns[i], 'click', UpdateBtnsclickHandler);
            addEvent(UpdateBtns[i], 'dblclick', UpdateBtnsclickHandler);
        };

        //启用按钮绑
        var StartBtns = q('start');
        var StartBtnsclickHandler = function(e) {
            var that = getTarget(e);
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            var pId = getAttr(that, 'pid');
            imePlugin.AfterStart(pId);
            window.external.PluginCmd(pId, '启用');
            stopPropagation(e);
        };
        for (var i = 0; i < StartBtns.length; i++) {
            addEvent(StartBtns[i], 'click', StartBtnsclickHandler);
            addEvent(StartBtns[i], 'dblclick', StartBtnsclickHandler);
        };

        //禁用按钮绑
        var StopBtns = q('stop');
        var StopBtnsclickHandler = function(e) {
            var that = getTarget(e);
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            //事件调用

            var pId = getAttr(that, 'pid');
            imePlugin.AfterStop(pId);
            window.external.PluginCmd(pId, '禁用');
            stopPropagation(e);
        };
        for (var i = 0; i < StopBtns.length; i++) {
            addEvent(StopBtns[i], 'click', StopBtnsclickHandler);
            addEvent(StopBtns[i], 'dblclick', StopBtnsclickHandler);
        };

        //安装按钮绑
        var StallBtns = q('stall');
        var StallBtnsclickHandler = function(e) {
            var that = getTarget(e),
		       container = that.parentNode;
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            cancel = that.nextSibling;
            var pId = getAttr(that, 'pid');
            imePlugin.renderProcessBar(container, cancel);
            imePlugin.dom.removeClass(cancel, 'disable');
            var pStatus = imePlugin.getProcessStatus(pId);
            pStatus.innerHTML = imePlugin.consts.stallingInfo;

            window.external.PluginCmd(pId, '安装');

            stopPropagation(e);
        };
        for (var i = 0; i < StallBtns.length; i++) {
            addEvent(StallBtns[i], 'click', StallBtnsclickHandler);
            addEvent(StallBtns[i], 'dblclick', StallBtnsclickHandler);
        }

        //卸载按钮绑
        var UntallBtns = q('unstall');
        var UnstallBtnsclickHandler = function(e) {
            var that = getTarget(e);
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }
            //事件详情
            var pId = getAttr(that, 'pid');
            window.external.PluginCmd(pId, '卸载');

            imePlugin.AfterUnstall(pId);
            stopPropagation(e);
        };
        for (var i = 0; i < UntallBtns.length; i++) {
            addEvent(UntallBtns[i], 'click', UnstallBtnsclickHandler);
            addEvent(UntallBtns[i], 'dblclick', UnstallBtnsclickHandler);
        }

        //取消按钮绑
        var CancelBtns = q('cancel');
        var CancelBtnsclickHandler = function(e) {

            var that = getTarget(e),
		       parent = that.parentNode;
            if (hasClass(that, 'disabled')) {
                stopPropagation(e);
                return false;
            }

            //事件详情
            var pId = getAttr(that, 'pid');
            window.external.PluginCmd(pId, '取消下载');

            var processStatus = imePlugin.getProcessStatus(pId);

            var childrenArr = imePlugin.dom.children(parent);
            imePlugin.each(childrenArr, function(v, i) {
                if (imePlugin.dom.hasClass(v, 'dis')) {
                    imePlugin.dom.removeClass(v, 'dis');
                }
                if (imePlugin.dom.hasClass(v, 'percentage') || imePlugin.dom.hasClass(v, 'Progress')) {
                    imePlugin.dom.remove(v);
                }
            });

            var btnCon = imePlugin.getBtnCon(pId);
            var updateBtn = imePlugin.dom.find(btnCon, 'update');

            processStatus.innerHTML = imePlugin.consts.updateErrInfo;
            if (imePlugin.dom.hasClass(updateBtn, 'disabled')) {
                processStatus.innerHTML = imePlugin.consts.stallErrInfo;
            }

            imePlugin.dom.addClass(that, 'dis');
            stopPropagation(e);
        }
        for (var i = 0; i < CancelBtns.length; i++) {
            addEvent(CancelBtns[i], 'click', CancelBtnsclickHandler);
            addEvent(CancelBtns[i], 'dblclick', CancelBtnsclickHandler);
        }

    };



    /*
    考虑到复用性开接口获取对应元素
    */
    //获取第一级的容器
    imePlugin.getPluginBox = function(pID) {
        return imePlugin.dom.g(pID);
    };

    imePlugin.getDetailInfo = function(pID) {
        var con = imePlugin.getPluginBox(pID);
        return imePlugin.dom.find(con, 'detailInfo');
    };

    //获取快捷键
    imePlugin.getQuickA = function(pID) {
        var detailInfo = imePlugin.getDetailInfo(pID);
        var pFirst = imePlugin.dom.find(detailInfo, 'first');
        return imePlugin.dom.find(pFirst, 'quickA');
    };

    //获取版本号
    imePlugin.getVersion = function(pID) {
        var detailInfo = imePlugin.getDetailInfo(pID);
        var pFirst = imePlugin.dom.find(detailInfo, 'first');
        return imePlugin.dom.find(pFirst, 'Version');
    };


    //获取p1流程状态
    imePlugin.getStatusInfo = function(pID) {
        var detailInfo = imePlugin.getDetailInfo(pID);
        var pFirst = imePlugin.dom.find(detailInfo, 'first');
        return imePlugin.dom.find(pFirst, 'statusInfo');
    }

    //获取p2流程状态信息
    imePlugin.getProcessStatus = function(pID) {
        var detailInfo = imePlugin.getDetailInfo(pID);
        var pInfo = imePlugin.dom.find(detailInfo, 'pInfo');
        return imePlugin.dom.find(pInfo, 'processStatus');
    };


    //获取按钮区域btnCon
    imePlugin.getBtnCon = function(pID) {
        var detailInfo = imePlugin.getDetailInfo(pID);
        return imePlugin.dom.find(detailInfo, 'btnCon');
    };



    /*
    setProcessBar
    需要知道是升级or安装
    type -- 0 安装 默认值0  ---是否就是未启用
    1 升级 
    */
    imePlugin.setProcessBar = function(pID, bError, nPercentage, type) {
        //debugger;
        type = type || 0;
        var container = imePlugin.getPluginBox(pID);
        var detailInfo = imePlugin.getDetailInfo(pID);
        var statusInfo = imePlugin.getStatusInfo(pID);
        var processStatus = imePlugin.getProcessStatus(pID);
        var quickA = imePlugin.getQuickA(pID);
        var version = imePlugin.getVersion(pID);

        var btnCon = imePlugin.getBtnCon(pID);
        var Progress = imePlugin.dom.find(btnCon, 'Progress');
        var ProgressBar = imePlugin.dom.find(Progress, 'ProgressBar');
        var percentage = imePlugin.dom.find(btnCon, 'percentage');

        //各个按钮
        var useBtn = imePlugin.dom.find(btnCon, 'use');
        var updateBtn = imePlugin.dom.find(btnCon, 'update');
        var startBtn = imePlugin.dom.find(btnCon, 'start');
        var stopBtn = imePlugin.dom.find(btnCon, 'stop');
        var unstallBtn = imePlugin.dom.find(btnCon, 'unstall');
        var stallBtn = imePlugin.dom.find(btnCon, 'stall');
        var cancelBtn = imePlugin.dom.find(btnCon, 'cancel');

        var show = imePlugin.dom.show,
	      hide = imePlugin.dom.hide,
	      addClass = imePlugin.dom.addClass,
	      removeClass = imePlugin.dom.removeClass;

        //还要考虑失败情况
        if (bError) {
            processStatus.innerHTML = (type == 0) ? imePlugin.consts.stallErrInfo : imePlugin.consts.updateErrInfo;

            imePlugin.dom.remove(percentage);
            imePlugin.dom.remove(Progress);

            //需要操作按钮
            if (type == 0) {
                addClass(useBtn, 'disabled');
            }

            hide(cancelBtn);
            removeClass(useBtn, 'dis');
            removeClass(updateBtn, 'dis');
            removeClass(stopBtn, 'dis');
            removeClass(stallBtn, 'dis');
            removeClass(unstallBtn, 'dis');
            removeClass(startBtn, 'dis');

            //hide(startBtn);
            return false;
        }

        if (nPercentage > 99) {
            nPercentage = nPercentage - 1;
        }

        imePlugin.dom.setAttr(ProgressBar, 'style', 'width:' + nPercentage + '%');
        percentage.innerHTML = nPercentage + '%';
        processStatus.innerHTML = (type == 0) ? imePlugin.consts.stallingInfo : imePlugin.consts.updatingInfo;


        if (nPercentage == 99) {
            addClass(cancelBtn, 'disabled');
        }
        else if (nPercentage == 100) {
              
            if (type == 1) { //升级
                addClass(updateBtn, 'disabled');
                processStatus.innerHTML = imePlugin.consts.updateSucInfo;
            }
            else if (type == 0) {
                processStatus.innerHTML = imePlugin.consts.stallSucInfo;
            }

            //成功
            imePlugin.dom.remove(percentage);
            imePlugin.dom.remove(Progress);

            //安装成功--直接是已启用
            addClass(statusInfo, 'isStart');
            removeClass(statusInfo, 'noinstall');
            removeClass(statusInfo, 'noStart');


            statusInfo.innerHTML = '已启用';
            removeClass(cancelBtn, 'disabled')
            hide(cancelBtn);
            removeClass(useBtn, 'disabled dis');
            removeClass(updateBtn, 'dis');
            removeClass(stopBtn, 'dis disabled');
            addClass(stallBtn, 'disabled');
            show(unstallBtn);
            show(stopBtn);
            removeClass(unstallBtn, 'dis');
            removeClass(startBtn, 'dis');
            hide(startBtn);
            removeClass(quickA, 'disabled')
            show(quickA);

        }
    }

    /*
    renderProcessBar
    为了方便切换--取消和安装|升级
    我们现在的策略是取消按钮是第一次初始化载入
    @container --btnCon 容器
    @cancale  -- 取消按钮
    先给btnCon容器的所有子节点增加dis的class
    再控制cancel的显示并去掉上面加的dis的class
    创建Progress的容器和percentage的span
    以cancel为基准其前插入Progress | 以Progress为基准其后插入percentage
    */
    imePlugin.renderProcessBar = function(container, cancel) {
        //还是隐藏吧
        var childrenArr = imePlugin.dom.children(container);
        imePlugin.each(childrenArr, function(v, i) {
            imePlugin.dom.addClass(v, 'dis');
        });
        imePlugin.dom.removeClass(cancel, 'dis');
        imePlugin.dom.show(cancel);

        var Progress = imePlugin.dom.create('div', { 'class': 'Progress' });
        var percentage = imePlugin.dom.create('span', { 'class': 'percentage' });

        Progress.innerHTML = imePlugin.consts.template.processTpl;
        percentage.innerHTML = '0%';

        imePlugin.dom.insertBefore(Progress, cancel);
        imePlugin.dom.insertAfter(percentage, Progress);
    };


    //刷新快捷键
    imePlugin.refreshQuick = function(pID, data) {
        var quickA = imePlugin.getQuickA(pID);
        quickA.innerHTML = data;
    };

    //刷新版本号
    //刷新快捷键
    imePlugin.refreshVersion = function(pID, data) {
        var version = imePlugin.getVersion(pID);
        version.innerHTML = data;
    }

    //刷新p1的状态
    imePlugin.refreshStatusInfo = function(pID, type) {
        var statusInfo = imePlugin.getStatusInfo(pID),
	      addClass = imePlugin.dom.addClass,
		  removeClass = imePlugin.dom.removeClass,
		  hasClass = imePlugin.dom.hasClass;

        if (type == 0) {
            //NOTINSTALL
            if (hasClass(statusInfo, 'noinstall')) {
                return false;
            } else {
                addClass(statusInfo, 'noinstall');
                statusInfo.innerHTML = '未安装';
            }
        } else if (type == 1) {
            //INSTALLED
            if (hasClass(statusInfo, 'isStart')) {
                return false;
            } else {
                addClass(statusInfo, 'isStart');
                statusInfo.innerHTML = '已启用';
            }
        } else if (type == 2) {
            //FORBIDDEN
            if (hasClass(statusInfo, 'noStart')) {
                return false;
            } else {
                addClass(statusInfo, 'noStart');
                statusInfo.innerHTML = '未启用';
            }
        }
    }


    //刷新processStatus
    imePlugin.refreshProcessStatus = function(pID, data) {
        var processStatus = imePlugin.getProcessStatus(pID);

    };

    //检测是否有更新
    imePlugin.AfterUpdateCheck = function(pID, flag) {
        //        debugger;
        var btnCon = imePlugin.getBtnCon(pID);
        var updateBtn = imePlugin.dom.find(btnCon, 'update');
        var processStatus = imePlugin.getProcessStatus(pID),
	      addClass = imePlugin.dom.addClass,
		  removeClass = imePlugin.dom.removeClass,
		  hasClass = imePlugin.dom.hasClass;
        flag = flag || false;
        if (flag) {
            processStatus.innerHTML = '';
            if (hasClass(updateBtn, 'disabled')) {
                removeClass(updateBtn, 'disabled');
            }
        } else {
            processStatus.innerHTML = imePlugin.consts.noUpdateInfo;
        }
    }

    //卸载之后
    imePlugin.AfterUnstall = function(pID) {
        var statusInfo = imePlugin.getStatusInfo(pID);
        var processStatus = imePlugin.getProcessStatus(pID);
        var btnCon = imePlugin.getBtnCon(pID);
        var quickA = imePlugin.getQuickA(pID);

        //各个按钮
        var useBtn = imePlugin.dom.find(btnCon, 'use');
        var updateBtn = imePlugin.dom.find(btnCon, 'update');
        var startBtn = imePlugin.dom.find(btnCon, 'start');
        var stopBtn = imePlugin.dom.find(btnCon, 'stop');
        var unstallBtn = imePlugin.dom.find(btnCon, 'unstall');
        var stallBtn = imePlugin.dom.find(btnCon, 'stall');
        var cancelBtn = imePlugin.dom.find(btnCon, 'cancel');

        var show = imePlugin.dom.show,
	      hide = imePlugin.dom.hide,
	      addClass = imePlugin.dom.addClass,
	      removeClass = imePlugin.dom.removeClass;


        addClass(statusInfo, 'noinstall');
        removeClass(statusInfo, 'isStart');
        removeClass(statusInfo, 'noStart');
        statusInfo.innerHTML = '未安装';
        processStatus.innerHTML = imePlugin.consts.unstallSucInfo;
        //控制按钮
        addClass(useBtn, 'disabled');
        addClass(updateBtn, 'disabled');
        addClass(stopBtn, 'disabled');
        show(stopBtn);
        hide(unstallBtn);
        show(stallBtn);
        addClass(startBtn, 'dis');
        hide(startBtn);

        removeClass(stallBtn, 'dis disabled');
        hide(quickA);

    }

    //禁用之后
    imePlugin.AfterStop = function(pID) {
        var quickA = imePlugin.getQuickA(pID);
        var statusInfo = imePlugin.getStatusInfo(pID);
        var processStatus = imePlugin.getProcessStatus(pID);
        var btnCon = imePlugin.getBtnCon(pID);
        //各个按钮
        var useBtn = imePlugin.dom.find(btnCon, 'use');
        var updateBtn = imePlugin.dom.find(btnCon, 'update');
        var startBtn = imePlugin.dom.find(btnCon, 'start');
        var stopBtn = imePlugin.dom.find(btnCon, 'stop');
        var unstallBtn = imePlugin.dom.find(btnCon, 'unstall');
        var stallBtn = imePlugin.dom.find(btnCon, 'stall');
        var cancelBtn = imePlugin.dom.find(btnCon, 'cancel');

        var show = imePlugin.dom.show,
	      hide = imePlugin.dom.hide,
	      addClass = imePlugin.dom.addClass,
	      removeClass = imePlugin.dom.removeClass;

        removeClass(statusInfo, 'isStart');
        addClass(statusInfo, 'noStart');
        statusInfo.innerHTML = '未启用';
        hide(stopBtn);
        show(startBtn);
        removeClass(startBtn, 'disabled');
        addClass(useBtn, 'disabled');
        if (imePlugin.dom.hasClass(updateBtn, 'disabled')) {
            processStatus.innerHTML = imePlugin.consts.stopUseInfo;
        }

        hide(quickA);
    }

    //启用之后
    imePlugin.AfterStart = function(pID) {
        var quickA = imePlugin.getQuickA(pID);
        var statusInfo = imePlugin.getStatusInfo(pID);
        var processStatus = imePlugin.getProcessStatus(pID);
        var btnCon = imePlugin.getBtnCon(pID);
        //各个按钮
        var useBtn = imePlugin.dom.find(btnCon, 'use');
        var updateBtn = imePlugin.dom.find(btnCon, 'update');
        var startBtn = imePlugin.dom.find(btnCon, 'start');
        var stopBtn = imePlugin.dom.find(btnCon, 'stop');
        var unstallBtn = imePlugin.dom.find(btnCon, 'unstall');
        var stallBtn = imePlugin.dom.find(btnCon, 'stall');
        var cancelBtn = imePlugin.dom.find(btnCon, 'cancel');

        var show = imePlugin.dom.show,
	      hide = imePlugin.dom.hide,
	      addClass = imePlugin.dom.addClass,
	      removeClass = imePlugin.dom.removeClass;

        hide(startBtn);
        show(stopBtn);
        removeClass(stopBtn, 'disabled');
        removeClass(useBtn, 'disabled');

        removeClass(statusInfo, 'noStart');
        addClass(statusInfo, 'isStart');

        statusInfo.innerHTML = '已启用';
        if (imePlugin.dom.hasClass(updateBtn, 'disabled')) {
            processStatus.innerHTML = imePlugin.consts.useInfo;
        }

        show(quickA);
    }


    //右键和内容选择屏蔽 
    var ContextmenuHandler = function(e) {
        imePlugin.event.preventDefault(e);
    }
    window.onload = function() {
        imePlugin.event.addEvent(document, 'contextmenu', ContextmenuHandler);
        imePlugin.event.addEvent(document, 'selectstart', ContextmenuHandler);
    }

})(window);