/**
 * 常用的封装类
 * 
 * 
**/
/**
 * json util
 */
var JsonUtil = {
	toJson:function(text){
	   try{
		 if(!text){
			 return null;
		 }
	     var j = eval('(' + text + ')')
	     return j;
	   }catch(e){//捕获是否成功转换异常
		   
	   }
	   return null;
    },
    toString:function(o){
    	var arr = []; 
    	var fmt = function(s) { 
    		 if (typeof s == 'object' && s != null) return JsonToStr(s); 
    		 return /^(string|number)$/.test(typeof s) ? '\'' + s + '\'' : s; 
    	} 
    	
    	for (var i in o) {
    	    arr.push('\'' + i + '\':' + fmt(o[i]));
    	}
    	return '{' + arr.join(',') + '}'; 
    }
}
/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 * eg:
 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.format=function(fmt) {
	var o = {
		"M+" : this.getMonth()+1, //月份
		"d+" : this.getDate(), //日
		"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时
		"H+" : this.getHours(), //小时
		"m+" : this.getMinutes(), //分
		"s+" : this.getSeconds(), //秒
		"q+" : Math.floor((this.getMonth()+3)/3), //季度
		"S"  : this.getMilliseconds() //毫秒
	};
	var week = {
		"0" : "\u65e5",
		"1" : "\u4e00",
		"2" : "\u4e8c",
		"3" : "\u4e09",
		"4" : "\u56db",
		"5" : "\u4e94",
		"6" : "\u516d"
	};
	if(/(y+)/.test(fmt)){
		fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	if(/(E+)/.test(fmt)){
		fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);
	}
	for(var k in o){
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
}
/**
 * string
 * @return  string
 */
String.prototype.Trim = function() { 
	return this.replace(/(^\s*)|(\s*$)/g, ""); 
} 
/**
 * string fromat
 * @param src
 * @return
 */
String.format = function(src){
    if (arguments.length == 0) return null;
    var args = Array.prototype.slice.call(arguments, 1);
    return src.replace(/\{(\d+)\}/g, function(m, i){
        return args[i];
    });
};
/**
 * 时间 处理类
 * 
 */
var DateUtil = {
	/**
	 * 昨天
	 */
	yesterday:function(){
	    var dat = new Date();
	    dat.setDate(dat.getDate() - 1);
	    return this.patternYMD(dat);
    },
    /**
     * 今天
     */
	today:function(){
	    var dat = new Date();
	    return this.patternYMD(dat);
    },
    /**
     * 明天
     */
    tomorrow:function(){
	    var dat = new Date();
	    dat.setDate(dat.getDate() + 1);
	    return this.patternYMD(dat);    	
    },
    /**
     * 格式
     */
    patternYMD: function(dat){
    	return dat.getFullYear() + '-' + (dat.getMonth() + 1) + '-' + dat.getDate();
    },
    /**
     * @param time:string time
     */
    getYMDHm: function(time){
    	if (!time) {
    		return '';
    	}
    	return time.substring(0, 16);
    },
    /**
     * @param time:string time
     */
    getYMD: function(time){
    	return time.substring(0, 10);
    }
}
/**
 * 数据检测类
 */
var CheckUtil = {
	/**
	 * 电话号码验证(移动 + 家庭电话)
	 * @param phone:号码
	 * @return 满足格式true 否则为false
	 */
	checkPhone: function(phone){
		if (phone) {
			var regex = /^(((1[0-9]{10})|(0[0-9]{2,3}-*[0-9]{7,8}))[,， ]?)+$/i;
			return regex.test(phone);
		}
		return false;
	},
	/**
	 * 手机号码验证
	 * @param mobile:号码 
	 * @return 满足格式true 否则为false
	 */
    checkMobile: function(mobile){
		if (mobile) {
			var regex = /^1[0-9]{10}$/i;
			return regex.test(mobile);
		}
		return false;
	},
	/**
	 * qq号码验证
	 * @param qq: 号码
	 * @return 满足格式true 否则为false
	 */
	checkQQ:function(qq){
		var regex = /^\d{4,12}$/i;
		return regex.test(qq);
	},
	/**
	 * 检测邮箱地址
	 * @parm email:email地址
	 * @return 满足格式true 否则为false
	 */
	checkEmail:function(email){
		var regex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i;
		return regex.test(email);
	},
	/**
	 * 只能是数字输入
	 *  onkeypress="return onlyNumber(event)" style="ime-mode:Disabled"
	 * @param event
	 * @return
	 */
	onlyNumber: function(event){
	   event = (event) ? event : ((window.event) ? window.event : ""); 
	   var key = event.keyCode?event.keyCode:event.which; 
	   if((key>=48 && key<=57) || key ==8  ||key == 37 || key == 39 || key == 9){ //|| key == 46
	     //e.returnValue=true;
	     return true;
	   }
	   return false;
	}
}

/**
 * 过滤器
 */
var Filter = {
	/**
	 * < 这个字符换成 &lt;
	 * @param html内容
	 */
	filteLTLaber:function(html){
	   if (!html) {return "";}
	   
	   return html.replace(/</g,'&lt;').replace(/>/g,'&gt;');	   
    },
    /**
     * 换行
     */
    filteToHTMLNextLine:function(text){
    	return text.replace(/(\r\n)|(\n)|(\r)/gi,'<br/>');	   
    },
    escapeHTML:function(text){
    	return this.filteLTLaber(text);
    },
    /**
     * 过滤html标签
     */
    filteHTML:function(html){
    	return html.replace(/<[^>]*>/gi,'');
    },
    /**
     * 过滤 textarea
     */
    filteTextArea:function(text){
    	return this.filteToHTMLNextLine(this.filteLTLaber(text));
    }
}
/**
 * 请求操作
 * 
 */
var Request = {
	/**
	 *  post
	 *  @param url:url操作
	 *  @param data:{}json object
	 *  @param handler:回调函数
	 */
	post: function(url, data, handler){
		$.ajax({
		   type: 'POST',
		   url : url,
		   data: data,
		   success: function(msg){
			   var json = JsonUtil.toJson(msg);
			   if (json) {
				   (handler)(json);
			   }
		   }
		});
   }	
}
/**
 * 转换器
 */
var Formater = {
   /**
    * 保留pos位小数
    */
   formatFloat: function(val, pos){
	 return Math.round(val * Math.pow(10, pos))/Math.pow(10, pos);
   }
}
/*********create a window end*********/
/**
 * 
 * 
 * 确定窗口
 * **/
var Window = {
   showConfirm:function(text, okFunc, cancelFunc) {	
		pop({text:text},function(){
			if(typeof(okFunc)=='function') {
				(okFunc)();
			}
	    },function(){
	    	if(typeof(cancelFunc)=='function') {
	    		(cancelFunc)();
	    	}
	    });
	},
	/**错误提示窗口**/
    showError: function(text, okFunc, timeout){
		pop({text:text },0,function(){
			if(typeof(okFunc)=='function') {
				(okFunc)();
			}		
		});
		this.closeShower(timeout);
	},
	/**关闭窗口**/
	closeShower: function(timeout) {		
		if (!timeout) {
			timeout = 2000;
		} else if (timeout == -1){
			return;
		}
		
		setTimeout(function(){
			Window.closingShower()},
		timeout);		
	},
	 closingShower:function(){
		$('#_overlay').remove();
		$('#popup').remove();
	},
	/**成功提示窗口**/
	showSuccess: function(text, okFunc, timeout, url){
		pop({text:text},1,function(){
			if(typeof(okFunc)=='function') {
				(okFunc)();
			}
		});
		if (!timeout) {
			timeout = 1200;
		}
		this.closeShower(timeout);
		if (url){
			setTimeout(function(){location.href = url;}, timeout);
		}
	},
	showWindow: function(title, text, width, height){
		if(!title) {title = '';}
		if(!text) {text = '';}
	    if (!width || width < 1) {
	    	width = 480;
	    }
	    if (!height || height < 1) {
	    	height = 0;
	    }
		$(document.body).popup( $.extend({
			//buttons: {},
			iframe: false,
			type: 9,
			width: width,
			height: height
		},{text :  text, title : title}) );
	},
	showFrameWindow: function(title, url, width, height) {
	    if (!width || width < 1) {
	    	width = 480;
	    }
	    if (!height || height < 1) {
	    	height = 1;
	    }
	    $(document.body).popup( $.extend({
			//buttons: {},
			iframe: true,
			type: 9,
			width: width,
			height: height
		}, {url : url , title : title}) );
	},
	/**
	 * 操作结果
	 * @successTit:operationCode > 0  操作成功的提示
	 * @failreTit:operationCode == 0失败的提示
	 * ignoredTit:operationCode < 0的提示
	 */
	showResult:function(operationCode, successTit, failureTit, ignoredTit, url){
		    if (operationCode >  0){
			   Window.showSuccess(successTit, null, null, url);
		   }
		   else if (operationCode == 0 ) {
			   Window.showError(failureTit, null, null, url);
		   }
		   else {
			   Window.showSuccess(ignoredTit, null, null, url);
		   }
	}
}
/**
 * 提示
 */
Window.tip = {
	/**
	 * target:提示的对象
	 * msg:提示信息
	 */
	error:function(target, msg){
	   this.show(target, msg, false) 
    },	
    clear:function(target){
    	$('#' + target).html('');
    },
    success: function(target, msg) {
    	this.show(target, msg, true);
    },
    show:function(target, msg, type){
    	var css = type? 'success':'error';
    	var t = [];
    	t.push('<span class="');
    	t.push(css);
    	t.push('">');
    	t.push(msg);
    	t.push('</span>');
    	$('#' + target).html(t.join(''));
    }
}
Language = {
	isChinese: function(temp){
		return temp.test(/[\u4e00-\u9fa5]/);
	},
	/**
	 * 是不是中国名字
	 */
	isChineseName:function(realname){
		return /[\u4e00-\u9fa5]{2,5}$/.test(realname);
	}

}
/**
 * 图片预加载
 * 
 */
var MM = {
		swapImgRestore:function(){//v3.0
		   var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;	
		},
		preloadImages: function() {//v3.0
		  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
		    var i,j=d.MM_p.length,a=this.preloadImages.arguments; for(i=0; i<a.length; i++)
		    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}		
		},
		findObj: function(n, d) { //v4.01
		  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=this.findObj(n,d.layers[i].document);
		  if(!x && d.getElementById) x=d.getElementById(n); return x;
		},
		swapImage: function() { //v3.0
		  var i,j=0,x,a=this.swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
		   if ((x=this.findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
		}
}
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/**
 * 设置cookie值 
 * @param name  ：cookie名称
 * @param value :cookie值
 * @return
 */
function setCookie(name, value){
	var expdate = new Date();
	var argv = setCookie.arguments;
	var argc = setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	if(expires!=null) expdate.setTime(expdate.getTime() + ( expires * 1000 ));
	document.cookie = name + "=" + escape (value) +((expires == null) ? "" : ("; expires="+ expdate.toGMTString()))
	+((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain))
	+((secure == true) ? "; secure" : "");
}
/**
 * 
 * @param offset
 * @return
 */
function getCookieVal (offset){
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
/**
 * 取cookie
 * @param name:cookie名称
 */	
function getCookie(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 getCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
	if (i == 0) break;
	}
	return null;
}
/**
 * 删除cookie
 * @param name:cookie名称
 */
function delCookie(name){
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = getCookie (name);
	document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString();
}

