/*
	定义和用法
	open() 方法用于打开一个新的浏览器窗口或查找一个已命名的窗口。
	
	语法
	window.open(URL,name,features,replace)
	

	URL 一个可选的字符串，声明了要在新窗口中显示的文档的 URL。如果省略了这个参数，或者它的值是空字符串，那么新窗口就不会显示任何文档。 

	name 一个可选的字符串，该字符串是一个由逗号分隔的特征列表，其中包括数字、字母和下划线，该字符声明了新窗口的名称。
		  这个名称可以用作标记 <a> 和 <form> 的属性 target 的值。
		  如果该参数指定了一个已经存在的窗口，那么 open() 方法就不再创建一个新窗口，而只是返回对指定窗口的引用。在这种情况下，features 将被忽略。 

	features 一个可选的字符串，声明了新窗口要显示的标准浏览器的特征。如果省略该参数，新窗口将具有所有标准特征。
		            在窗口特征这个表格中，我们对该字符串的格式进行了详细的说明。 

	replace 一个可选的布尔值。规定了装载到窗口的 URL 是在窗口的浏览历史中创建一个新条目，还是替换浏览历史中的当前条目。支持下面的值：

			true - URL 替换浏览历史中的当前条目。

			false - URL 在浏览历史中创建新的条目。 

	窗口特征（Window Features）
	channelmode=yes|no|1|0 是否使用剧院模式显示窗口。默认为 no。 
	directories=yes|no|1|0 是否添加目录按钮。默认为 yes。 
	fullscreen=yes|no|1|0 是否使用全屏模式显示浏览器。默认是 no。处于全屏模式的窗口必须同时处于剧院模式。 
	height=pixels 窗口文档显示区的高度。以像素计。 
	left=pixels 窗口的 x 坐标。以像素计。 
	location=yes|no|1|0 是否显示地址字段。默认是 yes。 
	menubar=yes|no|1|0 是否显示菜单栏。默认是 yes。 
	resizable=yes|no|1|0 窗口是否可调节尺寸。默认是 yes。 
	scrollbars=yes|no|1|0 是否显示滚动条。默认是 yes。 
	status=yes|no|1|0 是否添加状态栏。默认是 yes。 
	titlebar=yes|no|1|0 是否显示标题栏。默认是 yes。 
	toolbar=yes|no|1|0 是否显示浏览器的工具栏。默认是 yes。 
	top=pixels 窗口的 y 坐标。 
	width=pixels 窗口的文档显示区的宽度。以像素计。 

 */
var clearId;
var cutId;
Exmay = {};
Exmay = {
	plugin : {},
	string : {},
	url : {},
	path : {}
};

Exmay.string = {
	isEmpty : function(str) {
		str = str.replace(/(^[\s]*)|([\s]*$)/g,"");
		return str == null || str == "" || str == " " && str == 'undefined' && str == undefined;
	},
	isNotEmpty : function(str) {
		str = str.replace(/(^[\s]*)|([\s]*$)/g,"");
		return str != null && str != "" && str != " " && str!= 'undefined' && str != undefined;
	},
	trim : function(str) {
		return exmayTrim(str);
	}
}

String.prototype.endWith = function(str) {
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substring(this.length - str.length) == str)
		return true;
	else
		return false;
	return true;
}

String.prototype.startWith = function(str) {
	if (str == null || str == "" || this.length == 0
			|| str.length > this.length)
		return false;
	if (this.substr(0, str.length) == str)
		return true;
	else
		return false;
	return true;
}



Exmay.path = {
	admin : ""
}

// 打开全屏窗口
function openFullScreenWindow(url) {

	var width = (screen.availWidth - 10) + "px";
	var height = (screen.availHeight - 50) + "px";
	var left = 0;
	var top = 0;

	var args = "directories=no, location=no, maximize=yes, menubar=no, resizable=yes, scrollbars=yes, status=no, titlebar=no, toolbar=no, left=" + left + ", top=" + top + ", width=" + width + ", height=" + height;

	var wo = window.open(url, "", args);

	if (!wo) {

		$.exmayMessagebox.alert("窗口打开失败", "发现弹出窗口被阻止，请更改浏览器设置，以便正常使用本功能!", "warning");

		return false;

	} else {

		wo.moveTo(0, 0);

		wo.resizeTo(screen.availWidth, screen.availHeight);

		wo.outerWidth = screen.availWidth;

		wo.outerHeight = screen.availHeight;

	}

};

function openMaximizeWindow(url) {
	 if(url!== undefined && url!== null && url !== ''){
	    var scrWidth=screen.availWidth;
	    var scrHeight=screen.availHeight;
	    var self=window.open(url,"newwindow","resizable=yes,toolbar=yes, menubar=yes,   scrollbars=yes,location=yes, status=yes,top=0,left=0,width="+scrWidth+",height="+scrHeight);
	    self.resizeTo(scrWidth,scrHeight);
	    self.moveTo(0,0);
     }
}

$(function() { 
	/*只能输入数字*/
	$(".exmay-ui-number").keypress(function(evt){
		var $this = $(this);	 
		var myEvent = (evt) ? evt : ((window.event) ? window.event : "");
		var key =myEvent.keyCode||myEvent.which||myEvent.charCode;
	 	if(key > 47 && key <58 || key == 8 ){
	 		return true;
	 	}else{
	 		return false;
	 	}		 
	});
	
	$(".exmay-ui-english").keypress(function(evt){
		var $this = $(this);	 
		var myEvent = (evt) ? evt : ((window.event) ? window.event : "");
		var key =myEvent.keyCode||myEvent.which||myEvent.charCode;
		if(key >= 97 && key <=122 || key >=65 && key <=90 ){
 			return true;
 		}else{
 			return false;
 		}		
	});
	
	$(".exmay-ui-history-back").click(function(){
		window.history.go(-1);		
	});

});

function checkLength(target, name, max) {
	var maxChars = max;
	var contentLength = target.value.length;
	for ( var i = Math.floor(maxChars / 2); i < contentLength; i++) {
		var content = target.value.substring(0, i);
		if (content.replace(/([\u0391-\uFFE5])/ig, '111').length >= maxChars) {
			target.value = target.value.substring(0, i);
			document.getElementById(name + "-length").innerHTML = curr.toString(0);
			break;
		}
	}
	test = target.value.replace(/([\u0391-\uFFE5])/ig, '111');
	var curr = maxChars - test.length;
	document.getElementById(name + "-length").innerHTML = curr.toString();
}

$(function() {
	/*if (self != top) {
		if (self.frameElement.name == "exmay-panel-frame") {
			$(".exmay-ui-buttons").hide();
		}
	}*/
	
	$(".exmay-ui-auto-keyword").click(function(){
		var targetId = $(this).attr("to");
		var title = $("#exmay-title").val();
		var content = $("#exmay-content").exmayEditor("getHtml");
		if(title!="" ||  content!=""){
			$.ajax({
				type:"post",
				url:Exmay.path.admin+"/plugin/keyword/auto-keyword/?ajax=true",
				data:{"content":title+content},
				beforeSend:function(){exmayInitLoading("ExmayCMS提示:正在提取！");},
				error:function(){exmayInitLoading("ExmayCMS提示:提取失败！");},
				success:function(data){
					if(data.exmay!='fail'){
						exmayInitLoading("ExmayCMS提示:提取成功！");
						$("#"+targetId).val(data.exmay);
					}else{
						exmayInitLoading("亿美提示:内存不足或内容和标题的长度不够,请手动填写关键字.<a href='javascript:;' onclick='exmayMemory()' style='color:#ff0000;'>查看原因</a>");
					}
				}
			});
		}else{
			exmayInitLoading("亿美提示:请填写标题内容！");
		}
	});
	
	$(".exmay-ui-auto-summary").click(function(){
		var targetId = $(this).attr("to");
		var title = $("#exmay-title").val();
		var content = $("#exmay-content").exmayEditor("getHtml");
		if(title!="" ||  content!=""){
			$.ajax({
				type:"post",
				url:Exmay.path.admin+"/plugin/keyword/auto-summary/?ajax=true",
				data:{"content":title+content},
				beforeSend:function(){exmayInitLoading("ExmayCMS提示:正在提取！");},
				error:function(){exmayInitLoading("ExmayCMS提示:提取失败！");},
				success:function(data){
					if(data.exmay!='fail'){
						exmayInitLoading("ExmayCMS提示:提取成功！");
						$("#"+targetId).val(data.exmay);
					}else{
						exmayInitLoading("ExmayCMS提示:内存不足或者内容和标题的长度不够！&nbsp;<a href='javascript:;' onclick='exmayMemory()' style='color:#ff0000;'>查看原因</a>");
					}
				}
			});
		}else{
			exmayInitLoading("亿美提示:请填写标题内容！");
		}
	});
	
});

function exmayMemory(){
	$.ajax({
		type:"post",
		url:Exmay.path.admin+"/plugin/keyword/memory/?ajax=true",
		beforeSend:function(){},
		error:function(){},
		success:function(data){
			var jsonData = eval("("+data.exmay+")");
			exmayInitLoadingT("当前可用内存空间是："+exmayCountFileSize(jsonData.totalMemory).fileSize+",<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;剩余内存空间是："+exmayCountFileSize(jsonData.freeMemory).fileSize+",<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;只有当前虚拟内存超出64MB才能进行此操作.",5000);
		}
	});
}

function closeDialogs(top) {
	top.find(".exmayui-panel").remove();
	top.find(".exmayui-window-shadow").remove();
	top.find(".exmayui-window-mask").remove();
}

// 获取对话框
function getDialog(button) {
	return $(button).parents(".exmayui-dialog");
}

function getIframeDocument($dialog) {
	return getIFrameWindow($dialog).document;
}

//exmay
function get$Iframe($dialog) {
	return $dialog.find("#exmay-panel-frame").contents();
}
function getIframe($dialog) {
	return $dialog.find("#exmay-panel-frame")[0];
}
function reloadIFrame(button) {
	getDialog(button).find("#exmay-panel-frame")[0].contentWindow.location.reload();
}

function getIFrameWindow($dialog) {
	return $dialog.find("#exmay-panel-frame")[0].contentWindow;
}
//end exmay

// 获取对话框iframe中的表单
function getForm($dialog) {
	return get$Iframe($dialog).find("#exmay-form");
};

function exmayRefreshMenuIFrame() {
	window.top.menuFrame.location.reload();
}
function exmayRefreshMainIFrame() {
	window.top.mainFrame.location.reload();
}
/**
 * 刷新左右框架
 */
function exmayRefreshMenuAndMain() {
	exmayRefreshMenuIFrame();
	exmayRefreshMainIFrame();
}

/*获取父窗体和iframe窗体的事件*/
function exmayGetParentWindow(){
	var _window ;
	if(top.mainFrame!=undefined){
		_window = top.mainFrame;
	}else{
	    _window = parent;
	}
	return _window;
};

// 获取参数
function getData() {
	var id = null;
	var ids = null;
	var data = "";
	ids = $(".exmayui-treegrid").exmaySelectable("getSelected");
	if (ids.length > 0) {
		id = ids[0];
		data = "?parentId=" + id;
	}
	return data;
}

/* 重加载表格树*/
function exmayTreegridReload() {
	$('#exmay-treegrid').exmayTreegrid("reload");
};

/*获取窗体的高度和宽度*/
function getBodySize() {
	var _document = document;
	if (_document.compatMode == "BackCompat") {
		return {
			width : Math.max(_document.body.scrollWidth, _document.body.clientWidth),
			height : Math.max(_document.body.scrollHeight, _document.body.clientHeight)
		};
	} else {
		return {
			width : Math.max(_document.documentElement.scrollWidth, _document.documentElement.clientWidth),
			height : Math.max(_document.documentElement.scrollHeight, _document.documentElement.clientHeight)
		};
	}
};

/*获取窗体的高度和宽度(含滚动条)*/
function getBodyScrollSize() {
	var width = document.documentElement.clientWidth+document.documentElement.scrollWidth;
	var height = document.documentElement.clientHeight+document.documentElement.scrollHeight;
	return {"width":width,"height":height};
};

/*去除左边的空格*/
function exmayTrimLeft(str) { 
	var whitespace = '\t\r\n';
	while (str.length > 0 && whitespace.indexOf(str.substr(0, 1)) != -1) {
		str = str.substr(1);
	}
	return str;
}

/*去除右边的空格*/
function exmayTrimRight(str) { 
	var whitespace = '\t\r\n';
	while (str.length > 0 && whitespace.lastIndexOf(str.substr(str.length - 1, 1)) != -1) {
		str = str.substr(0, str.length - 1);
	}
	return str;
};

/*左右组合，去除两边的空格*/
function exmayTrim(str) { 
	return trim(str);
}

/*替换*/
function trim(val){
	if(val){
		return val.replace(/(^[\s]*)|([\s]*$)/g, "");
	}
};

/*随机产生ID*/
var random = 0;
function exmayYMD() {
	random++;
	return new Date().getTime() + "" + random;
};
/*随机生成随机数*/
function exmayRandom() {
	random++;
	return new Date().getTime() + "" + random;
};


/*图片扩展名验证*/
function exmayCheckImg(val) {
	return /(jpg|gif|bmp|png)$/.test(val);
};


/*获取选中内容来自news - list.html 2011-07-16*/
function exmayGetSelection() {
	var range;
	if ($.browser.msie) {
		range = document.selection.createRange();
		if (range.htmlText && range.text) {
			return range.htmlText;
		}
	} else {
		if (window.getSelection) {
			var selection = window.getSelection();
			if (selection.rangeCount > 0 && window.XMLSerializer) {
				range = selection.getRangeAt(0);
				var html = new XMLSerializer().serializeToString(range.cloneContents());
				return html;
			}
			if (selection.rangeCount > 0) {
				range = selection.getRangeAt(0);
				var clonedSelection = range.cloneContents();
				var div = document.createElement('div');
				div.appendChild(clonedSelection);
				return div.innerHTML;
			}
		}
	}
};

/*获取文件的后缀*/
function exmayGetFileExt(fileName){
	if (fileName.lastIndexOf(".") == -1)
		return "";
	var pos = fileName.lastIndexOf(".") + 1;
	return fileName.substring(pos, fileName.length);
};

/*获取文件名无后缀*/
function exmayGetFileName(file){
	var fileName = exmayTransferFile(file);
	var pos = fileName.lastIndexOf("/") + 1;
	if (pos == -1) {
		return fileName;
	} else {
		return fileName.substring(pos, fileName.length);
	}
};

/*boolean to string*/
function exmayBooleanToString(booleanString){
	/*if(booleanString==undefined || booleanString=='undefined')return eval(booleanString);
	return booleanString.toString();*/
	alert(booleanString);
	var flag = (booleanString ? booleanString == "true": undefined);
	if(flag) {
		return "true";
	} else {
		return "false";
	}
};

/*boolean to string*/
function exmayBooleanToStr(booleanString){
	if(booleanString==undefined || booleanString=='undefined')return eval(booleanString);
	return String(booleanString);
};

/*string to boolean*/
function exmayStringToBooleanEval(string){
	if(string==undefined || string=='undefined')return eval(string);
	return eval(string); 
};

/*string to boolean*/
function ExmayBooleanParse(string) { 
	if(string==undefined || string=='undefined')return eval(string);
	switch (string.toLowerCase ()) {   
		case "true": case "yes": case "1": return true;     
		case "false": case "no": case "0": case null: return false;        
		default:   return Boolean(string);  
	}
}; 

/*将\\转成/*/
function exmayTransferFile(fileName) {
	if (fileName.indexOf("\\") != -1) {
		fileName = fileName.replace("/\\\\/i", "/");
	}
	return fileName;
};

function exmayClearLoading(){
	$("body").exmayLoading("hide");
};

function exmayInitLoading(msg){
	$("body").exmayLoading( {msg : msg,show : true,timeout:3000});
};

function exmayWaitLoading(msg){
	$("body").exmayLoading( {msg : msg,show : true});
};

function exmayInitLoadingT(msg,timeout){
	$("body").exmayLoading( {msg : msg,show : true,timeout:timeout});
};


/*文件大小转换为MB GB KB格式*/
function exmayCountFileSize(size){
	var fsize = parseFloat(size,2);
	var fileSizeString;
    if (fsize < 1024) {
        fileSizeString = fsize.toFixed(2) + "B";
    } else if (fsize < 1048576) {
    	fileSizeString = (fsize/1024).toFixed(2) + "KB";
    } else if (fsize < 1073741824) {
    	fileSizeString = (fsize/1024/1024).toFixed(2) + "MB";
    } else if(fsize < 1024 * 1024 * 1024) {
    	fileSizeString = (fsize/1024/1024/1024).toFixed(2) + "GB";
    }else{
    	fileSizeString = "0B";
    }
	return {fileSize:fileSizeString};
};

/*缓存附件操作*/
function exmayGetCache(data){
	var cache = {
		id:data.id,
		path:data.path,
		name:data.name,
		alias:data.alias,
		size:data.size,
		url:data.url,
		viewss:data.views,
		description:data.description,
		price:data.price,
		credit:data.credit,
		password:data.password,
		ext:data.ext,
		time:data.time,
		status:data.status,
		type:data.type
	}
	return cache;
};

function exmayToJson(o,flag,replace){
	var arr_start = "ARRAY_S";
	var arr_end = "ARRAY_E";
	if(flag==null){
		flag = "\"";
	}
	if(replace==null){
		replace = true;
	}
	var r = [];
	if(typeof o == "string" || o == null) {
		return o;
	}
	if(typeof o == "object"){
		if(!o.sort){
			r[0]="{";
			for(var i in o){
				r[r.length]=flag;
				r[r.length]=i;
				r[r.length]=flag;
				r[r.length]=":";
				r[r.length]=flag;
				r[r.length]=exmayAarryToJson(o[i],flag,false);
				r[r.length]=flag;
				r[r.length]=",";
			}
			r[r.length-1]="}";
		}else{
			r[0]= arr_start;
			for(var i =0;i<o.length;i++){
				r[r.length]=flag;
				r[r.length]=exmayAarryToJson(o[i],flag,false);
				r[r.length]=flag;
				r[r.length]=",";
			}
			r[r.length-1]=arr_end;
		}
	 
		var str = r.join("");
		
		if(str=="}"){
			str="{}";
		}
		
		if(str==arr_end){
			str=arr_start+arr_end;
		}

		if(replace){
		
			var reg=new RegExp(flag+"{","g"); 
			str = str.replace(reg,"{");

			reg=new RegExp("}"+flag,"g");
			str = str.replace(reg,"}");
			
			reg=new RegExp(flag+arr_start,"g"); 
			str = str.replace(reg,"[");

			reg=new RegExp(arr_end+flag,"g");
			str = str.replace(reg,"]");

			if(str.indexOf(arr_start+"{")>-1){
				reg=new RegExp(arr_start+"{","g"); 
				str = str.replace(reg,"[{");
			}
			if(str.indexOf("}"+arr_end)>-1){
				reg=new RegExp("}"+arr_end,"g"); 
				str = str.replace(reg,"}]");
			}
		}
		return str;
	}
	return o.toString();
};
	
function exmayToJson(o){
    var r = [];  
    if (typeof o == "string")
    return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\""; 
	if (typeof o == "object") {  
     	if (!o.sort) { 
          for (var i in o)  
			r.push("\"" + i + "\":" + exmayToJson(o[i])); 
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) { 
                r.push("toString:" + o.toString.toString()); 
            } 
            r = "{" + r.join() + "}" 
        } else {  
           for (var i = 0; i < o.length; i++)
            	r.push(exmayToJson(o[i])) 
                r = "[" + r.join() + "]" 
        }  
         return r;  
	}  
    return o.toString(); 
}; 

/*转成json为对象*/	
function exmayEval(json){    
    return eval("("+json+")");    
};

function  exmayToJsonStringify(obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = exmayToJsonStringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

function exmayClearBlank(content){
	if(content=="")return "";
	return content.replace(/\s*/g,"");	
};

function exmayClearById(id){
	$("#"+id).html("");
};

function exmayClearByClass(className){
	$("."+className).html("");
};

function exmayClearSetTimeOutById(timer,attribute){
	exmaySetTimeout(exmayClearById,timer,attribute);
};

function exmayClearSetTimeOutByClass(timer,attribute){
	exmaySetTimeout(exmayClearByClass,timer,attribute);
};

/*自定义定时器 args是自定义多少个的.参数写在timer的后面*/
function exmaySetTimeout(funcName,timer){
	var args=[];
	for(var i=2;i<arguments.length;i++){
	  	args.push(arguments[i]);
	}
	return window.setTimeout(function(){funcName.apply(this,args);},timer);
};


/*为Url加上时间戳*/
function convertUrl(url) {
	var timestamp = (new Date()).valueOf();
	if (url.indexOf("?") >= 0) {
		url = url + "&t=" + timestamp;
	} else {
		url = url + "?t=" + timestamp;
	}
	return url;
};

//IE Firefox获取剪切板内容
function exmayGetClipboard() {
	if (window.clipboardData) {
		return (window.clipboardData.getData('text'));
	} else {
		if (window.netscape) {
			try {
				netscape.security.PrivilegeManager
						.enablePrivilege("UniversalXPConnect");
				var clip = Components.classes["@mozilla.org/widget/clipboard;1"]
						.createInstance(Components.interfaces.nsIClipboard);
				if (!clip) {
					return;
				}
				var trans = Components.classes["@mozilla.org/widget/transferable;1"]
						.createInstance(Components.interfaces.nsITransferable);
				if (!trans) {
					return;
				}
				trans.addDataFlavor("text/unicode");
				clip.getData(trans, clip.kGlobalClipboard);
				var str = new Object();
				var len = new Object();
				trans.getTransferData("text/unicode", str, len);
			} catch (e) {
				alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试，相对路径为firefox根目录/greprefs/all.js");
				return null;
			}
			if (str) {
				if (Components.interfaces.nsISupportsWString) {
					str = str.value
							.QueryInterface(Components.interfaces.nsISupportsWString);
				} else {
					if (Components.interfaces.nsISupportsString) {
						str = str.value
								.QueryInterface(Components.interfaces.nsISupportsString);
					} else {
						str = null;
					}
				}
			}
			if (str) {
				return (str.data.substring(0, len.value / 2));
			}
		}
	}
	return null;
} ;


/*全角转半角*/
function exmay_To_SBC(text) {
    return text.replace(/[\x20-\x7e]/g, function($) {
        return $ == " " ? "\u3000" : String.fromCharCode($.charCodeAt(0) + 0xfee0);
    });
};

/*全角转半角*/ 
function exmayToDBC(input) {//to DBC case
    var res="",c;
    for(var i=0;i< input.length;i++) {
        c=input.charCodeAt(i);
        if(c >=0xFF01 && c <=0xFF5E)// 65281 65374
            res+=String.fromCharCode(c-0xFEE0);//65248
        else if(c==0x3000)//12288
            res+=String.fromCharCode(0x20);//32
        else
            res+=input.charAt(i);
    }
    return res;
};

/*半角转全角*/
function exmayToSBC(input) {
    var res="",c;
    for(var i=0; i < input.length;i++) {
        c=input.charCodeAt(i);
        if(c>=0x21 && c<=0x7e)//33 126
            res+=String.fromCharCode(c+0xFEE0);
        else if(c==0x20)
            res += String.fromCharCode(0x3000);
        else
            res += input.charAt(i);
    }
    return res;
};

function exmaySetClipboard(txt){ 
	if(window.clipboardData){ 
	window.clipboardData.clearData(); 
		window.clipboardData.setData("Text",txt); 
	} 
	else if(navigator.userAgent.indexOf("Opera")!=-1){ 
		window.location=txt; 
	} 
	else if(window.netscape){ 
	try{ 
		netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
	} 
	catch(e){ 
		alert("您的firefox安全限制限制您进行剪贴板操作，请打开'about:config'将signed.applets.codebase_principal_support'设置为true'之后重试，相对路径为firefox根目录/greprefs/all.js"); 
		return false; 
	} 
	var clip=Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard); 
	if(!clip)return; 
	var trans=Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable); 
	if(!trans)return; 
	trans.addDataFlavor('text/unicode'); 
	var str=new Object(); 
	var len=new Object(); 
	var str=Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString); 
	var copytext=txt;str.data=copytext; 
	trans.setTransferData("text/unicode",str,copytext.length*2); 
	var clipid=Components.interfaces.nsIClipboard; 
	if(!clip)return false; 
		clip.setData(trans,null,clipid.kGlobalClipboard); 
	} 
};

/*过滤脚本*/
function exmayFilterScript(str){
	var regex = /<[\s]*?script[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?script[\s]*?>/ig;
	return str.replace(regex,"");
};

/*清除样式*/
function exmayFilterStyle(str){
	var regex = /<[\s]*?style[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?style[\s]*?>/ig;
	return str.replace(regex,"");
};

/*清除样式*/
function exmayFilterHead(str){
	var regex = /<[\s]*?head[^>]*?>[\s\S]*?<[\s]*?\/[\s]*?head[\s]*?>/ig;
	return str.replace(regex,"");
};


/*过滤A标签*/
function exmayFilterLink(str){
	var regex = /(<[\s]*?a[^>]*?>)([\s\S]*?)(<[\s]*?\/[\s]*?a[\s]*?>)/ig;
	return str.replace(regex,"$2");
};

/*过滤注释*/	
function exmayFilterRecommens(str){
	var regex = /<!--[^\s<]*-->/ig;
	return str.replace(regex,"");
};

/*过滤注释*/
function exmayFilterRecommensIV(str){
	var regex = /<!--(.*)[^\s<]*(.*)-->/ig;
	return str.replace(regex,"");
};

/*过滤注释*/
function exmayFilterRecommensVI(str){
	var regex = /<!--(.*)[^\s<]*/ig;
	return str.replace(regex,"");
};

/*替换空白符*/
function exmayFilterBlanks(str){
	var regex = /(\n|\r\n)\s+/ig;
	return str.replace(regex,"\n");
};

/*过滤注释*/
function exmayFilterComments(str){
	var regex = /\/\*(.*?)\*\//ig;
	return str.replace(regex,"");
};

/*
 * 高亮设置
 * obj  :要高亮的对象
 * flag :flag控制显示和不显示高亮
*/
function exmayAddHighlighter(obj, flag) {
	if (flag) {
		$(obj).css( {
			"backgroundColor" : "#FFFF99"
		});
	} else {
		$(obj).css( {
			"backgroundColor" : ""
		});
	}
};

/*数字递增*/
function exmayAddMouseDown(obj){
	clearId = window.setInterval(function(){
		exmayAddNumber(obj)
	},100);
};

/*数字递减*/
function exmayCutMouseDown(obj){
	cutId = window.setInterval(function(){
		exmayCutNumber(obj)
	},100);
};

/*清除递增递减*/
function exmayClearAddMouseUp(){
	if(clearId!=null || clearId!=undefined){
		window.clearInterval(clearId);
	}
	if(cutId!=null || clearId!=undefined){
		window.clearInterval(cutId);
	}
};
/*光标置后
用法:<input type="text" value="abcdefg123456789" onfocus="setFocus()">*/
function setFocus() { 	
	var obj = event.srcElement; 
	var txt =obj.createTextRange(); 
	txt.moveStart('character',obj.value.length); 
	txt.collapse(true); 
	txt.select(); 
}

function exmayAddNumber(obj){
	var $this = $(obj);
	var $targetId = $this.attr("to");
	var $val = $("#"+$targetId).val()*1;
	if(isNaN($val))return;
	if($val<=0)$("#"+$targetId).val(0);
	$("#"+$targetId).val($val+1);
};

function exmayCutNumber(obj){
	var $this = $(obj);
	var $targetId = $this.attr("to");
	var $val = $("#"+$targetId).val()*1;
	if(isNaN($val))return;
	if($val*1<=0){
		$("#"+$targetId).val(0);
	}else{
		$("#"+$targetId).val($val*1-1);
	}
};


function resizeImg(img, _w, _h) {
	//如果图片设定了宽度和高度就移除他们设定的宽度和高度
	img.removeAttribute('width');
	img.removeAttribute('height');
	var v = img.width / img.height;
	if (img.width / img.height > _w / _h) {
		if (img.width > _w) {
			img.width = _w;
		}
		else {
			img.width = img.width;
		}
		img.height = img.width / v;
	} else {
		if (img.height > _h) {
			img.height = _h;
		}
		else {
			img.height = img.height;
		}
		img.width = img.height * v+50;
	}
}

/**
 * 用法
 * var p = exmayParseQuery(url)["width"];
 * @param {Object} query
 * @return {TypeName} 
 */
function exmayParseQuery(query){var Params=new Object();if(!query)return Params;var Pairs=query.split(/[;&]/);for(var i=0;i<Pairs.length;i++) {var KeyVal=Pairs[i].split('=');if(!KeyVal||KeyVal.length!=2)continue;var key=unescape(KeyVal[0]);var val=unescape(KeyVal[1]);val=val.replace(/\+/g,' ');Params[key]=val;};return Params;};



$(function() {

	// Input元素获取焦点时绑定回车事件
	$("input").focus(function() {
		// 先清除绑定
			exmayUnbindInputSubmitEvents($(this));
			$(this).bind("keydown.enter", function(event) {
				event = (event) ? event : ((window.event) ? window.event : "")
				var key = event.keyCode ? event.keyCode : event.which;
				/*if (key == 13) { // Enter
						//this.form.submit();
					exmayFormSubmit(this);
					return false;
				}*/
			});
			exmayCtrlEnterSubmit(this);
		});

	// Input元素失去焦点时绑定清除事件
	$("input").blur(function() {
		//$(this).unbind(".enter");
			//$(this).unbind(".ctrl-s");
			exmayUnbindInputSubmitEvents($(this));
		});

	// 清除Input表单提交事件
	function exmayUnbindInputSubmitEvents($target) {
		$target.unbind(".enter");
		$target.unbind(".ctrl-s");
	}
	;

	// Textarea元素获取焦点时绑定CTRL+回车事件
	$("textarea").focus(function() {
		// 先清除绑定
			exmayUnbindTextareaSubmitEvents($(this));
			$(this).bind("keydown.ctrl-enter", function(event) {
				event = (event) ? event : ((window.event) ? window.event : "")
				var key = event.keyCode ? event.keyCode : event.which;
				if (event.ctrlKey && key == 13) { // Ctrl + Enter
						//this.form.submit();
					exmayFormSubmit(this);
					return false;
				}
			});
			exmayCtrlEnterSubmit(this);
		});

	// Textarea元素失去焦点时消除CTRL+回车事件
	$("textarea").blur(function() {
		//$(this).unbind(".ctrl-enter");
		//$(this).unbind(".ctrl-s");
		exmayUnbindTextareaSubmitEvents($(this));
	});

	// 清除Input表单提交事件
	function exmayUnbindTextareaSubmitEvents($target) {
		$target.unbind(".ctrl-enter");
		$target.unbind(".ctrl-s");
	}
	;

	// CTRL+S自动保存事件
	function exmayCtrlEnterSubmit(target) {
		$(target).bind("keydown.ctrl-s", function(event) {
			event = (event) ? event : ((window.event) ? window.event : "")
			var key = event.keyCode ? event.keyCode : event.which;
			/*if (event.ctrlKey && key == 83) { // Ctrl + s
				//target.form.submit();
				exmayFormSubmit(this);
				return false;
			}*/
		});
	}
	;

	// 表单提交
	function exmayFormSubmit(target) {
		var $submit = $("#exmay-dialog-submit", window.parent.document.body);
		if ($submit.length == 1) { // 对话框表单提交
			$submit.focus();
			///$submit.trigger("click"); 
//			if(!$(target.form).exmayValidator("validate")) {
//				return false;
//			}
			exmayTriggerClick($submit[0]);
		} else { // 普通表单提交
			if (target.form) {
				$(target.form).submit();
			}
		}
	}
	;

	// 模拟点击事件
	function exmayTriggerClick(target) {
		if (document.all && typeof (document.all) == "object") { //IE
			target.fireEvent("onclick");
		} else {
			var event = document.createEvent("MouseEvent");
			event.initEvent("click", false, false);
			target.dispatchEvent(event);
		}
	};

});

function exmaySubmit(target) {
	var $target = $(target);
	$target.exmayButton("disable");

	var name = $target.parents("form").attr("name");
	var isIE = (document.all) ? true : false;

	var $form = $target.parents("form");
	var isSubmit = $form.exmayValidator("validate");
	if (!isSubmit) {
		$target.exmayButton("enable");
		return false;
	}

	var isIE6 = isIE && ( [ /MSIE (\d)\.0/i.exec(navigator.userAgent) ][0][1] == 6);

	if (isIE6) {
		//IE6
		setTimeout(function() {
			document[name].fireEvent("onsubmit");
			document[name].submit();
		}, 0);
		return false;
	}
	$form.submit();
}

// 表单按钮
$(function() {
	var $exmaySubmit = $(".exmay-ui-submit");
	var $exmayReset = $(".exmay-ui-reset");
	var $exmayBack = $(".exmay-ui-back");
	if($exmaySubmit.html() != null) {
		$exmaySubmit.exmayButton({
			onClick : function(){
				$(this).exmayButton("disable");
				
				var name = $(this).parents("form").attr("name");
				var isIE = (document.all) ? true : false;
				
				var $form = $(this).parents("form");
				var isSubmit =  $form.exmayValidator("validate");
				if(!isSubmit) {
					$(this).exmayButton("enable");
					return false;
				}
				
				var isIE6 = isIE && ([/MSIE (\d)\.0/i.exec(navigator.userAgent)][0][1] == 6);
				
				if(isIE6) {
					//IE6
					setTimeout(function(){
						document[name].fireEvent("onsubmit");
						document[name].submit();
					},0);
					return false;
				}
				$form.submit();
			}
		});
	};
	if($exmayReset.html() != null) {
		$(".exmay-ui-reset").exmayButton({
			onClick : function(){
				$(this).parents("form")[0].reset();
				$(".exmayui-tip").hide();
			}
		});
	};
	if($exmayBack.html() != null) {
		$(".exmay-ui-back").exmayButton({
			onClick : function(){
				window.history.back();
			}
		});
	};
	
});

// 操作与动作栏
$(function() {
	
	$(document).scroll(function(){
		$("#exmay-action").css({"bottom": "0"});
	});
	
	$(document).resize(function(){
		$("#exmay-action").css({"bottom": "0"});
	});
	
});

function exmayIsIE6()  {
	return $.browser.msie && ($.browser.version == "6.0") && !$.support.style;
}

/**
 * 时间对象的格式化;
 */
Date.prototype.format = function(format) {
    /*eg:format="YYYY-MM-dd hh:mm:ss"; */
    var o = {
        "M+" :this.getMonth() + 1, 
        "d+" :this.getDate(), 
        "h+" :this.getHours(), 
        "m+" :this.getMinutes(), 
        "s+" :this.getSeconds(), 
        "q+" :Math.floor((this.getMonth() + 3) / 3),
        "S" :this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for ( var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]: ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

	function exmayIsIE6(){
		return $.brower.msie&&($.browser.version==6.0)&&!$.support.style;
	}
	
	// 兼容IE6
	function exmaySetIframeSrc(ele, url) {
		var self = this, timer=null;
		this.init = function() {
			timer = setTimeout(self.loadifm, 50);
		};
		this.loadifm = function() {
			ele.src = url;
			clearTimeout(timer);
		};
		this.init();
	}