// ------------------------> 常量，保持跟 style_1.php 一致
var COLOR1 = '#F0F0F0';
var COLOR2 = '#E4E4E4';
var COLOR3 = '#D0D0D0';
var COLOR5 = '#770000';

// ------------------------> 兼容性判断
var userAgent = navigator.userAgent.toLowerCase();
var is_opera = userAgent.indexOf('opera') != -1 && opera.version();
var is_moz = (navigator.product == 'Gecko') && userAgent.substr(userAgent.indexOf('firefox') + 8, 3);
var is_ie = (userAgent.indexOf('msie') != -1 && !is_opera) && userAgent.substr(userAgent.indexOf('msie') + 5, 3);

// ------------------------> 常用的函数
if(typeof $ == 'undefined') {
	function $(id) {
		return document.getElementById(id);
	}
}

Array.prototype.push = function(value) {
	this[this.length] = value;
	return this.length;
}

var attachEvents = new Array();
if(typeof _attachEvent == 'undefined') {
	function _attachEvent(obj, evt, func, uniqid) {
		if(uniqid && attachEvents[uniqid]) {
			return true;
		} else {
			if(obj.addEventListener) {
				obj.addEventListener(evt, func, false);
			} else if(obj.attachEvent) {
				obj.attachEvent("on" + evt, func);
			}
			attachEvents[uniqid] = 1;
		}
	}
}

function _cancelBubble(e, returnValue) {
	if(!e) return ;
	try {
		if(is_ie) {
			if(!returnValue && e) e.returnValue = false;
			if(e)e.cancelBubble = true;
		} else {
			if(e.stopPropagation)e.stopPropagation();
			if(!returnValue && e.preventDefault) e.preventDefault();
		}
	} catch(e) {/*alert('_cancelBubble:' + e.message)*/}
}

// 得到某个对象的绝对定位
if(typeof getposition == 'undefined') {
	function getposition(obj) {
		var r = new Array();
		r['x'] = obj.offsetLeft;
		r['y'] = obj.offsetTop;
		while(obj = obj.offsetParent) {
			r['x'] += obj.offsetLeft;
			r['y'] += obj.offsetTop;
		}
		return r;
	}
}

// ------------------------> setdata() savedata(), 2M
if(is_ie) document.documentElement.addBehavior("#default#userdata");

//private
function getdata(key){
	if(is_ie){
		with(document.documentElement)try {
			load(key);
			return getAttribute("value");
		} catch(error) {alert(error.message);}
	} else {
		return sessionStorage.getItem(key) && sessionStorage.getItem(key).toString().length == 0 ? '' : (sessionStorage.getItem(key) == null ? '' : sessionStorage.getItem(key));
	}
}

function setdata(key, value){
	if(is_ie){
		with(document.documentElement)try {
			load(key);
			setAttribute("value", value);
			save(key);
			return  getAttribute("value");
		} catch(error) {/*alert('setdata:'+error.message);*/}
	} else {
		sessionStorage.setItem(key, value);
	}
}

/*
function form_option_selected(obj, value) {
	for(var i=0; i<obj.options.length; i++) {
		if(obj.options[i].value == value) {
			obj.options[i].selected = true;
		}
	}
}
*/

// -----------------------------> ajax.js
function get_domain(url) {
	/(\w+\.(\w+\.\w+))\//.exec(url);
	return new Array(RegExp.$1, RegExp.$2);
}

function unhtmlspecialchars(s) {
	s = s.replace(/\&amp\;/g, '&');
	s = s.replace(/\&lt\;/g, '<');
	s = s.replace(/\&gt\;/g, '>');
	return s;
}

//避免重复创建
function Ajax(waitId){
	// 加载进度条
	var ajax = new Object();
	ajax.waitId = $(waitId);
	if(ajax.waitId == null) {
		if(!$('ajax_default_waitid')) {
			var waitdiv = document.createElement('div');
			waitdiv.id = 'ajax_default_waitid';
			waitdiv.className = "ajaxloading";
			$('append').appendChild(waitdiv);
		} else {
			waitdiv = $('ajax_default_waitid');
		}
		ajax.waitId = waitdiv;
	}

	ajax.loading = '<img src="image/common/loading.gif" style="margin: 3px; vertical-align: middle" height="16" /><span style="margin-right: 8em;">Loading...</span>';
	ajax.waitId.orgdisplay = ajax.waitId.style.display;
	ajax.waitId.style.display = '';
	ajax.waitId.innerHTML = ajax.loading;
	var waitId = ajax.waitId.id;
	var that = ajax;
	ajax.get = function(url, recall) {
		var script = document.createElement("script");
	       	script.src = url;
		if(!is_ie) {
			script.onload = function() {
			       (function(){
			       		var json_return2 = unhtmlspecialchars(json_return);
			       		evalscript(json_return2);
			       		json_return2 = parsexml(json_return2);
					recall(json_return2, that);
					if(waitId == 'ajax_default_waitid') {
						$(waitId).style.display = 'none';
			     		}
			     		if(json_return2.message)evalscript(json_return2.message.text, true);
			     	})();
			}
		} else {
			// 闭包函数可以用到caller的局部变量（最后的状态）
			script.onreadystatechange = function() {
				// 创建匿名函数保存当前状态的值
				(function(){
					//var b = a;
					if(script.readyState=='complete'||script.readyState== 'loaded') {
						// 需要定义一个局部变量，防止重复点击，导致错误。
						var json_return2 = unhtmlspecialchars(json_return);
						evalscript(json_return2);
						json_return2 = parsexml(json_return2);
						recall(json_return2, that);
				 		if(waitId == 'ajax_default_waitid') {
							$(waitId).style.display = 'none';
				     		}
				     		// IE 需要延迟
				     		setTimeout(function(){evalscript(json_return2.message.text, true)}, 100);
					}
				})();
			}

		}
	   	document.getElementsByTagName('head')[0].appendChild(script);
	}
	return ajax;
}

function show(id, display) {
	if(!$(id)) return false;
	if(display == 'auto') {
		$(id).style.display = $(id).style.display == '' ? 'none' : '';
	} else {
		$(id).style.display = display;
	}
}

function ajaxget(url, showId, waitId, display, recall) {
	try {
		var e = is_ie ? event : (ajaxget.caller == null ? null : ajaxget.caller.arguments[0]);
	} catch(error) {
		var e = null;
		//alert('ajaxget() ajaxget.caller.arguments: '+error.message);
	}
	ajaxget2(e, url, showId, waitId, display, recall);
}

function ajaxget2(e, url, showId, waitId, display, recall) {

	var target = e ? (is_ie ? e.srcElement : e.target) : null;
	var display = display ? display : '';
	var x = new Ajax(waitId);
	x.waitId = waitId;
	x.showId = showId;
	x.display = display;
	var sep = url.indexOf('?') != -1 ? '&' : '?';
	x.target = target;
	x.recall = recall;
	x.get(url+sep+'inajax=1', function(s, x) {

		if(x.display == 'auto' && x.target) {
			x.target.onclick = function() {
				show(x.showId, 'auto');
			}
		}
		if(x.showId) {
			//alert(s.message.text+':'+x.showId+':display='+x.display);
			show(x.showId, x.display);// tbody
			show(x.showId+'tbody', x.display);// tbody
			if(s && s.message)$(x.showId).innerHTML = s.message.text;
		}
		if(x.recall) {
			x.recall(s);
		}
	});
	_cancelBubble(e);
}

function stripscript(s) {
	return s.replace(/<script.*?>.*?<\/script>/ig, '');
}

var evalscripts = new Array();
function evalscript(s, later) {
	if(typeof s == 'undefined') return '';
	if(!s || typeof s == 'number' || s.indexOf('<script') == -1) return s;
	var p = /<script[^>]*?src="([^\x00]+?)"[^>]*( reload="1")?><\/script>/ig;
	var arr = new Array();
	while(arr = p.exec(s)) appendscript(arr[1], '', arr[2]);
	p = /<script([^>]*?)>([^\x00]+?)<\/script>/ig;
	while(arr = p.exec(s)) {
		var reloadflag = arr[1].indexOf('reload="1"');
		var laterflag = arr[1].indexOf('later="1"');
		if(!later && !laterflag || later && laterflag)appendscript('', arr[2], reloadflag);
	}
	return s;
}

function appendscript(src, text, reload) {
	var id = hash(src + text);
	if(!reload && in_array(id, evalscripts)) return;
	if(reload && $(id)) {
		$(id).parentNode.removeChild($(id));
	}
	evalscripts.push(id);
	var scriptNode = document.createElement("script");
	scriptNode.type = "text/javascript";
	scriptNode.id = id;
	if(src) {
		scriptNode.src = src;
	} else if(text){
		scriptNode.text = text;
	}
	$('append').appendChild(scriptNode);
}

// 得到一个定长的 hash 值， 依赖于 stringxor()
function hash(string, length) {
	var length = length ? length : 32;
	var start = 0;
	var i = 0;
	var result = '';
	filllen = length - string.length % length;
	for(i = 0; i < filllen; i++){
		string += "0";
	}
	while(start < string.length) {
		result = stringxor(result, string.substr(start, length));
		start += length;
	}
	return result;
}

//note 将两个字符串进行异或运算，结果为英文字符组合
function stringxor(s1, s2) {
	var s = '';
	var hash = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var max = Math.max(s1.length, s2.length);
	for(var i=0; i<max; i++) {
		var k = s1.charCodeAt(i) ^ s2.charCodeAt(i);
		s += hash.charAt(k % 52);
	}
	return s;
}

function in_array(needle, haystack) {
	for(var i in haystack) 	{if(haystack[i] == needle) return true;}
	return false;
}

var currmenuid = null;
// attr 窗口属性 {confirm:recall,cose:yes}
function ajaxmenu(url, position, timeout, recall, attr) {
	// 判断层是否存在。
	e = is_ie ? event : (ajaxmenu.caller ? ajaxmenu.caller.arguments[0] : null);
	controlid = e == null ? null : (is_ie ? e.srcElement : e.target);

	var menuid = hash(url);// 使每个 url 对应一个弹出层，避免重复请求
	currmenuid = menuid;
	//if(!$(menuid)) {
		createmenu(menuid, attr);
	//}
	menubodyid = menuid + 'body';
	showmenu2(e, menuid, position, controlid, timeout);
	// 与服务端有个约定， id="message" 字样表示是提示信息//已经废弃改规则。
	var p = /id=\"?message\"?/;

	if(!recall) {
		recall = function() {setposition(menuid, position, controlid);}
	}

	if(!$(menubodyid).innerHTML || p.test($(menubodyid).innerHTML)) {
		var clientrecall = '';
		var recallhref = controlid ? (is_ie ? controlid.href : controlid.getAttribute('href')) : '';
		var s = window.location.toString();
		if(recallhref && recallhref != '' && recallhref != s.replace(/^(http:\/\/[^\/]+?\/).*$/ig, "$1")) {
			clientrecall = escape(recallhref);
		}

		url = url + (url.indexOf('?') == -1 ? '?' : '&')+'menuid='+menuid+'&clientrecall='+clientrecall;// 通过 URL 传递 menuid
		if(controlid && !controlid.id) {
			controlid.id = Math.random();
		}

		ajaxget2(e, url, menubodyid, menubodyid, '', recall);
	} else {

	}
	_cancelBubble(e);
}

function ajaxconfirm(url, recall) {
	ajaxmenu(url, 1, 0, null, {confirm:recall});
}

function ajaxpost(formid, showid, recall) {
	var ajaxframeid = 'ajaxframe' + formid;
	var ajaxframe = $(ajaxframeid);

	if(ajaxframe == null) {
		if (is_ie) {
			ajaxframe = document.createElement("<iframe name='" + ajaxframeid + "' id='" + ajaxframeid + "'></iframe>");
		} else {
			ajaxframe = document.createElement("iframe");
			ajaxframe.name = ajaxframeid;
			ajaxframe.id = ajaxframeid;
		}
		ajaxframe.style.display = 'none';
		$('append').appendChild(ajaxframe);
	}

	// 判断是否跨域
	if($(formid).action.indexOf('inajax') == -1) {
		$(formid).action += ($(formid).action.indexOf('?') != -1 ? '&' : '?') + 'inajax=1';
	}
	var formdomain = get_domain($(formid).action);
	if(formdomain[0] != document.domain) {
		$(formid).action = $(formid).action.replace(/inajax=1/, "inajax=2");
	}

	$(formid).target = ajaxframeid;
	// 默认的回调函数

	function ajaxpost_onload() {

		//var s = (is_ie && $(ajaxframeid)) ? $(ajaxframeid).contentWindow.document.XMLDocument.text : $(ajaxframeid).contentWindow.document.documentElement.firstChild.nodeValue;
		var s = is_ie ? $(ajaxframeid).contentWindow.document.body.innerHTML : $(ajaxframeid).contentWindow.document.body.textContent;
		s = unhtmlspecialchars(s);
		eval(s);
		s = json_return;
		if(s) {
			evalscript(s);
			// 必须去除 <script> 标签和里面内容

			s = stripscript(s);
			s = parsexml(s);
			var menuid = showid ? showid.substring(0, showid.length - 4) : '';
			if(recall) {
				recall(s);
			} else {
				if($(showid) && s.message)$(showid).innerHTML = s.message.text;
				setposition(menuid, 1);
				hidemenu('', 2);
			}
		} else {
			alert('服务端返回的数据为空。');
			//setTimeout("hidemenu();", 2000);
		}
	}
	_attachEvent(ajaxframe, 'load', ajaxpost_onload, ajaxframe.id);
	$(formid).submit();
}


//-----------------------------> menu.js
var Menus = new Array();
Menus['active'] = null;
Menus['timeout'] = new Object();
/**
	menuid: 菜单 id
	position: 默认为 0 相对链接，1 绝对居中，2 位置不变(自定义层位置时)
*/
function showmenu(menuid, position, timeout) {
	e = is_ie ? event : showmenu.caller.arguments[0];
	controlid = is_ie ? e.srcElement : e.target;
	showmenu2(e, menuid, position, controlid, timeout);
}

/**
	event: 事件
	controlid: 可选参数，不填时，表示当前鼠标事件点击的元素，通常就是 A
*/
function showmenu2(e, menuid, position, controlid, timeout) {
	hidemenu();
	position = position ? position : 0;
	$(menuid).style.display = 'block';// 只有 display 显示后，div 才会有 clientHeight clientWidth 等属性
	if($(menuid).className.indexOf('menu') == -1) $(menuid).className += ' menu';
	setposition(menuid, position, controlid);
	Menus['active'] = $(menuid);
	_cancelBubble(e);
	document.onkeypress = function (e) {
		e = e ? e : window.event;
		if (e && ((e.keyCode ? e.keyCode : e.charCode) == 27)) {
			hidemenu();
		}
	}

}

function setposition(menuid, position, controlid) {
	var menuid = $(menuid);
	if(!menuid) return;
	// 相对定位
	if(position == 0) {
		var controlpos = getposition(controlid);
		menuid.style.left = controlpos['x'] + 'px';
		menuid.style.top = controlpos['y'] + controlid.offsetHeight + 'px';
		menuid.style.marginLeft = '0px';
		menuid.style.marginTop = '0px';
	// 绝对居中定位
	} else if(position == 1 || position == 2) {
		menuid.style.top = '50%';
		menuid.style.left = '50%';
		var scrolltop = parseInt(document.documentElement.scrollTop) - (position == 1 ? 50 : 0);
		menuid.style.marginLeft = '-' + parseFloat(menuid.offsetWidth / 2) + 'px';
		menuid.style.marginTop = scrolltop - parseFloat(menuid.offsetHeight / 2) + 'px';
	}
}

/**
	只是创建层和关闭按钮，层的位置和显示由 showmenu() 来完成。
*/
function createmenu(id, attr) {
	if($(id)) {
		// 在IE下，删除节点的时候，必须先清空innerHTML
		$(id).innerHTML = '';
		$(id).parentNode.removeChild($(id));
	}
	//if($(id)) return;
	var div = document.createElement('DIV');
	div.className = 'menu';

	div.onclick = function(e) {_cancelBubble(e ? e : event, true);}
	div.id = id;
	div.innerHTML = '<div style="border:1px solid '+COLOR5+'; background:'+COLOR1+'; padding: 10px; margin:10px;" id="'+id+'border"><div id="'+id+'body"></div></div>';
	$('append').appendChild(div);

	if(attr && attr.confirm) {
		s = '<center><input type="button" id="'+id+'confirm" value=" 确 定 " />　';
		s += '<input type="button" id="'+id+'close" value=" 关 闭 " onclick="hidemenu(\''+id+'\')" /></center>';
		$(id+'border').innerHTML += s;
		$(id+'confirm').onclick = attr.confirm;
	}

	return id;
}

function hidemenu(menuid, timeout) {
	if(menuid && $(menuid)) {
		var id = menuid;
	} else if(Menus['active'] != null && Menus['active'] && Menus['active'].style) {
		var id = Menus['active'].id;
	} else {
		return;
	}
	if(timeout > 0) {
		Menus['timeout'][id] = setTimeout("$('"+id+"').style.display='none';", timeout * 1000);
	} else {
		$(id).style.display = 'none';
	}
}

function parsexml_childnodes(oNode) {
	var newNode = new Object();//oNode为只读属性，所以只能产生一个新的对象来存贮数据
	if(oNode.childNodes) {
		for(var i=0; i<oNode.childNodes.length; i++) {
			if(oNode.childNodes[i].nodeName) {
				newNode[oNode.childNodes[i].nodeName] = oNode.childNodes[i];
				if(is_moz) newNode[oNode.childNodes[i].nodeName].text = newNode[oNode.childNodes[i].nodeName].textContent;
			}
		}
	}
	return newNode;
}

function parsexml(xmlString) {
	if(is_ie) {
		doc = new ActiveXObject("Microsoft.XMLDOM")
		doc.async="false"
		doc.loadXML(xmlString)
	} else {
		var parser = new DOMParser()
		doc = parser.parseFromString(xmlString, "text/xml")
	}
	var newNode = parsexml_childnodes(doc.firstChild);
	return newNode;
}

_attachEvent(document, 'click', hidemenu);

function loginrecall(menuid) {
	return function(s) {
		if(!s.error) {
			if(s.clientrecall && s.clientrecall.text != '') {
				ajaxmenu(s.clientrecall.text, 1);
				$('navuser').innerHTML = s.navuser.text;
			} else {
				window.location.reload();
			}
			/*
			if(s.clientrecall && s.clientrecall.text != '') {
				ajaxmenu(s.clientrecall.text, 1);
			} else {
				hidemenu(menuid, 2);
			}
			*/
		} else {
			alert(s.message.text);
			$('username').focus();
		}
	}
}

function checkall(o, name) {
	var inputs = document.getElementsByTagName("INPUT");
	var checked = o.checked;
	var len = inputs.length;
	var reg = new RegExp("^"+name, 'i');
	for(var i=0; i<len; i++) {
		if(inputs[i].type=='checkbox' && reg.test(inputs[i].name)) {
			inputs[i].checked = checked;
		}
	}
}


/*window.onerror = function(Msg,Url,Num) {
	alert('window.onerror:'+Msg+Url+Num);
}*/

//
//window.onload = function() {
//	ajaxconfirm('http://www.struct.com/user-login.htm', function(){alert(123)});
//}

