function preventDefault(e) {
    if (e && e.preventDefault){　　 
    　　e.preventDefault();
    }else{
    　　e.returnValue = false;
	}
    return false;
}
if (!Array.prototype.forEach) {
    Array.prototype.forEach = function(f, obj) {
        var l = this.length;
        for (var i = 0; i < l; i++) {
            f.call(obj, this[i], i, this);
        }
    };
}

/**
 * 支付宝安全控件检测接口 v1.0
 * _env{platform,browser,browserMode}
 * _url{win,mac,downSrc,update()}
 * _installedAliedit
 * =====public=====
 * init()
 * alieditSwitch()
 * detectAliedit()
 * getAliedit()
 * downAliedit()
 * checkService()
 * =====private=====
 * notApplyAliedit()
 * getSubmitObj()
 * revertEmbedNode()
 * switchAlieditPopInfo()
 *
 * combFunc()
 * allowComb()
 */

var AlieditControl = {};
(function() {
    var AC = AlieditControl;
    var alieditContainer_arr=null;
    //是否弹出了未安装控件的内容
    _popAlieditInstall=false;
    //检测页面中是否调用控件，以确定是否开启自动检测功能。（暂定不开启自动检测功能）
	AC.detect=false;
	//环境变量
    var _env = (function() {
        var userAgent = navigator.userAgent.toLowerCase();
        return {
            platform: {
                windows: /(windows|win32)/.test(userAgent),
                mac: /macintosh/.test(userAgent)
            },
            browser: {
                version: (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1],
                webkit: /webkit/.test(userAgent),
                opera: /opera/.test(userAgent),
                msie: /msie/.test(userAgent) && !/opera/.test(userAgent),
                mozilla: /mozilla/.test(userAgent) && !/(compatible|webkit)/.test(userAgent)
            },
            browserMode:document.compatMode
        };
    })();
	AC.env=_env;
	//判断是否已安装控件
    var _installedAliedit = (function() {
        var mac = _env.platform.mac;
        var aliedit = null;
        if (window.ActiveXObject) {
            try {
                aliedit = new ActiveXObject('Aliedit.EditCtrl');
            } catch(er) {};
        } else {
            aliedit = navigator.plugins['Alipay security control']||navigator.plugins['Aliedit Plug-In']||navigator.plugins['Aliedit']||null;
        }
        return aliedit?true:false;
    })();
    
	AC.installedAliedit=_installedAliedit;
	//默认控件安装程序url
    var _url = {
        win: {
            ie: "https://img.alipay.com/download/2121/aliedit.exe",
            noie: "https://img.alipay.com/download/aliedit/npaliedit.exe"
        },
        mac: {
            safari: "https://img.alipay.com/download/aliedit/wkaliedit.dmg"
        },
        downSrc: null,
		//检测平台、浏览器的类型，并返回相应的控件下载url
        update: function() {
			var url = null;
			if (_env.platform.windows) {
				if (_env.browser.msie) {
					url = _url.win.ie;
				} else {
					url = _url.win.noie;
				}
			} else if (_env.platform.mac) {
				if (_env.browser.webkit) {
					url = _url.mac.safari;
				} else {
					url = null;
				}
			} else {
				url = null;
			}
			_url.downSrc = url;
			return url;
		}
    };
	_url.update();
	AC.url=_url;
	//初始化
    AC.init = function() {
    	/*
    	//给帮助链接增加浏览器识别锚记
    	var alieditHelpLink=AC.dom.get('alieditHelpLink');
    	if(alieditHelpLink){
    		alieditHelpLink.href=alieditHelpLink.href+(_env.browser.msie?'#ie':(_env.browser.mozilla?'#firefox':''));
		}
		*/
    	//初使化静态变量
    	alieditContainer_arr=AC.dom.getElementsByAttr('class', 'alieditContainer','span');
    	//切换控件状态
    	AC.alieditSwitch();
		//业务
		AC.checkService('PTA');
		AC.checkService('PCID');
    	/*
    	//判断页面上控件状态，是否需要检测
		if(alieditContainer_arr.length>0){
			alieditContainer_arr.forEach(function(o, i) {
				var detect=o.getAttribute('detect');
				if(detect==null||detect=='true'){
					AC.detect=true;
				}
			});
		}
		*/
		//为红框类内容绑定事件
		var popAlieditInstallInfo_arr = AC.dom.getElementsByAttr('class', 'popAlieditInstallInfo','a');
		if(popAlieditInstallInfo_arr.length>0){
	        AC.on(popAlieditInstallInfo_arr, 'mouseover',
	        function(e) {
	            return true;
	        });
	        AC.on(popAlieditInstallInfo_arr, 'focus',
	        function(e) {
	            this.blur();
	        });
	        AC.on(popAlieditInstallInfo_arr, 'click',
	        function(e) {
	             AC.detectAliedit();
	             preventDefault(e);
	        });
    	}
    	//为文字类内容绑定事件
        var alieditDownLink_arr = AC.dom.getElementsByAttr('class', 'alieditDownLink','a');
        if(alieditDownLink_arr.length>0){
	        AC.on(alieditDownLink_arr, 'mouseover',
	        function(e) {
	            return true;
	        });
	        AC.on(alieditDownLink_arr, 'focus',
	        function(e) {
	            this.blur();
	        });
	        AC.on(alieditDownLink_arr, 'click',
	        function(e) {
	             AC.downAliedit(this);
	        });
    	}
    	//为关闭按钮绑定事件
        var closeAlieditBox_arr=AC.dom.getElementsByAttr('class', 'closeAlieditBox','a');
        if(closeAlieditBox_arr.length>0){
	        AC.on(closeAlieditBox_arr, 'click',
	        function(e) {
	        	//显示窗体滚动条
	        	document.getElementsByTagName('html')[0].style.overflow='auto';
				_popAlieditInstall=false;
	            try {
	                AC.closeAlieditBox();
	            } catch(er) {};
	            preventDefault(e);
	        });
    	}
		//为控件绑定回车
        var object_arr = AC.getAliedit();
        if(object_arr.length>0){
	        object_arr.forEach(function(o, i) {
	            AC.on(o, 'keydown',
	            function(e) {
	                try {
	                    if (e.keyCode == 13) {
	                        var submitObj=getSubmitObj(this.form);
	                        submitObj? submitObj.click() : null;
	                    }
	                } catch(er) {};
	            });
	        });
    	}
    	//自动检测
		//AC.detect?AC.detectAliedit():null;
		//组合函数
		//combFunc();
    };
	//切换控件内容
    AC.alieditSwitch=function() {
		alieditContainer_arr=AC.dom.getElementsByAttr('class', 'alieditContainer','span');
        var installed = _installedAliedit;
        if(alieditContainer_arr.length>0){
	        alieditContainer_arr.forEach(function(o, i) {
	        	if(!installed){
                	o.innerHTML="<a href='javascript:void(0);' class='popAlieditInstallInfo'>请点此输入密码</a>";
            	}else{
            		//针对embed不能在某些浏览器中100%的情况做处理
            		if (!window.ActiveXObject) {
	            		var embedNode=AC.dom.getElementsByAttr('type', 'application/aliedit', 'embed',o)[0];
	            		embedNode?o.innerHTML=revertEmbedNode(embedNode):null;
        			}
            	}
	        });
    	}
    };
	//检测控件或给予相应弹出提示
    AC.detectAliedit = function() {
    	if(!_url.downSrc){
	        notApplyAliedit();
	        return false;
	    }
        if (!_installedAliedit) {
        	_popAlieditInstall=true;
            try {
				switchAlieditPopInfo('notInstalledAlieditInfo');
                openAlieditBox({openDiv:'alieditPopInfo'});
            } catch(er) {
                alert('您还未安装密码安全控件，安装后即可输入密码。');
            };
            return false;
        }
        //return true;
    };
    /**
	 * 获取页面上已加载的控件对象的ID值
	 * arguments[0]：string：返回此id的控件对象
	 * arguments[0]：object：返回相应对象区域内的控件数组
	 */
    AC.getAliedit = function() {
        var object_arr = null;
        var arg0=arguments[0];
        if(arg0&&typeof(arg0) == 'string'){
    		return document.getElementById(arg0+(window.ActiveXObject?'_ie':'_noie'))||null;
        }
        var parentNode = (arg0&&arg0.nodeName&&typeof(arg0) == 'object') ? arg0 : document;
        if (window.ActiveXObject) {
            object_arr = AC.dom.getElementsByAttr('classid', 'clsid:488A4255-3236-44B3-8F27-FA1AECAA8844', 'object',parentNode);
        } else {
            object_arr = AC.dom.getElementsByAttr('type', 'application/aliedit', 'embed',parentNode);
        }
        return object_arr;
    };
	//移除控件节点
    AC.removeAliedit = function() {
        if (alieditContainer_arr.length > 0) {
            alieditContainer_arr.forEach(function(o, i) {
                o.parentNode.removeChild(o);
            });
        }
    };
	//转到下载
    AC.downAliedit = function(oLink) {
        var url = _url.downSrc;
        if (url) {
        	/*
        	//预留firefox下控件自动运行JS
        	if(_env.browser.mozilla){
        		var params = {
				    "支付宝安全控件": { 
				    	URL: 'https://img.alipay.com/download/aliedit/npaliedit.xpi',
				        IconURL: 'https://img.alipay.com/img/icon/favicon.ico'
				    }
				};
				try{
					InstallTrigger.install(params);
				}catch(er){
					oLink.href = url;
				};
        	}else{
            	oLink.href = url;
        	}
        	*/
        	oLink.href = url;
        	if(_popAlieditInstall){
        		try{
	            	switchAlieditPopInfo('afterClickInstallInfo');
		        	openAlieditBox({openDiv:'alieditPopInfo'});
	        	}catch(er){
	        		alert('完成安装后，请您重新启动浏览器。');
	        	};
        	}
        } else {
			notApplyAliedit();            
        }
    };
/**
 * 业务级内容
 * PCID
 * input[name='REMOTE_PCID_NAME'] 
 * PTA
 * .promptText_PTA PTA的提示内容
 * input[name='PTA_SN'] 
 */
    AC.checkService = function(type) {
        if (window.ActiveXObject) {
            switch (type) {
            case 'PCID':
                var name_input = AC.dom.getElementsByAttr('name', 'REMOTE_PCID_NAME', 'input')[0];
                if (name_input && name_input.value != '') {
                    try {
                        var aliObject = new ActiveXObject("alim.webmod");
                        var encryptText = aliObject.ci4();
                        var unEncryptText = aliObject.ciraw();
                        var node_arr=AC.dom.getElementsByAttr('name', name_input.value, 'input');
                        if(node_arr.length>0){
	                        node_arr.forEach(function(o, i) {
	                            o.value = unEncryptText;
	                        });
                   		}
                    } catch(er) {};
                }
                break;
            case 'PTA':
                var sn_arr = AC.dom.getElementsByAttr('name', 'PTA_SN', 'input');
                if (sn_arr[0]&&sn_arr[0].value!='') {
                	var sn=sn_arr[0].value;
                    try {
                        var iTrusPTA = new ActiveXObject("PTA.iTrusPTA");
                        if (parseInt(sn.substr(0, 1), 16) > 8) {
                            sn = "00" + sn;
                        }
                        var certFilter = iTrusPTA.Filter;
                        certFilter.Clear();
                        certFilter.SerialNumber = sn;
                        if (iTrusPTA.MyCertificates.Count <= 0) {
                            certFilter.Clear();
                            certFilter.SerialNumber = sn;
                            //隐藏控件
                            sn_arr.forEach(function(o,i){
                            	var arr=AC.dom.getElementsByAttr('class', 'alieditContainer','span',o.form);
                            	arr.forEach(function(o,i){
                            		o.style.width='0px';
                            		o.style.height='0px';
                            		o.style.overflow='hidden';
                            		var aliedit=AC.getAliedit(o)[0];
                            		if(aliedit){
                            			aliedit.style.width='0px';
                            			aliedit.style.height='0px';
                            		}
                            	});
                            });
							//显示没有检测到支付盾的提示
							var node_arr=AC.dom.getElementsByAttr('class', 'promptText_PTA','span');
                            if(node_arr.length>0){
	                            node_arr.forEach(function(o, i) {
	                               o.style.display = 'inline';
	                            });
	                        }
                        }
                    } catch(er) {};
                }
                break;
            }
        }

    };
    //判断当前浏览器是否支持安全控件
    function notApplyAliedit(){
    	try {
			switchAlieditPopInfo(_env.platform.mac?'notSupportAlieditInfo-mac':(_env.platform.windows?'notSupportAlieditInfo-win':'notSupportAlieditInfo-other'));
            openAlieditBox({openDiv:'alieditPopInfo'});
        } catch(er) {
            alert('您现在所用的浏览器，暂不支持安全控件。');
        };
    }
	//获取form中的[type=submit]对象
	function getSubmitObj(oForm){
		var node_arr=oForm.getElementsByTagName('*');
		for(var i=0;i<node_arr.length;i++){
			if(node_arr[i].type=='submit'){
				return node_arr[i];
				break;
			}
		}
		return null;
	}
	//拼合embed节点
    function revertEmbedNode(obj){
    	var w=0;
    	if(!window.ActiveXObject){
    		w=parseFloat(document.defaultView.getComputedStyle(obj.parentNode.parentNode,null)['width']);
    	}
    	var str='<embed ';
    	var attr_arr=obj.attributes;
		for(var i in attr_arr){
			var attr=attr_arr[i];
		    if(attr.specified){
		    	str+=' '+attr.name+'="'+(attr.name=='width'&&w>0?w:attr.value)+'"';
		    }
		}
		str+=' />';
		return str;
    }
	//切换控件相关弹出内容
    function switchAlieditPopInfo(id) {
        var infoId_arr = ['notInstalledAlieditInfo','afterClickInstallInfo', 'notSupportAlieditInfo-win', 'notSupportAlieditInfo-mac', 'notSupportAlieditInfo-other'];
        infoId_arr.forEach(function(o, i) {
            AC.dom.get(o)?AC.dom.get(o).style.display = 'none':null;
        });
        id && id != ''&&AC.dom.get(id)? AC.dom.get(id).style.display = 'block': null;
    }
	//不同浏览器中实现inline-block
    function setAlieditContentDisplay(obj) {
        obj.style.display = 'inline-block';
        if (_env.browser.mozilla) {
            obj.style.display = '-moz-inline-stack';
        }
        if (_env.browser.msie) {
            obj.style.display = 'inline';
            obj.style.zoom = '1';
        }
    }
	//组合控件和onsubmit函数
	function combFunc(){
		var forms=document.forms;
		for(var i=0;i<forms.length;i++){
			if(allowComb(forms[i])){
				(function(oForm){
					var originalFunc=oForm.onsubmit;
					var newFunc=function(){
						return AC.detectAliedit()&&originalFunc.call(oForm);
					};
					oForm.onsubmit=newFunc;
				})(forms[i]);
			}
		}
	}
	//是否满足组合控件和onsubmit函数的条件
	function allowComb(oForm){
		if(oForm.onsubmit&&AC.getAliedit(oForm)[0]){
			return true;
		}
		return false;
	}
    AC.onDOMReady = function(onready, config) {
        var browser = _env.browser;
        this.conf = {
            enableMozDOMReady: true
        };
        if (config) {
            for (var p in config) {
                this.conf[p] = config[p];

            }
        }
        var isReady = false;
        function doReady() {
            if (isReady) return;

            isReady = true;
            onready();
        }
        /*IE*/
        if (browser.msie) { (function() {
                if (isReady) return;
                try {
                    document.documentElement.doScroll("left");
                } catch(error) {
                    setTimeout(arguments.callee, 0);
                    return;
                }
                doReady();
            })();
            window.attachEvent('onload', doReady);
        }
        /*Webkit*/
        else if (browser.webkit && browser.version < 525) { (function() {
                if (isReady) return;
                if (/loaded|complete/.test(document.readyState)) {
                    doReady();
                } else {
                    setTimeout(arguments.callee, 0);
                }
            })();
            window.addEventListener('load', doReady, false);
        }
        /*FF Opera 高版webkit 其他*/
        else {
            if (!browser.mozilla || browser.version != 2 || this.conf.enableMozDOMReady) {
                document.addEventListener("DOMContentLoaded",
                function() {
                    document.removeEventListener("DOMContentLoaded", arguments.callee, false);
                    doReady();
                },
                false);
            }
            window.addEventListener('load', doReady, false);
        }

    };
    AC.on = function(os, type, fn) {
        if (typeof(os) == 'object'||typeof(os) == 'function') {
        	if(!os.length){os=[os]}
          	 os.forEach(function(o,i){
                if (window.addEventListener) {
                    o.addEventListener(type,
                    function(e) {
                        fn.call(o,e);
                    },
                    false);
                } else if (window.attachEvent) {
                    o.attachEvent('on' + type,
                    function(e) {
                        fn.call(o,e);
                    });
                } else {
                    o['on' + type] = function(e) {
                        fn.call(o,e);
                    };
                }
			});
        }
    };
    AC.dom = {
        getElementsByAttr: function(attr, value, tag, parent) {
            var parent = parent || document;
            var nodes = parent.getElementsByTagName(tag || '*');
            var newNodes = [];

            for (var i = 0; i < nodes.length; i++) {
                switch (attr) {
                case 'class':
                    var re = new RegExp('(?:^|\\s+)' + value + '(?:\\s+|$)');
                    if (re.test(nodes[i].className)) {
                        newNodes.push(nodes[i]);
                    }

                    break;
                default:
                    if (nodes[i].getAttribute(attr) == value) {
                        newNodes.push(nodes[i]);
                    }
                    break;
                }
            }
            return newNodes;
        },
        get: function(id) {
            return document.getElementById(id) || null;
        }

    };

	function closeAlieditBox(){
		if(theOpenDiv==null){return};
		alieditBox_float.style.display = 'none';
		alieditBox_container.style.display="none";
		theOpenDiv.style.display="none";
		openDiv_parent.appendChild(theOpenDiv);
		disableAlieditBox=false;
	}
	function openAlieditBox(argsObj){
		if(disableAlieditBox){return};
		disableAlieditBox=true;
		//
		cssObj=argsObj.cssObj;
		openDiv=argsObj.openDiv;
		theOpenDiv=AC.dom.get(argsObj.openDiv);
		if(theOpenDiv==null){return};
		openDiv_parent=theOpenDiv.parentNode;
		//
		alieditBox_float=AC.dom.get("alieditBox_float");
		alieditBox_container=AC.dom.get("alieditBox_container");
		if(alieditBox_float==null){
			alieditBox_float = document.createElement("div");
			alieditBox_float.id="alieditBox_float";
			//对iframe加载控件的情况进行处理
			if(window.top!=self&&_env.browser.msie){
				alieditBox_float.style.filter='';
			}
			document.body.appendChild(alieditBox_float);
		}
		if(alieditBox_container==null){
			alieditBox_container = document.createElement("div");
			alieditBox_container.id="alieditBox_container";
			document.body.appendChild(alieditBox_container);
			var lbStr='';
			lbStr+="<div class='lb_body' id='alieditBox_body'></div>";
			alieditBox_container.innerHTML=lbStr;
		}
		AC.dom.get("alieditBox_body").appendChild(theOpenDiv);
		//
		alieditBox_float.style.display = 'block';
		alieditBox_container.style.display="block";
		theOpenDiv.style.display="block";
		if(cssObj){
			for(var i in cssObj){
				cssObj[i]?alieditBox_container.style[i]=cssObj[i]:null;
			}
		}
		//隐藏窗体滚动条
		document.getElementsByTagName('html')[0].style.overflow='hidden';
		changeStyleTop();
		var interval=1;
		var timerHandle=setTimeout(function(){
			changeStyleTop();
			if(disableAlieditBox){
				timerHandle=setTimeout(arguments.callee,interval);
			}else{
				clearTimeout(timerHandle);
			}
		},interval);
	}
	function getDocHeight() {
            var scrollHeight = (_env.browserMode == 'CSS1Compat') ?document.documentElement.scrollHeight:document.body.scrollHeight;
            var h = Math.max(scrollHeight, getViewportHeight());
            return h;
    }
    function getDocWidth() {
            var scrollWidth = (_env.browserMode == 'CSS1Compat') ?document.documentElement.scrollWidth:document.body.scrollWidth;
            var w = Math.max(scrollWidth, getViewportWidth());
            return w;
    }
    function getViewportHeight(){
    	var h=self.innerHeight;
    	if(_env.browser.msie){
    		h=(_env.browserMode=='CSS1Compat')?document.documentElement.clientHeight:document.body.clientHeight;
    	}
    	return h;
    }
    function getViewportWidth(){
    	var w=self.innerWidth;
    	if(_env.browser.msie){
    		w=(_env.browserMode=='CSS1Compat')?document.documentElement.clientWidth:document.body.clientWidth;
    	}
    	return w;
    }
    function getDocScrollLeft(){
    	return window.pageXOffset?window.pageXOffset:Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);
    }
    function getDocScrollTop(){
    	return window.pageYOffset?window.pageYOffset:Math.max(document.documentElement.scrollTop,document.body.scrollTop);
    }
	function changeStyleTop() {
			alieditBox_float.style.height=getDocHeight() +"px";
			alieditBox_float.style.width=getDocWidth()+"px";
			var x=getDocScrollLeft()+(getViewportWidth()-alieditBox_container.offsetWidth)/2;
			var y=getDocScrollTop()+(getViewportHeight()-alieditBox_container.offsetHeight)/2;
			x=(x<=0||isNaN(x))?0:x;
			y=(y<=0||isNaN(y))?0:y;
			alieditBox_container.style.marginLeft=x+"px";
			alieditBox_container.style.marginTop=y+"px";
	}

	var openDiv=null;
	var theOpenDiv =null;
	var openDiv_parent=null;
	var alieditBox_float=null;
	var alieditBox_container=null;
	var disableAlieditBox=false;
	AC.closeAlieditBox =function(){
		closeAlieditBox();
	}
	//对iframe加载控件的情况进行处理
	if(window.top==self){
	    AC.onDOMReady(function() {
			AC.init();
		});
	}else{
		if(_env.browser.msie){
			document.onreadystatechange=function(){
				if(document.readyState=='complete'){
					AC.init();
			    }
			}
		}else{
			AC.onDOMReady(function() {
				AC.init();
			});
		}
	}
})();

