﻿/*******************************************************************************
* 程序 : FreeContex Javascript扩展函数库
* 作者 : Alan
* 网站 : www.FreeContex.com
* 更新 : 2008/08
* 备注 : 
*******************************************************************************/

//删除首尾空格
String.prototype.trim = function()
{
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

//返回字节数
String.prototype.len = function()
{
	return this.replace(/[^\x00-\xff]/g,"**").length;
}

//执行正则验证
String.prototype.test = function(pattern,flag)
{
	if (!flag) flag = 'i';
	var reg = new RegExp(pattern,flag) ;
	return reg.test(this);
}

//邮件地址验证
String.prototype.isMail = function()
{
	var pattern = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9-]+([.][a-zA-Z0-9]+){1,3}$/;
	return pattern.test(this);
}

//IP地址验证
String.prototype.isIP = function()
{
	var pattern = /^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$/;
	return pattern.test(this);
}

//住宅电话验证
String.prototype.isPhone = function()
{
	var pattern = /^0[0-9]{2,3}\-[0-9]{7,8}$/;
	return pattern.test(this);
}

//手机号码验证
String.prototype.isMPhone = function()
{
	var pattern = /^1[0-9]{10}$/;
	return pattern.test(this);
}

//邮政编码验证
String.prototype.isPostCode = function()
{
	var pattern = /^[0-9]{6}$/;
	return pattern.test(this);
}

//QQ号码验证
String.prototype.isQQ = function()
{
	var pattern = /^[1-9][0-9]{4,9}$|^[a-zA-Z0-9_-]+@[a-zA-Z0-9-]+([.][a-zA-Z0-9]+)+$/;
	return pattern.test(this);
}

//数字检测
String.prototype.isNumeric = function()
{
	var pattern = /^[0-9]+$/;
	return pattern.test(this);
}

//返回元素在数组中的索引
Array.prototype.index = function(v)
{
	for (var i=0; i<this.length; i++)
	{
		if (this[i] === v) return i;
	}
	return -1;
}

//检查在数组内是否存在某值
Array.prototype.isOwn = function(v)
{
	for (var i=0; i<=this.length; i++)
	{
		if (this[i] === v) return true;
	}
	return false;
}

//从数组中移除指定元素
Array.prototype.remove = function(v)
{
	var arr = new Array();
	for(var i=0; i<=this.length; i++)
	{
		if(this[i] !== v) arr.push(v);
	}
	return arr;
}

//返回文件名
function getFileName(url)
{
	var strUrl = location.href;
	if (url || url=='') strUrl = url;
	var arrUrl = strUrl.split('/');
	var strName = arrUrl[arrUrl.length-1];
	if (strName.indexOf('?') != -1)
	{
		arrUrl = strName.split('?');
		strName = arrUrl[0];
	}
	return strName;
}

//返回文件后缀
function getFileExt(url)
{
	var strUrl = location.href;
	if (url || url=='') strUrl = url;
	var arrUrl = strUrl.split('.');
	var strExt = arrUrl[arrUrl.length-1];
	if (strExt.indexOf('?') != -1)
	{
		arrUrl = strExt.split('?');
		strExt = arrUrl[0];
	}
	return strExt;
}

//返回URL参数值
function getQuery(query)
{
	var strUrl = location.href;
	var strQ = '';
	if (strUrl.indexOf('?') != -1)
	{
		var arrUrl = strUrl.split('?');
		//alert(arrUrl.length);
		var strQuery = arrUrl[arrUrl.length-1];
		var arrQuery = strQuery.split('&');
		for (var i=0; i<arrQuery.length; i++)
		{
			var arr = arrQuery[i].split('=');
			//alert(arr.length);
			if (arr.length==1)arr.push('');
			if (arr[0]==query){strQ=arr[1]; break;}
		}
	}
	return strQ;
}

//返回指定格式的当前系统时间
function getTimeNow(format)
{
	var str = format; var now = new Date();
	var y = now.getFullYear(); var m = now.getMonth()+1;
	var d = now.getDate(); var h = now.getHours();
	var i = now.getMinutes(); var s = now.getSeconds();
	if (format.indexOf('yy') != -1) str = str.replace('yy',y.toString().substr(y.toString().length-2));
	if (format.indexOf('y') != -1) str = str.replace('y',y);
	if (format.indexOf('mm') != -1) str = str.replace('mm',('0'+m).substr(m.toString().length-1));
	if (format.indexOf('m') != -1) str = str.replace('m',m);
	if (format.indexOf('dd') != -1) str = str.replace('dd',('0'+d).substr(d.toString().length-1));
	if (format.indexOf('d') != -1) str = str.replace('d',d);
	if (format.indexOf('h') != -1) str = str.replace('h',('0'+h).substr(h.toString().length-1));
	if (format.indexOf('h') != -1) str = str.replace('h',h);
	if (format.indexOf('ii') != -1) str = str.replace('ii',('0'+i).substr(i.toString().length-1));
	if (format.indexOf('i') != -1) str = str.replace('i',i);
	if (format.indexOf('ss') != -1) str = str.replace('ss',('0'+s).substr(s.toString().length-1));
	if (format.indexOf('s') != -1) str = str.replace('s',s);
	return str;
}

//全选/全不选/反选
function selectAll(mode,name)
{
	var elems = $N(name);
	for(i=0; i<elems.length; i++)
	{
		if (elems[i].disabled) continue;
		switch (mode)
		{
		case 1://全选
			elems[i].checked = true;
			break;
		case 0://全不选
			elems[i].checked = false;
			break;
		case -1://反选
			elems[i].checked = !elems[i].checked;
			break;
		}
	}
	return false;
}

//按要求选中下拉框
function setSelect(obj,model,value)
{
	if( model == 'text' ){
		for( var i=0; i<obj.length; i++ )
			if( obj.options[i].text == value ){
				obj.selectedIndex = i;
				return;
			}
	}else if( model == 'value' ){
		for( var i=0; i<obj.length; i++ )
			if( obj.options[i].value == value ){
				obj.selectedIndex = i;
				return;
			}
	}
}

//重新加载当前页面
function redirect(url)
{
	if (url)
	{
		window.location.href = url;
	}
	else
	{
		window.location.href = window.location.href;
	}
}

//添加页面载入事件
function addLoadEvent(func)
{
	if (typeof func == 'string')
	{
		eval('func = function(){'+func+';}');
	}
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload(); func();
		}
	}
}

//动态加载脚本
function loadScript(src,parent)
{
	var root = parent ? document.getElementById(parent) : document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = src;
	root.appendChild(script);
}

//装载编辑器
function loadEditor(arg)
{
	KE.show
	({
		id               : arg.id,
		resizeMode       : typeof arg.resizeMode != 'undefined' ? arg.resizeMode : 1,
		urlType          : typeof arg.urlType != 'undefined' ? arg.urlType : 'absolute',
		newlineTag       : typeof arg.newlineTag != 'undefined' ? arg.newlineTag : 'p',
		items            : typeof arg.items != 'undefined' ? arg.items : [
							'source', '|', 'fullscreen', 'undo', 'redo', 'print', 'cut', 'copy', 'paste',
							'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
							'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent',
							'subscript', 'superscript', '-',
							'coder', 'title', 'fontname', 'fontsize', '|', 'textcolor', 'bgcolor', 'bold',
							'italic', 'underline', 'strikethrough', 'removeformat', '|', 'image',
							'flash', 'media', 'table', 'hr', 'emoticons', 'link', 'unlink', 'about'],
		allowUpload      : false,
		allowFileManager : true,
		fileManagerJson  : KE.scriptPath + '../kindjson'
	});
}

//等比缩图(批量)
function imageLimit(parent, width, height)
{
	if ((!width) && (!height)) return;
	
	$('#'+parent+' img').each(function()
	{
		if (width && this.width>width)
		//限宽
		{
			this.style.width  = width + 'px';
			this.style.height = '';
		}
		else if (height && this.height>height)
		//限高
		{
			this.style.width  = '';
			this.style.height = height + 'px';
		}
	});
}

//等比缩图并适应容器(单个)
function imageLayout(image, src, width, height)
{
	if ((!width) && (!height)) return;
	
	var _image = new Image;
	_image.onload = function()
	{
		if (typeof image == 'string') image = $I(image);
		image.style.display = 'none';
		
		var h = _image.height;
		var w = _image.width;
		if (!height) height = h;
		if (!width) width = w;
		if (w/h > width/height)
		{
			if (w > width)
			{
				image.style.width      = width + 'px';
				image.style.marginTop  = (height-width*h/w)/2 + 'px';
			}
			else
			{
				image.style.marginLeft = (width-w)/2 + 'px';
				image.style.marginTop  = (height-h)/2 + 'px';
			}
		}
		else
		{
			if (h > height)
			{
				image.style.height     = height + 'px';
				image.style.marginLeft  = (width-height*w/h)/2 + 'px';
			}
			else
			{
				image.style.marginLeft = (width-w)/2 + 'px';
				image.style.marginTop  = (height-h)/2 + 'px';
			}
		}
		
		image.src = src;
		$(image).slideDown(300);
	};
	_image.src = src;
}

//显示loading提示
function loading(show,message,seconds,callback)
{
	function loadingHide()
	{
		var layer = window.top.$('#loading');
		if (layer) layer.fadeOut(300,function()
		{
			if (callback)
			{
				if (typeof callback == 'string')
				{
					try {eval(callback)} catch (e){};
				}
				else if (typeof callback == 'function') callback();
			}
		});
	}
	
	if ( show && !message ) var message = '正在与服务器通信...';
	if ( show )
	{
		var layer = window.top.$I('loading');
		if ( layer ) layer.style.display = 'block';
		else
		{
			layer = document.createElement('DIV');
			layer.id = 'loading';
			window.top.document.body.appendChild(layer);
		}
		layer.innerHTML = message;
		if ( typeof(seconds) == 'number' && callback)
		{
			window.top.window.setTimeout(loadingHide,seconds);
		}
	}
	else
	{
		var layer = window.top.$I('loading');
		if (layer && message) layer.innerHTML = message;
		if ( typeof(seconds) == 'number' )
		{
			window.top.window.setTimeout(loadingHide,seconds);
		}
		else loadingHide();
	}
}

//异步POST请求
function post(url,data,message,callback)
{
	if (!message) message = [null,null,0];
	else if (typeof message == 'string') message = [message,null,0];
	else if (typeof message == 'object' && !message[2]) message[2] = 0;
	$.ajax
	({
		type       : 'post',
		url        : url.replace('?','/default.asp?'),
		cache      : false,
		dataType   : 'text',
		data       : data,
		timeout    : 20000,
		beforeSend : function(XMLHttpRequest)
		{
			loading(true,message[0]);
			$(':button').each(function(){this.disabled=true;});
			$(':submit').each(function(){this.disabled=true;});
		},
		success: function(text)
		{
			var a = text ? text.split('|') : ['无效的服务器响应。'];
			if( a[0] == 'YES' )
			{
				if (typeof callback == 'function')
				{
					loading(false,message[1],message[2],function(){callback(a[1])});
				}
				else loading(false,message[1],message[2],callback);
			}
			else if ( a[0] == 'ERR' )
			{
				if (a[1]) alert(a[1]);
				if (a[2])
				{
					try {if (a[2]) $I(a[2]).focus();} catch (e){};
				}
				loading(false);
			}
			else
			{
				alert(a[0]);
				loading(false);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert('请求超时，请重试。');
			loading(false);
		},
		complete: function(XMLHttpRequest)
		{
			$(':button').each(function(){this.disabled=false;});
			$(':submit').each(function(){this.disabled=false;});
		}
	});
}

//异步GET请求
function get(url,message,callback)
{
	if (!message) message = [null,null,0];
	else if (typeof message == 'string') message = [message,null,0];
	else if (typeof message == 'object' && !message[2]) message[2] = 0;
	$.ajax
	({
		type       : 'get',
		url        : url,
		cache      : false,
		dataType   : 'text',
		timeout    : 20000,
		beforeSend : function(XMLHttpRequest)
		{
			loading(true,message[0]);
			$(':button').each(function(){this.disabled=true;});
			$(':submit').each(function(){this.disabled=true;});
		},
		success: function(text)
		{
			var a = text ? text.split('|') : ['无效的服务器响应。'];
			if( a[0] == 'YES' )
			{
				if (typeof callback == 'function')
				{
					loading(false,message[1],message[2],function(){callback(a[1])});
				}
				else loading(false,message[1],message[2],callback);
			}
			else if ( a[0] == 'ERR' )
			{
				if (a[1]) alert(a[1]);
				if (a[2])
				{
					try {if (a[2]) $I(a[2]).focus();} catch (e){};
				}
				loading(false);
			}
			else
			{
				alert(a[0]);
				loading(false);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown)
		{
			alert('请求超时，请重试。');
			loading(false);
		},
		complete: function(XMLHttpRequest)
		{
			$(':button').each(function(){this.disabled=false;});
			$(':submit').each(function(){this.disabled=false;});
		}
	});
}

//返回具有相同class名称的一组对象
document.getElementsByClassName = function(className, tagName, parent)
{
	var elems;
	if (parent && typeof(parent) == 'string' && tagName) elems = document.getElementById(parent).getElementsByTagName(tagName);
	else if (parent && typeof(parent) == 'object' && tagName) elems = parent.getElementsByTagName(tagName);
	else if (tagName) elems = document.getElementsByTagName(tagName);
	else elems = document.getElementsByTagName("*");
	var result=[];
	for (i=0; j=elems[i]; i++)
	{
	  if ((" "+j.className+" ").indexOf(" "+className+" ")!=-1) result.push(j);
	}
	return result;
}

//控制滚动条滚动JQuery插件
if (jQuery)
{
	jQuery.fn.scrollTo = function(speed)
	{
		var targetOffset = $(this).offset().top;
		$('html,body').stop().animate({scrollTop: targetOffset}, speed);
		return this;
	};
}

//简化调用(parent tagName是为提高运行效率而设置的可选参数)
function $I(id){return document.getElementById(id);}
function $N(name,parent){var parent = parent||document; if (typeof(parent)=='string')parent=document.getElementById(parent); return parent.getElementsByName(name);}
function $T(tagName,parent){var parent = parent||document; if (typeof(parent)=='string')parent=document.getElementById(parent); return parent.getElementsByTagName(tagName);}
function $C(className,tagName,parent){return document.getElementsByClassName(className,tagName,parent);}
