var helper = {};

helper.http = {
	newXMLHttp: function() {
		var XMLHttp = null;
		if(window.XMLHttpRequest) {
			XMLHttp = new XMLHttpRequest();
		}
		if(XMLHttp == null && window.ActiveXObject) {
			var clsids = ["MSXML2.XMLHttp.7.0", "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp.2.0", "MSXML2.XMLHttp.1.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
			for(var i = 0; i < clsids.length && XMLHttp == null; i++) {
				try {
					XMLHttp = new ActiveXObject(clsids[i]);
				} catch(e) {}
			}
		}
		return XMLHttp;
	},
	get: function(URL, func) {
		try {
			var XMLHttp = this.newXMLHttp();
			if(typeof(func) != "function") {
				XMLHttp.open("GET", URL, false);
				XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				XMLHttp.send(null);

				var result = XMLHttp.status;
				var responseText = XMLHttp.responseText;

				if(result == 200) {
					return responseText;
				} else {
					return result;
				}
			} else {
				XMLHttp.onreadystatechange = function() {
					if(XMLHttp.readyState == 4) {
						if(XMLHttp.status == 200) {
							var responseText = XMLHttp.responseText;
							func(responseText);
						} else {
							func(false);
						}
					}
				};
				XMLHttp.open("GET", URL, true);
				XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				XMLHttp.send(null);
			}
		} catch(e) {}
	},
	post: function(URL, data, func) {
		try {
			var XMLHttp = this.newXMLHttp();
			if(typeof(func) != "function") {
				XMLHttp.open("POST", URL, false);
				XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				XMLHttp.send(data);

				var result = XMLHttp.status;
				var responseText = XMLHttp.responseText;

				if(result == 200) {
					return responseText;
				} else {
					return false;
				}
			} else {
				XMLHttp.onreadystatechange = function() {
					if(XMLHttp.readyState == 4) {
						if(XMLHttp.status == 200) {
							var responseText = XMLHttp.responseText;
							func(responseText);
						} else {
							func(false);
						}
					}
				};

				XMLHttp.open("POST", URL, true);
				XMLHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
				XMLHttp.send(data);
			}
		} catch(e) {}
	}
};

helper.cookies = {
	del: function(name) {
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		var cval = helper.cookies.get(name);
		if(cval != null)
			document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
	},
	set: function(name, value, remember) {
		if(remember == true) {
			var Days = 30;
			var exp = new Date();
			exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
			document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
		} else {
			document.cookie = name + "=" + escape(value) + ";path=/";
		}
	},
	setday: function(name, value, remember) {
		var Days = remember;
		var exp = new Date();
		exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
		document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();

	},
	setdomain: function(name, value, remember) {
		var domain = window.location.host.split(".");
		if(remember == true) {
			var Days = 30;
			var exp = new Date();
			exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
			document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString() + ";domain=." + domain[domain.length - 2] + "." + domain[domain.length - 1];
		} else {
			document.cookie = name + "=" + escape(value) + ";path=/" + ";domain=." + domain[1] + "." + domain[2];
		}
	},
	get: function(name) {
		var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

		if(arr = document.cookie.match(reg)) {
			return unescape(arr[2]);
		} else {
			return '';
		}
	}
};

/*
获取URL中指定的参数
例如：
URL:test.com/test.aspx?test=t
var t=help.request.queryString("test");
得到t
*/
helper.request = {
	queryString: function(item) {
		locationSearch = "";
		var tmpLocationArr = location.href.split("?");
		if(tmpLocationArr.length > 1) locationSearch = "?" + tmpLocationArr[1];
		var svalue = locationSearch.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
		var Qvalue = svalue ? svalue[1] : svalue;
		if(Qvalue == null) {
			return "";
		} else {
			return Qvalue.trim();
		}
	},
	queryurl: function(url, item) {
		locationSearch = "";
		var tmpLocationArr = url.split("?");
		if(tmpLocationArr.length > 1) locationSearch = "?" + tmpLocationArr[1];
		var svalue = locationSearch.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
		var Qvalue = svalue ? svalue[1] : svalue;
		if(Qvalue == null) {
			return "";
		} else {
			return Qvalue.trim();
		}
	}
};

helper.pager = {

	//分页
	PageList1: function(strFunName) {
		/***总页数***/
		var intPageCount = parseInt((parseInt(intRecordCount) + parseInt(intPageSize) - 1) / parseInt(intPageSize));
		if(intPageCount <= 1) {
			return "";
		}

		/***页码距***/
		var intPageCurrent = 10;

		/***起始页码***/
		var intStartPage = (parseInt((parseInt(intPageIndex) + intPageCurrent - 1) / intPageCurrent) - 1) * intPageCurrent + 1;

		/***结束页码***/
		var intEndPage = intStartPage + intPageCurrent - 1;
		if(intPageIndex % intPageCurrent == 0) {
			intStartPage++;
			intEndPage++;
		}

		if(intPageIndex % intPageCurrent - 1 == 0 && intPageIndex != 1) {
			intStartPage--;
			intEndPage--;
		}

		if(intEndPage >= intPageCount) {
			intEndPage = intPageCount;
		}

		/***上一页，下一页***/
		var intUpPage = parseInt(intPageIndex) - 1;
		var intDownPage = parseInt(intPageIndex) + 1;
		var strUpPage = "<a href=\"#\" onclick=\"" + strFunName + "(" + intUpPage + ")\" >上一页</a>";
		var strDownPage = "<a href=\"#\" onclick=\"" + strFunName + "(" + intDownPage + ")\">下一页</a>";
		if(intUpPage < 1) {
			//intUpPage = 1;
			strUpPage = "";
		}
		if(intPageIndex >= intPageCount) {
			//intDownPage = intPageCount;
			strDownPage = "";
		}

		/***生成页码列表***/
		var strPageList = strUpPage;

		for(var i = intStartPage; i <= intEndPage; i++) {
			if(intPageIndex == i) {
				/***当前页码***/
				strPageList += "<a style=\"background-image:url(../images/bg/menublue22.jpg); background-position:bottom; background-repeat:repeat-x; padding:1px 6px;border-radius: 4px 4px 4px 4px; margin-right:3px; border:1px solid #aeb2b1;\" >" + i + "</a>";
			} else {
				strPageList += "<a href=\"#\" onclick=\"" + strFunName + "(" + i + ");\">" + i + "</a>";
			}
		}
		strPageList += strDownPage;

		//直接跳转
		strPageList += "总页数：" + intPageCount + "&nbsp;&nbsp;/&nbsp;&nbsp;";
		strPageList += "<input type=\"text\" onkeyup=\"this.value=this.value.replace(/\\D/g,'')\" id=\"tb_index\" />";
		strPageList += "&nbsp;&nbsp;<a style=\"cursor:pointer;\" onclick=\"javascript:helper.pager.checkPageValue()\">跳转</a>";
		return strPageList;

	},
	checkPageValue: function() {
		var intPageIndexNext = document.getElementById('tb_index').value;
		if(parseInt(intPageIndexNext) == 0) {
			document.getElementById('tb_index').value = "1";
			$.jBox.alert('输入页面不能为0', '提示');
			return;
		}
		if(intPageIndexNext == "") {
			document.getElementById('tb_index').value = "1";
			$.jBox.alert('输入页面不能为空', '提示');
			return;
		}
		if(intPageIndexNext.length != 0) {
			var intPageCount = parseInt((parseInt(intRecordCount) + parseInt(intPageSize) - 1) / parseInt(intPageSize));
			if(intPageIndexNext <= intPageCount) {
				intPageIndex = intPageIndexNext;
				loadlist();
			} else {
				document.getElementById('tb_index').value = intPageCount;
				$.jBox.alert('输入页面不能大于总页数', '提示');
			}
		} else {
			document.getElementById('tb_index').value = "1";
		}
	},
	loadJS: function(url) {
		var domScript = document.createElement('script');
		domScript.type = "text/javascript";
		domScript.src = url;
		domScript.onload = domScript.onreadystatechange = function() {
			if(!this.readyState || 'loaded' === this.readyState || 'complete' === this.readyState) {
				this.onload = this.onreadystatechange = null;
				this.parentNode.removeChild(this);
			}
		};
		document.getElementsByTagName('head')[0].appendChild(domScript);
	}
};

helper.masklayer = {
	layer: null,
	showcount: 0,
	show: function() {
		this.layer = document.getElementById("masklayer");
		if(!this.layer) {
			this.layer = document.createElement("div");
			this.layer.id = "masklayer";
			this.layer.className = "masklayer";
			/*this.layer.style.position = "absolute";
			this.layer.style.top = "0";
			this.layer.style.left = "0";
			this.layer.style.zIndex = 1000;
			var width = Math.max(
			Math.max(document.body.clientWidth, document.documentElement.clientWidth),
			Math.max(document.body.scrollWidth, document.documentElement.scrollWidth)
			);
			var height = Math.max(
			Math.max(document.body.clientHeight, document.documentElement.clientHeight),
			Math.max(document.body.scrollHeight, document.documentElement.scrollHeight)
			);
			this.layer.style.width = width + "px";
			this.layer.style.height = height + "px";*/
			this.layer.innerHTML = "<iframe src='/blank.html' style='width:100%;height:100%;background-color:#fff;" +
				"filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;" +
				"position:absolute;z-index:999;top:0;left:0;' frameborder='0'></iframe>" +
				"<div style='width:100%;height:100%;position:absolute;top:0;left:0;z-index:1000;background:#000;" +
				"filter:alpha(opacity=20);-moz-opacity:0.2;-khtml-opacity: 0.2;opacity: 0.2;'></div>";
			document.body.appendChild(this.layer);
		}
		this.showcount++;
	},
	hide: function() {
		if(--this.showcount == 0) {
			if(this.layer && this.layer.parentNode) {
				this.layer.parentNode.removeChild(this.layer);
			}
		}
	},
	moveToCenter: function(e, x, y) {
		if(e.style.display == "none") e.style.display = "";
		var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
		var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
		if(x > 0) {
			x += scrollLeft;
		} else x = parseInt((document.documentElement.clientWidth - e.clientWidth) / 2) + scrollLeft;
		if(y > 0) {
			y += scrollTop;
		} else y = parseInt((document.documentElement.clientHeight - e.clientHeight) / 2) + scrollTop;
		x = x < 0 ? 0 : x;
		y = y < 50 ? 50 : y;
		e.style.left = x + "px";
		e.style.top = y + "px";
	}
};

helper.filter = {
	Transcoding: function(content) {
		content = content.replace(/∞L/g, "<");
		content = content.replace(/∞R/g, ">");
		content = content.replace(/∞∴/g, "'");
		content = content.replace(/∞≡/g, "#");
		content = content.replace(/∞※/g, "\"");
		return content;
	},
	//过滤html
	filterHTMLTag: function(str) {
		str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
		str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
		//str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
		str = str.replace(/ /ig, ''); //去掉 
		return str;
	},
	delHtmlTag: function(str) { //匹配html标签中的内容  
		return str.replace(/<[^>]+>/g, "");
	},
	//原样式输出内容
	content: function(content) {
		if(content === "null" || content === "undefined" || content === null || content === undefined || content == "") {
			content = "暂无内容。。。";
		} else {
			content = content.replace(/[ ]/g, "&nbsp;").replace(/\ +/g, "&nbsp;").replace(/\r\n/g, "<br />").replace(/\n/g, "<br />");
		}
		return content;
	},
	//电话号码截取前三位和后四位
    cutTel: function (val) {
        var str = '';
        var isShow = false;        // 是否截取号码
        if (val) {
            if (isShow) {
                var val1 = val.substring(0, 3);
                var val2 = val.substr(-4);
                str = val1 + '****' + val2;
            } else {
                str = val;
            }
        }
        return str;
    }

};

function str2asc(strstr) {
	return("0" + strstr.charCodeAt(0).toString(16)).slice(-2);
}
helper.url = {
	getpara: function(name) {
		var val;
		paras = window.location.search;
		paras = paras.substr(1);
		paraarray = paras.split("&");
		for(i = 0; i < paraarray.length; i++) {
			temp = paraarray[i].split("=");
			if(temp[0] == name) {
				val = temp[1];
				break;
			}
		}
		if(val == null || val == "") {
			return "";
		} else {
			return val;
		}
	}
};
helper.sys = {
	getElementsByClassName: function(pnode, className) {
		var nodes = pnode.getElementsByTagName('*');
		var elements = new Array();
		for(var i = 0; i < nodes.length; i++) {
			if(nodes[i].className == className) {
				elements[elements.length] = nodes[i];
			}
		}
		return elements;
	},
	removeElement: function(element) {
		if(element && element.parentNode) {

			element.parentNode.removeChild(element);
			return true;
		} else {
			return false;
		}
	},
	Return: function(url) {
		top.location.href = url;
	}
};

helper.DateFormat = {
	d2s: function(postdate) {
		var second = 1000;
		var minutes = second * 60;
		var hours = minutes * 60;
		var days = hours * 24;
		var months = days * 30;
		var twomonths = days * 365;
		var myDate = new Date(Date.parse(postdate));
		if(isNaN(myDate)) {
			myDate = new Date(postdate.replace(/-/g, "/"));
		}
		var nowtime = new Date();
		var longtime = nowtime.getTime() - myDate.getTime();
		var showtime = 0;
		if(longtime > months * 2) {
			return postdate;
		} else if(longtime > months) {
			return "1个月前";
		} else if(longtime > days * 7) {
			return("1周前");
		} else if(longtime > days) {
			return(Math.floor(longtime / days) + "天前");
		} else if(longtime > hours) {
			return(Math.floor(longtime / hours) + "小时前");
		} else if(longtime > minutes) {
			return(Math.floor(longtime / minutes) + "分钟前");
		} else if(longtime > second) {
			return(Math.floor(longtime / second) + "秒前");
		} else {
			return("刚刚");
		}
	},
	getPreMonth:
		/**
		 * 获取上一个月
		 *
		 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
		 */
		function(date) {
			var arr = date.split('-');
			var year = arr[0]; //获取当前日期的年份
			var month = arr[1]; //获取当前日期的月份
			var day = arr[2]; //获取当前日期的日
			var days = new Date(year, month, 0);
			days = days.getDate(); //获取当前日期中月的天数
			var year2 = year;
			var month2 = parseInt(month) - 1;
			if(month2 == 0) {
				year2 = parseInt(year2) - 1;
				month2 = 12;
			}
			var day2 = day;
			var days2 = new Date(year2, month2, 0);
			days2 = days2.getDate();
			if(day2 > days2) {
				day2 = days2;
			}
			if(month2 < 10) {
				month2 = '0' + month2;
			}
			var t2 = year2 + '-' + month2 + '-' + day2;
			return t2;
		},
	getNextMonth:
		/**
		 * 获取下一个月
		 *
		 * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
		 */
		function(date) {
			var arr = date.split('-');
			var year = arr[0]; //获取当前日期的年份
			var month = arr[1]; //获取当前日期的月份
			var day = arr[2]; //获取当前日期的日
			var days = new Date(year, month, 0);
			days = days.getDate(); //获取当前日期中的月的天数
			var year2 = year;
			var month2 = parseInt(month) + 1;
			if(month2 == 13) {
				year2 = parseInt(year2) + 1;
				month2 = 1;
			}
			var day2 = day;
			var days2 = new Date(year2, month2, 0);
			days2 = days2.getDate();
			if(day2 > days2) {
				day2 = days2;
			}
			if(month2 < 10) {
				month2 = '0' + month2;
			}

			var t2 = year2 + '-' + month2 + '-' + day2;
			return t2;
		},
	getNowDate: function() {
		var NowDate;
		var myDate = new Date();
		var YY = myDate.getFullYear(); //获取完整的年份(4位,1970-????)    
		var MM = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)    
		var DD = myDate.getDate(); //获取当前日(1-31)
		MM = MM > 9 ? MM : '0' + MM;
		DD = DD > 9 ? DD : '0' + DD;

		//      myDate.getDay();         //获取当前星期X(0-6,0代表星期天)    
		//		myDate.getYear();       //获取当前年份(2位)    
		//      myDate.getTime();       //获取当前时间(从1970.1.1开始的毫秒数)    
		//      myDate.getHours();       //获取当前小时数(0-23)    
		//      myDate.getMinutes();     //获取当前分钟数(0-59)    
		//      myDate.getSeconds();     //获取当前秒数(0-59)    
		//      myDate.getMilliseconds();   //获取当前毫秒数(0-999)    
		//      myDate.toLocaleDateString();     //获取当前日期    
		//      var mytime = myDate.toLocaleTimeString();     //获取当前时间    
		//      myDate.toLocaleString();       //获取日期与时间    
		NowDate = YY + "-" + MM + "-" + DD;
		return NowDate;
	},
	getNowYear: function() {
		//获取当前年份
		var NowDate;
		var myDate = new Date();
		var YY = myDate.getFullYear(); //获取完整的年份(4位,1970-????)    
		NowDate = YY;
		return NowDate;
	},

	getFirstDayInCurrentMonth: function() {
		var NowDate;
		var myDate = new Date();
		myDate.getYear(); //获取当前年份(2位)    
		var YY = myDate.getFullYear(); //获取完整的年份(4位,1970-????)    
		var MM = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)    
		var DD = myDate.getDate(); //获取当前日(1-31)    
		NowDate = YY + "-" + MM + "-1";

		return NowDate;
	}
};

helper.getDropList = {
	/**
	 * 获取字典下拉(搜索用)
	 * */
	getlistDropByDic(el, fg) {
		var dtd = $.Deferred(); //在函数内部，新建一个Deferred对象
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
			dataType: 'json',
			async: true,
			data: {
				flag: fg,
				token: $.cookie("token")
			},
			success: function(data) {
				if(data.state.toLowerCase() === 'success') {
					//el.empty();
					//el.append('<option value="0">请选择</option>');
					var res = data.data;
					for(var i = 0; i < res.length; i++) {
						$('<option value=' + res[i].F_DictionaryValueId + '>' + res[i].F_Name + '</option>').appendTo(el);
					}
					el.selectpicker('refresh');
					dtd.resolve(); // 改变Deferred对象的执行状态
				}
			}
		});
		return dtd.promise(); // 返回promise对象
	},
	/**
	 * 获取字典下拉(多次加载这个字典方法时用)
	 * */
	getlistDropByDics(el, fg) {
		var dtd = $.Deferred(); //在函数内部，新建一个Deferred对象
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
			dataType: 'json',
			async: true,
			data: {
				flag: fg,
				token: $.cookie("token")
			},
			success: function(data) {
				if(data.state.toLowerCase() === 'success') {
					el.empty();
					el.append('<option value="0">请选择</option>');
					var res = data.data;
					for(var i = 0; i < res.length; i++) {
						$('<option value=' + res[i].F_DictionaryValueId + '>' + res[i].F_Name + '</option>').appendTo(el);
					}
					el.selectpicker('refresh');
					dtd.resolve(); // 改变Deferred对象的执行状态
				}
			}
		});
		return dtd.promise(); // 返回promise对象
	},
	/**
	 * 根据字典 获取 动态radio
	 * el 元素  fg 元素值 ran radio的name
	 * */
	getOrderRadios(el, fg, ran) {
		var dtd = $.Deferred(); //在函数内部，新建一个Deferred对象
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "Dictionary/GetDicValueListByFlag",
			dataType: 'json',
			async: true,
			data: {
				flag: fg,
				token: $.cookie("token")
			},
			success: function(data) {
				if(data.state.toLowerCase() === 'success') {
					var res = data.data;
					for(var i = 0; i < res.length; i++) {
						$('<label class="radio-inline">' +
							'<input type="radio" name="' + ran + '" value="' + res[i].F_DictionaryValueId + '">' + res[i].F_Name +
							'</label>').appendTo(el);
					}
					$(el).find('input[type="radio"]').eq(0).attr('checked', true);
					dtd.resolve(); // 改变Deferred对象的执行状态
				}
			}
		});
		return dtd.promise(); // 返回promise对象
	},
	//区域，项目，期号三级联动
	getProLocations(obj, obj1, obj2) {
		var dtd = $.Deferred(); //在函数内部，新建一个Deferred对象
		$.ajax({
			type: "get",
			url: huayi.config.callcenter_url + "CusRegionCategory/GetListTreeDrop",
			dataType: 'json',
			async: false,
			success: function(data) {
				var content = data.data; //区域信息
				var cityInfos = []; //项目
				var proInfos = []; //期号信息
				//初始化区域
				//obj.selectpicker('destroy');
				obj.empty();
				obj.append('<option selected="selected" value="0">请选择区域</option>');
				$(content).each(function(i, n) {
					if(n.ParentId === 0) {
						$("<option value='" + n.id + "'>" + n.text + "</option>").appendTo(obj);
						if(n.children != null && n.children.length > 0) {
							cityInfos.push(n.children);
						}
					}
				});
				obj.selectpicker('refresh');
				//项目
				obj.change(function() {
					//obj1.selectpicker('destroy');
					obj1.empty();
					obj1.append('<option selected="selected" value="0">请选择项目</option>');
					proInfos = []; //期号信息
					for(var i = 0; i < cityInfos.length; i++) {
						$(cityInfos[i]).each(function(j, v) {
							if(v.ParentId > 0) {
								if(obj.find("option:selected").val() == v.ParentId) {
									$("<option value='" + v.id + "'>" + v.text + "</option>").appendTo(obj1);
									if(v.children != null && v.children.length > 0) {
										proInfos.push(v.children);
									}
								}
							}
						});
					}
					obj1.selectpicker('refresh');
					if(obj1.val() == null) {
						obj1.append('<option selected="selected" value="0">没有数据</option>');
					}
					obj1.trigger('change');
				});

				//楼
				obj1.change(function() {
					//obj2.selectpicker('destroy');
					obj2.empty();
					obj2.append('<option selected="selected" value="0">请选择期号</option>');
					for(var j = 0; j < proInfos.length; j++) {
						$(proInfos[j]).each(function(k, n) {
							if(n.ParentId > 0) {
								if(obj1.find("option:selected").val() == n.ParentId) {
									$("<option value='" + n.id + "'>" + n.text + "</option>").appendTo(obj2);
								}
							}
						});
					}
					obj2.selectpicker('refresh');
					if(obj2.val() == null) {
						obj2.append('<option selected="selected" value="0">没有数据</option>');
					}
					dtd.resolve(); // 改变Deferred对象的执行状态
				});
			},
		});
		return dtd.promise(); // 返回promise对象
	},

};

helper.methods = {
	/**
	* 对象数组去重(用于自定义字段保存时)
	* @oldArr 数组
	* @name 要比较的属性 String
	*/
	uniqueObjArray: function(oldArr, name) {
		var allArr = [];
		for(var i = 0; i < oldArr.length; i++) {　　
			var flag = true;　　
			for(var j = 0; j < allArr.length; j++) {
				if(oldArr[i][name] == allArr[j][name]) {　　　　　　
					flag = false;　　　　
				};　　
			};
			if(flag) {　　　　
				allArr.push(oldArr[i]);　　
			};
		};
		return allArr;
	},
	//比较器（可以根据对象的属性进行比较）  用法 arr.sort(compare('age'))
	compare: function(prop) {
		return function(obj1, obj2) {
			var val1 = obj1[prop];
			var val2 = obj2[prop];
			if(!isNaN(Number(val1)) && !isNaN(Number(val2))) {
				val1 = Number(val1);
				val2 = Number(val2);
			}
			if(val1 < val2) {
				return -1;
			} else if(val1 > val2) {
				return 1;
			} else {
				return 0;
			}
		}
	},
	/**
	 * 将一维的扁平数组转换为多层级对象
	 * @param  {[type]} list 一维数组，数组中每一个元素需包含id和ParentId两个属性 
	 * @return {[type]} tree 多层级树状结构
	 */
	buildTree: function(list) {
		var temp = {};
		var tree = {};
		var arr = [];
		for(var j in list) {
			temp[list[j].id] = list[j];
		}
		for(var i in temp) {
			if(temp[i].ParentId) {
				if(!temp[temp[i].ParentId].children) {
					temp[temp[i].ParentId].children = new Object();
				}
				temp[temp[i].ParentId].children[temp[i].id] = temp[i];
			} else {
				tree[temp[i].id] = temp[i];
			}
		}
		for(var k in tree) {
			arr.push(tree[k]);
		}
		return arr;
	},
	objToArray: function(mobj) {
		var arr = [];
		for(var k in mobj) {
			arr.push(mobj[k]);
		}
		return arr;
	},
	arrayToObj: function(marr) {
		var tobj = {};
		for(var k in marr) {
			tobj[k] = marr[k];
		}
		return tobj;
	}
}

helper.string = {
	stringbuilder: function() {
		this.arr = new Array();
		this.append = function(str) {
			this.arr.push(str);
		};
		this.tostring = function() {
			return this.arr.join('');
		};
	}
};
helper.init = {
	setajax: function(isload) { /// 配置AJAX
		$(document).on("ajaxStart", function() {
			if(isload) {
				//加载框显示
			}
		}).on("ajaxSuccess", function(e, jqXHR, s, data) {
			try {
				if(s.type == "POST") {
					if(typeof(data) != 'object') {
						data = $.parseJSON(data);
					}
				}
				if(s.type == "GET") {
					data = data
				}
				if(data.state.toLowerCase() == "notoken") {
					top.window.location.href = "/login.html";
					return;
				}
				if(data.state.toLowerCase() == "unauthorized") {
					layer.confirm(data.message, {
						btn: ['确定'] //按钮
					});
				}
				if(data.state.toLowerCase() == "error") {
					layer.confirm(data.message, {
						btn: ['确定'] //按钮
					});
				}
			} catch(e) {
				if(isload) {
					//加载框消失
				}
			}
		}).on("ajaxStop", function() {
			if(isload) {
				//加载框消失
			}
		})
	},
	setdh: function() {
		$(document).ready(function() {
			$("#ReIndex").click(function() {
				top.$("iframe:visible")[0].src = "widgets.html";
				top.$(".J_menuTab").eq(0).addClass("active").text('首页');
				top.$(".J_menuTab").eq(0).attr("data-id", 'widgets.html');
				top.$(".J_mainContent .J_iframe0").attr("data-id", "widgets.html");
			});
			$(".dhRight").click(function() {
				location.reload();
			})
		})
	},
	enterSearch: function() { //enter搜索
		$(document).on('keypress', function(event) {
			if(event.keyCode === 32) {
				if($(event.target).context.nodeName != "TEXTAREA") {
					$(event.target).blur();
				}
			}
			if(event.keyCode === 13) {
				$('.search').trigger("click");
				$('#sc_btns').trigger("click");
			}
		});
	}
}
helper.init.setajax();
helper.init.setdh();
helper.init.enterSearch();