// autor lhb

/**
 * 根据id得到document对象
 * @param {} id
 * @return {}
 */
function $(id) {
	if(! id){
		return null;
	}
	if (id.tagName) {
		return id;
	}
	return document.getElementById(id);
}

/**
 * 浏览器类型
 * @type 
 */
var BrowserType = {
	IE : !!(window.attachEvent && !window.opera),
	Opera : !!window.opera,
	WebKit : navigator.userAgent.indexOf("AppleWebKit/") > -1,
	Gecko : navigator.userAgent.indexOf("Gecko") > -1
			&& navigator.userAgent.indexOf("KHTML") == -1,
	MobileSafari : !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
};

/**
 * 事件管理(添加，移除事件监听)
 * @type 
 */
var Event = Event;
if (!Event) {
	Event = {};
}
Event.stop = function(e) {
	if (!e) {
		return;
	}
	if (e.stopPropagation) {
		e.stopPropagation();
	} else {
		e.cancelBubble = true;
	}
	if (e.preventDefault) {
		e.preventDefault();
	} else {
		e.returnValue = false;
	}
};

/**
 * 添加事件监听器
 * @param {} target 目标元素
 * @param {} eventType 事件类型，如click事件则传字符串"click"
 * @param {} handler 事件处理函数
 */
Event.addListener = function(target, eventType, handler) {
	var length = arguments.length;
	var params = new Array();
	for (var index = 3; index < length; index++) {
		params.push(arguments[index]);
	}

	var proxyHandler = function(event) {
		handler(event, params);
	}
	handler.proxyHandler = proxyHandler;

	if (document.attachEvent) {
		target.attachEvent("on" + eventType, proxyHandler);
	} else {
		if (document.addEventListener) {
			target.addEventListener(eventType, proxyHandler, false);
		} else {
			target["on" + eventType] = proxyHandler;
		}
	}
};
/**
 * 移除事件监听
 * @param {} target 目标元素
 * @param {String} eventType 事件类型，如click事件则传字符串"click"
 * @param {} handler 事件监听者
 */
Event.removeListener = function(target, eventType, handler) {
	if (handler.proxyHandler) {
		handler = handler.proxyHandler;
	}
	if (document.detachEvent) {
		target.detachEvent("on" + eventType, handler);
	} else {
		if (document.removeEventListener) {
			target.removeEventListener(eventType, handler, false);
		} else {
			target["on" + eventType] = null;
		}
	}
};
/**
 * 得到事件源
 * @param {} event
 * @return {}
 */
Event.target = function(event) {
	if (event.srcElement) {
		return event.srcElement;
	} else {
		return event.target;
	}
};

/**
 * 工具类包括(ajax,字符串,数组等常用操作)
 * @type 
 */
var Util;
if (!Util) {
	Util = {};
}
Util.namespace = function() {
	var a = arguments, o = null, i, j, d;
	for (i = 0; i < a.length; i = i + 1) {
		d = a[i].split(".");
		o = Handson;

		// Handson is implied, so it is ignored if it is included
		for (j = (d[0] == "Terry") ? 1 : 0; j < d.length; j = j + 1) {
			o[d[j]] = o[d[j]] || {};
			o = o[d[j]];
		}
	}
	return o;
};

/**
 * ajax请求
 * @param {} method-POST/GET
 * @param {} url-requestUrl
 * @param {} postContent-params
 * @param {} callback-回调函数
 * @param {} isAsy-是否异步
 */
Util.request = function(method, url, postContent, callback, isAsy) {
	var xmlhttp;
	if (arguments.length<5) {
		isAsy = true;
	}
	if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		xmlhttp = new XMLHttpRequest();
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				if (callback.type == "plain") {
					callback.success(xmlhttp.responseText);
				} else {
					callback.success(xmlhttp.responseXML);
				}
			} else {
				if(callback.fail){
				   callback.fail();
				}else{
				   alert("系统正忙!请稍后再试!")
				}
			}
		}
	};
	if (method.toLowerCase() == "get") {
		xmlhttp.open("get", url + "?" + postContent, isAsy);
		xmlhttp.send(null);
	} else {
		xmlhttp.open("post", url, isAsy);
		xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlhttp.send(postContent);
	}
};

/**
 * 封装FORM-ajax方式提交
 * @param {} form-form对象
 * @param {} callback-回调函数
 * @param {} isAsy-是否异步
 */
Util.formRequest = function(form, callback, isAsy) {
	var method = form.method;
	var url = form.action;
	var content = Util.serializeForm(form);
	Util.request(method, url, content, callback, isAsy);
};

/**
 * 序列化FORM
 * @param {} form对象
 * @return String-form所有属性并拼接参数为url(?name=admin&password=123)
 */

Util.serializeForm = function(form) {
	var postContent = "";
	var elements = form.elements;
	for (var i = 0; i < elements.length; ++i) {
		var element = elements[i];
		if (element.name == "") {
			continue;
		}
		if (element.type == "text" || element.type == "textarea"
				|| element.type == "hidden") {
			postContent += encodeURIComponent(element.name) + "="
					+ encodeURIComponent(element.value) + "&";
			continue;
		}

		if (element.type == "select-one" || element.type == "select-multiple") {
			var options = element.options, j, item;
			for (j = 0; j < options.length; ++j) {
				item = options[j];
				if (item.selected) {
					postContent += encodeURIComponent(element.name) + "="
							+ encodeURIComponent(item.value) + "&";
				}
			}
			continue;
		}

		if (element.type == "checkbox" || element.type == "radio") {
			if (element.checked) {
				postContent += encodeURIComponent(element.name) + "="
						+ encodeURIComponent(element.value) + "&";
			}
			continue;
		}

		if (element.type == "file") {
			if (element.value != "") {
				postContent += encodeURIComponent(element.name) + "="
						+ encodeURIComponent(element.value) + "&";
			}
			continue;
		}
		postContent += encodeURIComponent(element.name) + "="
				+ encodeURIComponent(element.value) + "&";

	}
	return postContent;
};

/**
 * 得到文件后缀
 * @param {} fileName
 * @return {}
 */
Util.getFileExt = function(fileName){
	if(fileName.indexOf(".")!=-1){
       var ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length);
       return ext.toLowerCase();
	}else{
	   return "";
	}
}

/**
 * 根据文件名或文件后缀得到文件类型相关的图片
 * 注: 修改此函数同时修改com.Tools类中的此同名方法
 * @param {} temp
 * @return {String}
 */
Util.reStrReturnImg = function(temp) {
    try {
        var tempint = 0;
        var tempstr = "";
        if (temp==null||temp=="") {
            return "";
        } else {
            tempint = temp.lastIndexOf(".");
            if (tempint != -1) {                 
            	tempstr = temp.substring(tempint + 1, temp.length);
            }else{
                tempstr = temp;
            }
            
            if (tempstr.toLowerCase().indexOf("rar")!=-1 ||
                    tempstr.toLowerCase().indexOf("zip")!=-1 ||
                    tempstr.toLowerCase().indexOf("jar")!=-1) {
                return "rz.gif";
            } else if (tempstr.toLowerCase().indexOf("htm")!=-1 ||
                    tempstr.toLowerCase().indexOf("jsp") !=-1 ||
                    tempstr.toLowerCase().indexOf("asp")!=-1  ||
                    tempstr.toLowerCase().indexOf("php")!=-1 ) {
                return "htm.gif";
            } else if (tempstr.toLowerCase().indexOf("mp3")!=-1 
            		||tempstr.toLowerCase().indexOf("mid")!=-1 
                    ||tempstr.toLowerCase().indexOf("wma")!=-1) {
                return "mmm.gif";
            } else if (tempstr.toLowerCase().indexOf("rm")!=-1) {
                return "rm.gif";
            } else if (tempstr.toLowerCase().indexOf("mp4")!=-1 ||
                    tempstr.toLowerCase().indexOf("mpg")!=-1 ||
                    tempstr.toLowerCase().indexOf("avi")!=-1) {
                return "mp.gif";
            } else if (tempstr.toLowerCase().indexOf("jpg")!=-1 ||
                    tempstr.toLowerCase().indexOf("gif")!=-1 ||
                    tempstr.toLowerCase().indexOf("bmp")!=-1) {
                return "pic.gif";
            } else if (tempstr.toLowerCase().indexOf("ppt")!=-1) {
                return "ppt.gif";
            } else if (tempstr.toLowerCase().indexOf("txt")!=-1) {
                return "txt.gif";
            } else if (tempstr.toLowerCase().indexOf("doc")!=-1) {
                return "doc.gif";
            } else if (tempstr.toLowerCase().indexOf("xls")!=-1) {
                return "xls.gif";
            } else if (tempstr.toLowerCase().indexOf("exe")!=-1 ||
                    tempstr.toLowerCase().indexOf("bat")!=-1) {
                return "exe.gif";
            }else {
                return "unknow.gif";
            }
        }
    } catch (ex) {
        return "unknow.gif";
    }
}
/**
 * 得到radio 或者choice类型的元素的选中值
 * @param {} inputArray
 * @return {}
 */
Util.getChoiceValue = function(inputArray){
	var length = inputArray.length;
	var result = new Array();
	for(var index=0; index<length; index++){
		if(inputArray[index] && inputArray[index].checked){
			result.push(inputArray[index].value);
		}
	}
	if(result.length == 1){
		return result[0];
	}
	return result;
}

/**
 * 全选
 * @param {} elementsA-需要全选的document对象
 * @param {} elementsB-触发全选的document对象
 */
Util.selectAll = function(elementsA,elementsB){
    var len = elementsA;
	if(len.length > 0)
	{
		for(i=0;i<len.length;i++)
		{
			elementsA[i].checked = elementsB.checked;
		}
	}
	else
	{
		len.checked = elementsB.checked;
	}
} 
/**
 * 四舍五入
 * @param {} number 数字10.223.5
 * @param {} len 保留长度
 * @return {}
 */
Util.round = function(number,len){
   var lenNum = 1;
   for(var i=0;i<len;i++){
       lenNum *= 10;
   }
   return Math.round(number*lenNum)/lenNum;
} 

/**
 * 截取字符串
 * @param {} str-String
 * @param {} len-截取长度
 * @return {}
 */
Util.subStr = function(str,len){
    if(str.length>len)return str.substring(0,len);
    else return str;
}
/**
 * @param {} fileLen 文件长度
 * @return {}
 */
Util.getFileLength = function(length,len){
    try{
        var maxLength = 0;
	    if (length <= maxLength) {
	        return "0byte";
	    }
	    maxLength = 1024;
	    if (length < maxLength) {
	        return length + "byte";
	    }
	    maxLength *= 1024;
	    if (length < maxLength) {
	        return Util.round(length / maxLength * 1024,len) + "KB"; 
	    }
	    maxLength *= 1024;
	    if (length < maxLength) {
	        return Util.round(length / maxLength * 1024,len) + "MB";
	    }
	    maxLength *= 1024;
	    if (length < maxLength) {
	        return Util.round(length / maxLength * 1024,len) + "GB";
	    }
	    maxLength *= 1024;
	    if (length < maxLength) {
	        return Util.round(length / maxLength * 1024,len) + "TB";
	    }else {
	        return "0byte";
	    }
    }catch(ex){
        return "0byte";
    }
}
/**
 * 比较开始时间是否小于结束时间
 * @param {} beginDate
 * @param {} endDate
 * @return {Boolean}
 */
Util.compareDate = function (beginDate,endDate){
     var beginDates = beginDate.split("-");
     var byear = beginDates[0];
     var bmonth = beginDates[1];
     var bday = beginDates[2];
     var endDates = endDate.split("-");
     var eyear = endDates[0];
     var emonth = endDates[1];
     var eday = endDates[2];                 
     if(byear<=eyear){
         if(byear<eyear)return true;
         if(byear == eyear){
             if(bmonth<=emonth){
                 if(bmonth<emonth)return true;
                 if(bmonth == emonth){
                    if(bday<eday)return true;
                 }
             }
         }
     }
     return false;
}
/**比较2个日期天数之差**/
//sDate1和sDate2是2002-12-18格式 ;
Util.DateDiff = function (sDate1, sDate2)   
{
    var aDate, oDate1, oDate2, iDays;   
    aDate = sDate1.split("-");   
    oDate1 = new Date(aDate[0],aDate[1]-1,aDate[2]);   
    aDate = sDate2.split("-");   
    oDate2 = new Date(aDate[0],aDate[1]-1,aDate[2]);   
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24);     
    if((oDate1 - oDate2)<0){   
        return -iDays;   
    }   
    return iDays;    
}


/**
 * 清除字符串空格
 * @return
 */
String.prototype.trim = function() {
	return this.replace(/(^\s+)|(\s+$)/g, "");
};

/**
 * 检测字符串是否是非负整数
 * @return
 */
String.prototype.isNumber = function() {
        var reg = new RegExp("^\\d+$"); 
        if(this.match(reg)==null) 
        { 
           return false;
        }else{
           return true;
        } 
};

/**
 * 检测是否是合法字符(汉字以及字母合法)
 * @return {Boolean}
 */
String.prototype.isLegal = function(){
   var reg=new RegExp("[^a-zA-Z0-9\_\u4e00-\u9fa5]"); 
   return !reg.test(this.trim());
}  

/**
 * 检测数字是否是非负整数
 * @return
 */
Number.prototype.isNumber = function() {
        var reg = new RegExp("^\\d+$"); 
        if(this.match(reg)==null) 
        { 
           return false;
        }else{
           return true;
        } 
};

/**
 * 改变字符串首字母大写，其他小写
 * @return
 */
String.prototype.capitalize = function() {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
}

/**
 * 实现java层的StringBuffer类,同样具有append和toString方法
 */
function StringBuffer(){
	this._strings_ = new Array();
}

StringBuffer.prototype.append = function(str){
	this._strings_.push(str);
};

StringBuffer.prototype.toString = function(){
	return this._strings_.join("");
};

/**
 * 删除数组重复的元素
 * @return {}
 */
Array.prototype.unique = function (){
 var o = new Object();
 for (var i=0,j=0; i<this.length; i++)
 {
  if (typeof o[this[i]] == 'undefined')
  {
   o[this[i]] = j++;
  }
 }
 this.length = 0;
 for (var key in o)
 {
  this[o[key]] = key;
 }
 return this;
}
/**
 * 删除下标为dx的数组
 * @param {} dx
 * @return {Boolean}
 */
Array.prototype.remove = function(dx) 
{ 
    if(isNaN(dx)||dx>this.length){return false;} 
    this.splice(dx,1); 
} 

