// 本js在jquery后加载
var charset = document.charset;
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);
var is_chrome = userAgent.indexOf('chrome') != -1 && userAgent.substr(userAgent.indexOf('chrome') + 7, 3);
var is_safari = userAgent.indexOf('safari') != -1 && userAgent.substr(userAgent.indexOf('safari') + 7, 3);
var ajaxPostGlobal = 0;

//处理斜杠
if(siteurl.substr(siteurl.length -1 , 1) != '/') {
	siteurl += '/';
}

var GLOBAL = new Array();
GLOBAL['js'] = new Array();
GLOBAL['css'] = new Array();
GLOBAL['js_root'] = 'include/javascript/';
GLOBAL['css_root'] = 'templates/main/default/';
GLOBAL['url'] = siteurl;
GLOBAL['mod'] = typeof(mod) == 'undefined' ? null : mod;

// 去空格
String.prototype.trim = function() {  
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

// 数组搜索
Array.prototype.indexof = function(value) {
	for (var i in this) {
		if(i==value) return this[i];
	}
	return null;
}

//动态载入JS文件
function loadscript(filename) {
	if(filename == '') return;
	if(filename.indexOf(',') > 0) {
		var files = filename.split(',');
		if(typeof(files) != null && files.length > 0) {
			for (var i=0; i<files.length; i++) {
				loadscript(files[i]);
			}
		}
	} else {
		var file = filename + '.js';
		if(typeof(arguments[1]) == 'string' && arguments[1] != '') {
			var src = arguments[1] + file;
		} else {
			var src = getUrl() + GLOBAL['js_root'] + file;
		}
		if(GLOBAL['js'].indexof(file)!= null) return;
		var j = document.createElement("script");
		j.setAttribute("type", "text/javascript");
		j.setAttribute("src", src);
		document.getElementsByTagName("head")[0].appendChild(j);
		/*
		$("<script></script>").attr({ type:"text/javascript", src:src }).appendTo(document.body);
		*/
		GLOBAL['js'][file] = 1;
	}
}

//动态载入CSS文件
function loadcss(filename) {
	if(filename=='') return;
	if(filename.indexOf(',') > 0) {
		var files = filename.split(',');
		if(typeof(files) != null && files.length > 0) {
			for (var i=0; i<files.length; i++) {
				loadcss(files[i]);
			}
		}
	} else {
		var file = filename + '.css';
		if(typeof(arguments[1]) == 'string' && arguments[1] != '') {
			var src = arguments[1] + file;
		} else {
			var src = getUrl() + GLOBAL['css_root'] + file;
		}
		if(GLOBAL['css'].indexof(src)!= null) return;
		var c = document.createElement("link");
		c.setAttribute("rel", "stylesheet");
		c.setAttribute("type", "text/css");
		c.setAttribute("href", src);
		document.getElementsByTagName("head")[0].appendChild(c);
		/*
		$("<link></link>").attr({rel:"stylesheet", type:"text/css", href:src}).appendTo(document.head);
		*/
		GLOBAL['css'][file] = 1;
	}
}

//获取相对路径
function getUrl() {
	if(arguments.length == 0) {
		return typeof(mod)=='undefined' ? '' : '../';
	}

	var flag = arguments[0];
	if(flag=='modoer') return siteurl;
	var crmod = modules[flag];
	var url = '';
	if(typeof(mod)=='undefined' && typeof(crmod)=='undefined') {
		 url = '';
	} else if(typeof(mod)=='undefined' && crmod) {
		url = crmod['directory'] + '/';
	} else if(mod && typeof(crmod)=='undefined') {
		url = '../';
	} else if(mod['flag'] != crmod['flag']) {
		url = '../' + crmod['directory'] + '/';
	} else if(mod['flag'] == crmod['flag']) {
		url = '';
	}

	if(typeof(arguments[1])=='string') {
		url	+= arguments[1];
	}

	var param = arguments[2];
	var type = typeof(param);
	if(type=='object') {
		var split = '?';
		for (var i=0; i<param.length; i++) {
			url += split + param[i];
			split = '&';
		}
	} else if(type=='string') {
		url += '?' + param;
	}

	if(typeof(arguments[3])=='string') {
		url += '#' + arguments[3];
	}
	return url;
}

// 判断是否为数字
function is_numeric(str) {
	var patn = /^[0-9-\/]+$/;
	if(!patn.test(str)) return false;
	return true;
}

//判断E-mail格式是否正确
function is_email(str) {
	var patn = /^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;
	if(!patn.test(str))	return false;
	return true;
}

//取随机值
function getRandom() {
	return Math.floor(Math.random()*1000+1);
}

//字符串长度
function mb_strlen(str) {
	var len = 0;
	for(var i = 0; i < str.length; i++) {
		len += str.charCodeAt(i) < 0 || str.charCodeAt(i) > 255 ? (document.charset == 'utf-8' ? 3 : 2) : 1;
	}
	return len;
}

// 提示对话框
function myAlert(data, width, height) {
	var mymsg = eval('('+data+')'); //JSON转换
	if(mymsg.extra == 'login') {
		if(window.confirm(mymsg.caption+'，需要“登录”后才能继续。点击“确定”，登录网站。')) {
			window.location.href = mymsg.url;
		}
	} else if(mymsg.extra == 'mdialog') {
		if (!width) {
			width = 400;
		}
		if (!height) {
			height = 300;
		}
		dlgOpen(mymsg.caption, mymsg.message.replace("{LF}","\r\n"), width, height, true);
	} else {
		alert(mymsg.message);
	}
}

//向目标加入TAG（感谢eonbell测试）
function addtag(Id, tag) {
	var str = $("#"+Id).val();
	if ((" "+str+" ").indexOf(" "+tag+" ") == -1) {
		str += str ? ' ' + tag : tag;
		$("#"+Id).val(str);
	}
}

//增加行数(textarea)
function addrows(obj, num) {
	obj.rows += num;
}

//减少行数
function decrows(obj, num) {
	if (obj.rows>num) {
		obj.rows -= num;
	}
}

//checkbox反选
function allchecked() { 
	var check = document.getElementsByTagName('input');
	for (var i=0; i<check.length; i++) {
		if (check[i].type == 'checkbox' && !check[i].disabled) {
			check[i].checked = !check[i].checked;
		}
	}
}

//name相同的checkbox反选
function checkbox_checked(name) { 
	var check = document.getElementsByTagName('input');
	for (var i=0; i<check.length; i++) {
		if (check[i].type == 'checkbox' && check[i].name == name && !check[i].disabled) {
			check[i].checked = !check[i].checked;
		}
	}
}

//检测checkbox是否有选中
function checkbox_check() {
	var check = document.getElementsByTagName('input');
	if(typeof(arguments[0]) == 'string') {
		var	checkname = arguments[1];
	} else {
		var checkname = null;
	}
	var ischecked = false;
	for (var i=0; i<check.length; i++) {
		if (check[i].type == 'checkbox' && check[i].checked && !check[i].disabled) {
			ischecked = checkname == null || check[i].name == checkname;
		}
	}
	if (!ischecked)
		alert('请至少选择一项！');
	return ischecked;
}

//检测radio是否有选择
function checkradio(obj) {
	if(obj) {
		var check=obj.getElementsByTagName('input');
	} else {
		var check=document.getElementsByTagName('input');
	}
	var ischecked = false;
	for (var i=0; i<check.length; i++) {
		if (check[i].type == 'radio' && check[i].checked) {
			ischecked=true;
		}
	}
	return ischecked;
}

//取单选框radio的值
function getRadio(from,name) {
	if(from) {
		var radios = from.getElementsByTagName('input');
	} else {
		var radios = document.getElementsByTagName('input');
	}
	if(!radios) return;
	var value='';
	for (var i=0; i<radios.length; i++) {
		if (radios[i].type == 'radio' && radios[i].name == name && radios[i].checked) {
			value=radios[i].value;
			break;
		}
	}
	return value;
}

//显示验证码
function show_seccode() {
        var sec = $('#seccode').empty();
        var img = $('<img />')
                .css({weight:"80px", height:"25px", cursor:"pointer"})
                .attr("title",'点击更新验证码')
                .click(function() {
                        this.src= getUrl()+'seccode.php?x='+getRandom();
                });
        sec.append(img);
        img.click();
}

function checkUsernameLogin(username) {
	var usernameErrMsg = document.getElementById('usernameErrMsg');
	if (!username) {
		usernameErrMsg.style.display = 'inline';
		usernameErrMsg.innerHTML = '请输入用户名！';
		return false;
	} else {
		usernameErrMsg.style.display = 'none';
		usernameErrMsg.innerHTML = '';
		return true;
	}
}
function checkPasswordLogin() {
	var passwordErrMsg = document.getElementById('passwordErrMsg');
	var password = document.getElementById('password').value;
	if (!password) {
		passwordErrMsg.style.display = 'inline';
		passwordErrMsg.innerHTML = '请输入密码！';
		return false;
	} else {
		passwordErrMsg.style.display = 'none';
		passwordErrMsg.innerHTML = '';
		return true;
	}
}
function checkLogin() {
	var username = document.getElementById('username').value;
	if (!checkUsernameLogin(username)) {
		return false;
	}
	var password = document.getElementById('password').value;
	if (!checkUsernameLogin(username)) {
		return false;
	}
	return true;
}

function tot(mobnumber) {
	while(mobnumber.indexOf("０")!=-1){           
		mobnumber = mobnumber.replace("０","0");        
	}                       
	while(mobnumber.indexOf("１")!=-1){             
		mobnumber = mobnumber.replace("１","1");}       
	while(mobnumber.indexOf("２")!=-1){             
		mobnumber = mobnumber.replace("２","2");}       
	while(mobnumber.indexOf("３")!=-1){             
		mobnumber = mobnumber.replace("３","3");}       
	while(mobnumber.indexOf("４")!=-1){             
		mobnumber = mobnumber.replace("４","4");}       
	while(mobnumber.indexOf("５")!=-1){             
		mobnumber = mobnumber.replace("５","5");}       
	while(mobnumber.indexOf("６")!=-1){             
		mobnumber = mobnumber.replace("６","6");}       
	while(mobnumber.indexOf("７")!=-1){             
		mobnumber = mobnumber.replace("７","7");}       
	while(mobnumber.indexOf("８")!=-1){             
		mobnumber = mobnumber.replace("８","8");}       
	while(mobnumber.indexOf("９")!=-1){             
		mobnumber = mobnumber.replace("９","9");}       
	return mobnumber;       
}

function checkByteLength(str,minlen,maxlen) {
	if (str == null) return false;
	var l = str.length;
	var blen = 0;
	for(i=0; i<l; i++) {
		if ((str.charCodeAt(i) & 0xff00) != 0) {
			blen ++;
		}
		blen ++;
	}
	if (blen > maxlen || blen < minlen) {
		return false;
	}
	return true;
}

//var unlen = username.replace(/[^\x00-\xff]/g, "**").length;

function isEqual(objid1, objid2) {
	return objid1.value == objid1.value;
}

function tabSelect(showId,idpre) {
	for(i=1; i<=10; i++) {
        var tab = $("#"+idpre+i);
        if(!tab[0]) break;
		if (i==showId) { 
			$("#btn_"+idpre+i).attr("className","selected");
			$("#"+idpre+i).toggleClass("none");
			$("#"+idpre+i).css("display","");
		 } else {
			$("#btn_"+idpre+i).attr("className","unselected");
			$("#"+idpre+i).addClass("none");
			$("#"+idpre+i).css("display","none");
		}
	}
}

//操作选择
function selectOperation(select) {
    var url = select.options[select.selectedIndex].value;
    if(url) {
		var cfm = select.options[select.selectedIndex].getAttribute("cfm");
		select.selectedIndex = 0;
		if(cfm && confirm(cfm) || !cfm) {
			window.location = url;
		}
	}
	select.selectedIndex = 0;
}

function easy_submit(form_name,act_value,check_name) {
	submit_form(form_name, 'op', act_value, null, null, check_name);
}

//按钮式多类型操作
function submit_form(form_name, act_name, act_value, param_name, param_value, check_name) {
    var form = $("[@name="+form_name+"]");
    if(check_name != null) {
        if(!checkbox_check(check_name)) return;
    }

    if(act_value == 'delete') {
        if(!confirm('确定要进行删除操作吗？')) return;
    }

	if(form.find("[@name="+act_name+"]")[0] == null) {
		form.append("<input type=\"hidden\" name=\""+act_name+"\" />");
	}
	form.find("[@name="+act_name+"]").val(act_value);

	if(param_name != null || param_name != '') {
		form.find("[@name="+param_name+"]").val(param_value);
	}

    form.submit();
}

//Ajax提交
function ajaxPost(formid,myid,func) {
	if(ajaxPostGlobal != 0) {
		return false;
	}
	var iframeid = 'ajaxiframe';
	if($('#'+iframeid)[0] == null) {
		$(document.body).append('<iframe name="'+iframeid+'" id="'+iframeid+'"></iframe>');
	}
	var iframe = $('#'+iframeid);
	iframe.css("display","none");

	ajaxPostGlobal = [formid, iframeid, myid, func];

	var form = $("#" + formid);
	form.attr("target", iframeid);
	iframe.unbind();
	iframe.load(ajaxPostLoad);

	form.submit();
}

//ajax提交后返回
function ajaxPostLoad() {
	if(ajaxPostGlobal==0) return;
	var ajaxparam = ajaxPostGlobal;
	ajaxPostGlobal = 0;
	var iframe = document.getElementById(ajaxparam[1]);
	var data = $(iframe.contentWindow.document.body).html();
	dlgClose();
	myAlert(data);
	if(ajaxparam[3]) {
		setTimeout(ajaxparam[3]+'(\'' + ajaxparam[2] + '\');', 10);
	}
}

function set_cookie(name, value, expireDays) {
    name = cookiepre + name;
	var expires = new Date();
	if(!expireDays) expireDays = 1;
	expires.setTime(expires.getTime() + expireDays*24*3600*1000);
	var cookiestr = '';
	cookiestr = name + '=' + escape(value) + '; path=' + cookiepath;
	if(cookiedomain != '') {
		cookiestr += '; domain=' + cookiedomain;
	}
	cookiestr += '; expires=' + expires.toGMTString();
	document.cookie = cookiestr;
}

function get_cookieval(start) {
	var end = document.cookie.indexOf(";", start);
	if(end == -1) {
		end = document.cookie.length;
	}
	return unescape(document.cookie.substring(start, end));
}

function get_cookie(name) {
    name = cookiepre + name;
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while(i < clen) {
		var j = i + alen;
		if(document.cookie.substring(i, j) == arg) return get_cookieval(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if(i == 0) break;
	}
	return null;
}

function del_cookie(name) {
    var expires = new Date();
	expires.setTime (expires.getTime() - 1);
	var cval = get_cookie(name);
    name = cookiepre + name;
	document.cookie = name+"=" + cval + "; expires=" + expires.toGMTString();
}
