/**
 * 106云盘自动发卡平台网盘系统
 * ============================================================================
 * 版权所有 2016-2028 扎兰屯市姝妍计算机服务有限公司，并保留所有权利。
 * 网站地址: http://www.106ym.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 */
window.onerror=function(){return true;}
if(typeof(root)=='undefined'){
	root='http://static.523w.cn';
}
if(typeof(host)=='undefined'){
	host=window.location.host;
}
/**
 * 引入mui.picker插件
 */
try{
	if(jQuery("[data-picker],[data-area]").length>0){
		document.write(unescape('%3Clink rel="stylesheet" type="text/css" href="'+root+'/css/mui/3.7.0/css/mui.picker.min.css" /%3E'));
		document.write(unescape('%3Cscript type="text/javascript" src="'+root+'/css/mui/3.7.0/js/mui.picker.min.js"%3E%3C/script%3E'));
	}
}catch(e){
	//TODO handle the exception
}

/**
 * 处理表单焦点，添加class="blur"避免弹出输入框
 */
try{
	mui(document).on("tap",".blur",function () {
		document.activeElement.blur();
	});
}catch(e){
	//TODO handle the exception
}
/**
 * 弹出列表，单选
 * @param {String} menu 菜单jq选择器 .xiangmu
 * @param {String} text 返回文字显示区域jq选择器 .mui-media-body
 * @param {String} id 返回值（id）表单名jq选择器 id
 * @param {String} title 返回值（文本）表单名jq选择器  title
 * @param {Function} callback 回调函数,函数参数{id,title}
 * @example data-radio='{menu:".xiangmu",text:".mui-media-body",id:"id",title:"title",callback:search}'
 */
try{
	mui(document).on("tap", "[data-radio]", function() {
		var the = jQuery(this);
		dataRadioThe=the;
		var opts = the.attr("data-radio") ? the.attr("data-radio") : "{}";
		opts = eval("(" + opts + ")");
		var menu=typeof(opts.menu)!="undefined"?jQuery(opts.menu):the.closest('.radio').find('.radio-menu');
		var length = menu.find('li').length;
		menu.find('ul').css({
			"height": length * 40 + 'px'
		});
		menu.show();
	});
	mui(document).on("tap", ".radio-menu li", function() {
		var the = dataRadioThe;
		var $this = jQuery(this);
		var opts = the.attr("data-radio") ? the.attr("data-radio") : "{}";
		opts = eval("(" + opts + ")");
		var menu=typeof(opts.menu)!="undefined"?jQuery(opts.menu):the.closest('.radio').find('.radio-menu');
		$this.find('input').prop('checked',true);
		if (opts.id) {
			jQuery('[name="'+opts.id+'"]').val($this.find('input').val());
		}
		if (opts.title) {
			jQuery('[name="'+opts.title+'"]').val($this.find('label').html());
		}
		if (opts.text) {
			jQuery(opts.text).html($this.find('label').html());
		}else{
			the.html($this.find('label').html());
		}
		if(typeof(opts.callback) == "function") {
			var redata={
				id:$this.find('input').val(),
				title:$this.find('label').html()
			};
			opts.callback(redata);
		}
		menu.fadeOut('fast');
	});
}catch(e){
	//TODO handle the exception
}
/**
 * 数组扩展,返回数组下标
 * @param {string} val 数组值
 * @return {int} 返回数组下标
 */
Array.prototype.indexOf = function(val) {
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) {
			return i;
		}
	}
	return -1;
};
/**
 * 删除指定数组元素
 * @param {array} arr 需要操作的数组
 * @param {string} val 需要删除的元素的值
 */
try{
	function array_remove(arr, val) {
		var index = arr.indexOf(val);
		arr.splice(index, 1);
		return arr;
	}
}catch(e){
	//TODO handle the exception
}
/**
 * 判断值是否包含在数组之内
 * @param {array} arr 待查询的数组
 * @param {string} search 查询的值
 * @return {boolean} 布尔值
 */
try{
	function in_array(search,arr) {
		for (var i = 0; i < arr.length; i++) {
			if (arr[i].toString() == search) {
				return true;
			}
		}
		return false;
	}
}catch(e){
	//TODO handle the exception
}
/**
 * angular 初始化
 */
try {
	//创建moudle1
	myAngular = angular.module('app', []);
	//创建控制器
	myAngular.controller("myController", function($scope, $http) {});
	//页面加载完成后,再加载模块
	angular.element(document).ready(function() {
		jQuery(".ng_hide").removeClass('ng_hide');
		angular.bootstrap(jQuery('html'), ["app"]);
		scope = angular.element(jQuery("body")).scope();
	});
	//解析html
	myAngular.filter('html', function($sce) {
		return function(text) {
			return $sce.trustAsHtml(text);
		}
	})
	//价格过滤器(保留两位小数)
	myAngular.filter('price', function() {
		return function(x) {
			var f_x = parseFloat(x);
			var f_x = Math.round(x * 100) / 100;
			var s_x = f_x.toString();
			var pos_decimal = s_x.indexOf('.');
			if (pos_decimal < 0) {
				pos_decimal = s_x.length;
				s_x += '.';
			}
			while (s_x.length <= pos_decimal + 2) {
				s_x += '0';
			}
			return s_x;
		}
	});
	//日期过滤器
	myAngular.filter('date', function() {
		return function(x) {
			x = x * 1000;
			var myDate = new Date(x);
			var Y = myDate.getFullYear();
			var m = (myDate.getMonth() + 1)<10?'0'+(myDate.getMonth() + 1):myDate.getMonth() + 1;
			var d = myDate.getDate()<10?'0'+myDate.getDate():myDate.getDate();
			var H = myDate.getHours()<10?'0'+myDate.getHours():myDate.getHours();
			var i = myDate.getMinutes()<10?'0'+myDate.getMinutes():myDate.getMinutes();
			var s = myDate.getSeconds()<10?'0'+myDate.getSeconds():myDate.getSeconds();
			return arguments[1].replace('Y', Y).replace('m', m).replace('d', d).replace('H', H).replace('i', i).replace('s', s);
		}
	});
} catch (e) {}



/**
 * 数据请求地址
 * @example  U('Admin/s', "&x=1&b=2")
 * @param {String} arguments[0] 模型控制器及方法，模型若省略则默认是Mobile
 * @param {String} arguments[1] 附加参数
 * @param {String} arguments[2] 入口地址
 * @return {String} 返回地址
 */
try{
	function U() {
		if (arguments[0].indexOf('http://')!=-1) {
			return arguments[0];
		}
		var str1 = arguments[0].split('/');
		if (str1.length == 2) {
			var m = 'Mobile';
			var c = str1[0];
			var a = str1[1];
		} else {
			var m = str1[0];
			var c = str1[1];
			var a = str1[2];
		}
		var str = '?m=' + m + '&c=' + c + '&a=' + a;
		if (arguments[1]) {
			str += arguments[1];
		}
		if (arguments[2]) {
			return arguments[2] + str;
		}
		return host + str;
	}
}catch(e){
	//TODO handle the exception
}


/**
 * 提示信息
 * @example
 * wd_alert({
 * msg:'数据处理中，请稍候...',
 * })
 * @param {Object} obj 各种参数，具体参考函数源码
 */
try{
	function wd_alert(){
		var param=typeof(arguments[0])=="undefined"?{}:arguments[0];
		param.msg=typeof(param.msg)=="undefined"?"数据处理中，请稍候...":param.msg;
		param.width=typeof(param.width)=="undefined"?"200px":param.width;
		param.height=typeof(param.height)=="undefined"?"30px":param.height;
		param.lineheight=typeof(param.lineheight)=="undefined"?param.height:param.lineheight;
		param.background=typeof(param.background)=="undefined"?"#2ecc71":param.background;
		param.color=typeof(param.color)=="undefined"?"#fff":param.color;
		param.timeout=typeof(param.timeout)=="undefined"?2000:param.timeout;
		jQuery("body").find(".wd_alert").remove();
		jQuery('body').prepend('<div class="wd_alert">'+param.msg+'</dov>').find(".wd_alert").css({width:param.width,height:param.height,"line-height":param.lineheight,"text-align":"center",background:param.background,position:"fixed",margin:"auto",left:0,right:0,top:0,"font-size":"14px","z-index":99999999,"color":param.color});
		if(param.timeout>0){
			setTimeout(function () {
				jQuery("body").find(".wd_alert").fadeOut(300,function(){
					jQuery(this).remove();	
				});	
			},param.timeout);
		}	
	}
}catch(e){
	//TODO handle the exception
}



/**
 * js分页
 * @version 1.0.0
 * @param {Object} [] 具体参考源码
 * @example 
 * list({
	url:'{:U("index")}',
	data:{
		row: 20
	},
	callback:function (data) {
		console.log(data.sql);
		scope.list = data.data;
		scope.totalPage = data.totalPage;
		scope.$apply();
		jQuery("#spinner").hide();
		scrollTo(0,0);
	},
	callback_next:function (data) {
		Array.prototype.push.apply(scope.list, data.data);
	}
});
 */
try{
	function list() {
		var opts = arguments[0];
		scope.p = typeof(opts.data.p) != "undefined" ? opts.data.p : 1;
		var next_btn=typeof(opts.data.next_btn) != "undefined" ? opts.data.next_btn : '.tips';
		var cache_name = md5(opts.url + JSON.stringify(opts.data));
		var cache_data = localStorage.getItem(cache_name);
		if(cache_data) {
			cache_data=JSON.parse(cache_data);
			if(typeof(opts.callback) == "function") {
				opts.callback(cache_data);
			}
		}
		mui.ajax(opts.url, {
			data: opts.data,
			dataType: "json",
			type: "post",
			timeout: 10000,
			success: function(data) {
				localStorage.setItem(cache_name,JSON.stringify(data));
				if(typeof(opts.callback) == "function") {
					opts.callback(data);
				}
				if(scope.totalPage > scope.p && opts.cache !== false) {
					scope.p += 1;
					opts.data.p = scope.p;
					mui.ajax(opts.url, {
						data: opts.data,
						dataType: "json",
						type: "post",
						timeout: 10000,
						success: function(data) {
							if(typeof(opts.callback_next) == "function") {
								opts.callback_next(data);
							}
						},
						error: function(e) {
							console.log(JSON.stringify(e));
						}
					});
				}
			},
			error: function(e) {
				console.log(e);
			}
		});
		var next_page=function () {
			//一共就一页
			if(scope.totalPage==1) {
				return false;
			} else if(opts.cache !== false) {
				scope.$apply();
				if(scope.totalPage > scope.p) {
					scope.p += 1;
					opts.data.p = scope.p;
					mui.ajax(opts.url, {
						data: opts.data,
						dataType: "json",
						type: "post",
						timeout: 10000,
						success: function(data) {
							if(typeof(opts.callback_next) == "function") {
								opts.callback_next(data);
							}
						},
						error: function() {
							console.log(JSON.stringify(e));
						}
					});
				}
			} else if(scope.totalPage > scope.p) {
				scope.p += 1;
				opts.data.p = scope.p;
				mui.ajax(opts.url, {
					data: opts.data,
					dataType: "json",
					type: "post",
					timeout: 10000,
					success: function(data) {
						if(typeof(opts.callback_next) == "function") {
							opts.callback_next(data);
						}
					},
					error: function() {
						console.log(JSON.stringify(e));
					}
				});
			}
		}
		jQuery(next_btn).on('click', function() {
			next_page();
		}).on('scrollin', function() {
			next_page();
		});
	}
}catch(e){
	//TODO handle the exception
}



/*微信相关*/


/**
 * 企业微信通讯录选择
 * @param {String} name 用户昵称 张三
 * @param {String} id 用户名 zhangsan
 * @param {Function} callback 回调函数
 * @param {String} fromDepartmentId -1表示打开的通讯录从自己所在部门开始展示, 0表示从最上层开始
 * @param {String} mode 选择模式，single表示单选，multi表示多选
 * @param {String} type "department、user" 选择限制类型，指定department、user中的一个或者多个
 * @param {String} selectedDepartmentIds "2,3" 已选部门ID列表
 * @param {String} selectedUserIds "4,5" 已选用户ID列表
 */
mui(document).on("tap", "[data-wxqy-linkman]", function() {
	var the = jQuery(this);
	var opts = the.attr("data-wxqy-linkman") ? the.attr("data-wxqy-linkman") : "{}";
	opts = eval("(" + opts + ")");
	var fromDepartmentId=typeof(opts.fromDepartmentId)!="undefined"?opts.fromDepartmentId:0;
	var mode=typeof(opts.mode)!="undefined"?opts.mode:'single';
	var type=typeof(opts.type)!="undefined"?opts.type.split(','):["user"];
	wx.invoke("selectEnterpriseContact", {
		"fromDepartmentId": fromDepartmentId,
		"mode": mode,
		"type": type,
		"selectedDepartmentIds": [],
		"selectedUserIds": []
	}, function(res) {
		if(typeof(res.result) == 'string') {
            res.result = JSON.parse(res.result);
        }
		jQuery('[name="' + opts.id + '"]').val(res.result.userList[0].id);
		jQuery('[name="' + opts.name + '"]').val(res.result.userList[0].name);
		if (res.result.userList.length>1) {
			the.html(res.result.userList[0].name+'...('+res.result.userList.length+')');
		}else{
			the.html(res.result.userList[0].name);
		}
		if (typeof(opts.callback)=="function") {
			opts.callback(res); 
		}
	});
});

/**
 * @description 微信图片预览
 * @time 2017-09-10 21:42
 */
try{
	mui(document).on("tap","[data-wx-preview] img",function () {
		var the=jQuery(this).closest('[data-wx-preview]');
		var $this=jQuery(this);
	    wx.previewImage({
		    current:$this.data('url'),
		    urls: the.data('wx-preview')
		});        
	});
}catch(e){
	//TODO handle the exception
}
//上传
mui(document).on("tap","[data-upload-wx] .btn_upload",function () {
	var the=jQuery(this).closest('[data-upload-wx]');
	var $this=jQuery(this);
	var opts = the.attr("data-upload-wx") ? the.attr("data-upload-wx") : "{}";
	opts = eval("(" + opts + ")");
	if (typeof(the.data('imgs_id'))=="undefined") {
		the.data('imgs_id',[]);
	}
	if (typeof(the.data('imgs_url'))=="undefined") {
		the.data('imgs_url',[]);
	}
	var btn_upload=typeof(opts.btn_upload)!="undefined"?opts.btn_upload:'.btn_upload';//上传按钮
	var btn_upload_del=typeof(opts.btn_upload_del)!="undefined"?opts.btn_upload_del:'.btn_upload_del';//删除按钮
	console.log(2);
	var width=typeof(opts.width)!="undefined"?opts.width:the.width()/3-10;
	width=Math.round(width);
	var tpl_del=typeof(opts.tpl_del)!="undefined"?opts.tpl_del:'<div class="mask" style=" height:'+width+'px; line-height: '+width+'px;">点击删除</div></div>';
	var tpl_item=typeof(opts.tpl_item)!="undefined"?opts.tpl_item:'<li class="upload_before upload-wx-items"><div style="height:'+width+'px; background: url(bgurl) no-repeat center center; background-size: cover;"><div class="mask" style=" height:'+width+'px; line-height: '+width+'px;">请稍候</div></div></li>';//模板
	
	
	var count = typeof(opts.count)!="undefined"?opts.count:9;//选择图片个数限制
	var sizeType = typeof(opts.sizeType)!="undefined"?opts.sizeType:['original','compressed']; //原图还是压缩图
	var sourceType = typeof(opts.sourceType)!="undefined"?opts.sourceType:['album', 'camera']; //来源是相册还是相机
	
	wx.chooseImage({
		count: count, 
		sizeType: sizeType, // 可以指定是原图还是压缩图，默认二者都有
		sourceType: sourceType, // 可以指定来源是相册还是相机，默认二者都有
		success: function(res) {
			var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
			for(var i = 0; i < localIds.length; i++) {
				//预览
				$this.before(tpl_item.replace('bgurl',localIds[i]));
			}
			wx_uploader(localIds,the);
		}
	});
});
//标记删除
mui(document).on("tap","[data-upload-wx] .btn_upload_del",function () {
	var the=jQuery(this).closest('[data-upload-wx]');
	var $this=jQuery(this);
	var opts = the.attr("data-upload-wx") ? the.attr("data-upload-wx") : "{}";
	opts = eval("(" + opts + ")");
	var width=typeof(opts.width)!="undefined"?opts.width:the.width()/3-10;
	width=Math.round(width);
	var tpl_del=typeof(opts.tpl_del)!="undefined"?opts.tpl_del:'<div class="mask" style=" height:'+width+'px; line-height: '+width+'px;">点击删除</div></div>';
	if (the.find('.mask').length>0) {
		$this.find('p').html('删除图片');
		the.find('.mask').remove();
	}else{
		$this.find('p').html('取消删除');
		$this.siblings('.upload-wx-items').find('div').append(tpl_del); 
	}
});
//预览与删除
mui(document).on("tap","[data-upload-wx] .upload-wx-items",function () {
	var the=jQuery(this).closest('[data-upload-wx]');
	var $this=jQuery(this);
	var opts = the.attr("data-upload-wx") ? the.attr("data-upload-wx") : "{}";
	opts = eval("(" + opts + ")");
	var name=typeof(opts.name)!="undefined"?opts.name:'imgs';
	if ($this.find('.mask').length>0) {
		the.data('imgs_id',array_remove(the.data('imgs_id'),$this.data('id')));
		the.data('imgs_url',array_remove(the.data('imgs_url'),$this.data('url')));
		jQuery('[name="'+name+'"]').val(the.data('imgs_id').join(','));
		$this.remove();
		return false;
	}
	wx.previewImage({
	    current:$this.data('url'),
	    urls: the.data('imgs_url')
	});
});
var wx_uploader = function(localIds,the) {
	var localId = localIds.shift();
	var data_post=new Object();
	var opts = the.attr("data-upload-wx") ? the.attr("data-upload-wx") : "{}";
	opts = eval("(" + opts + ")");
	var upload_url=typeof(opts.upload_url)!="undefined"?opts.upload_url:'/index.php?s=/Pub/Upload/upload_wx';
	var static_url=typeof(opts.static_url)!="undefined"?opts.static_url:'';
	var static_param=typeof(opts.static_param)!="undefined"?opts.static_param:'';
	var name=typeof(opts.name)!="undefined"?opts.name:'imgs';
	data_post.access_token=opts.access_token;
	if (typeof(opts.api_url)!="undefined") {
		data_post.api_url=opts.api_url;
	}
	if (typeof(opts.data)!="undefined") {
		for(var k in opts.data){
			data_post[k]=opts.data[k]
		}
	}
	wx.uploadImage({
		localId: localId,
		isShowProgressTips: 0,
		success: function(res) {
			var serverId = res.serverId; // 返回图片的服务器端ID
			data_post.media_id=serverId;
			jQuery.post(
				upload_url,
				data_post,
				function(data) {
					var item=the.find('.upload_before').eq(0);
					item.data('id',data.id);
					if (opts.water==1) {
						static_param+='|watermark/1/image/'+data.water+'/dissolve/100/gravity/SouthWest/dx/0/dy/0|imageslim';
					}
					item.data('url',static_url+data.path+static_param);
					item.removeClass('upload_before').find('.mask').remove();
					the.data('imgs_id').push(data.id);
					the.data('imgs_url').push(static_url+data.path+static_param);
					jQuery('[name="'+name+'"]').val(the.data('imgs_id').join(','));
					if(localIds.length > 0) {
						wx_uploader(localIds,the);
					}
				}
			);
			
		}
	});
};

/**
 * md5加密函数，和php同步
 * @param {String} 待加密字符串
 */
function md5(string){
    function md5_RotateLeft(lValue, iShiftBits) {
            return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }
    function md5_AddUnsigned(lX,lY){
            var lX4,lY4,lX8,lY8,lResult;
            lX8 = (lX & 0x80000000);
            lY8 = (lY & 0x80000000);
            lX4 = (lX & 0x40000000);
            lY4 = (lY & 0x40000000);
            lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
            if (lX4 & lY4) {
                    return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
            }
            if (lX4 | lY4) {
                    if (lResult & 0x40000000) {
                            return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
                    } else {
                            return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
                    }
            } else {
                    return (lResult ^ lX8 ^ lY8);
            }
    }         
    function md5_F(x,y,z){
            return (x & y) | ((~x) & z);
    }
    function md5_G(x,y,z){
            return (x & z) | (y & (~z));
    }
    function md5_H(x,y,z){
            return (x ^ y ^ z);
    }
    function md5_I(x,y,z){
            return (y ^ (x | (~z)));
    }
    function md5_FF(a,b,c,d,x,s,ac){
            a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_F(b, c, d), x), ac));
            return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    }; 
    function md5_GG(a,b,c,d,x,s,ac){
            a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_G(b, c, d), x), ac));
            return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_HH(a,b,c,d,x,s,ac){
            a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_H(b, c, d), x), ac));
            return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    }; 
    function md5_II(a,b,c,d,x,s,ac){
            a = md5_AddUnsigned(a, md5_AddUnsigned(md5_AddUnsigned(md5_I(b, c, d), x), ac));
            return md5_AddUnsigned(md5_RotateLeft(a, s), b);
    };
    function md5_ConvertToWordArray(string) {
            var lWordCount;
            var lMessageLength = string.length;
            var lNumberOfWords_temp1=lMessageLength + 8;
            var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
            var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
            var lWordArray=Array(lNumberOfWords-1);
            var lBytePosition = 0;
            var lByteCount = 0;
            while ( lByteCount < lMessageLength ) {
                    lWordCount = (lByteCount-(lByteCount % 4))/4;
                    lBytePosition = (lByteCount % 4)*8;
                    lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
                    lByteCount++;
            }
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
            lWordArray[lNumberOfWords-2] = lMessageLength<<3;
            lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
            return lWordArray;
    }; 
    function md5_WordToHex(lValue){
            var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
            for(lCount = 0;lCount<=3;lCount++){
                    lByte = (lValue>>>(lCount*8)) & 255;
                    WordToHexValue_temp = "0" + lByte.toString(16);
                    WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
            }
            return WordToHexValue;
    };
    function md5_Utf8Encode(string){
            string = string.replace(/\r\n/g,"\n");
            var utftext = ""; 
            for (var n = 0; n < string.length; n++) {
                    var c = string.charCodeAt(n); 
                    if (c < 128) {
                            utftext += String.fromCharCode(c);
                    }else if((c > 127) && (c < 2048)) {
                            utftext += String.fromCharCode((c >> 6) | 192);
                            utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                            utftext += String.fromCharCode((c >> 12) | 224);
                            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                            utftext += String.fromCharCode((c & 63) | 128);
                    } 
            } 
            return utftext;
    }; 
    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;
    string = md5_Utf8Encode(string);
    x = md5_ConvertToWordArray(string); 
    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; 
    for (k=0;k<x.length;k+=16) {
            AA=a; BB=b; CC=c; DD=d;
            a=md5_FF(a,b,c,d,x[k+0], S11,0xD76AA478);
            d=md5_FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
            c=md5_FF(c,d,a,b,x[k+2], S13,0x242070DB);
            b=md5_FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
            a=md5_FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
            d=md5_FF(d,a,b,c,x[k+5], S12,0x4787C62A);
            c=md5_FF(c,d,a,b,x[k+6], S13,0xA8304613);
            b=md5_FF(b,c,d,a,x[k+7], S14,0xFD469501);
            a=md5_FF(a,b,c,d,x[k+8], S11,0x698098D8);
            d=md5_FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
            c=md5_FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
            b=md5_FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
            a=md5_FF(a,b,c,d,x[k+12],S11,0x6B901122);
            d=md5_FF(d,a,b,c,x[k+13],S12,0xFD987193);
            c=md5_FF(c,d,a,b,x[k+14],S13,0xA679438E);
            b=md5_FF(b,c,d,a,x[k+15],S14,0x49B40821);
            a=md5_GG(a,b,c,d,x[k+1], S21,0xF61E2562);
            d=md5_GG(d,a,b,c,x[k+6], S22,0xC040B340);
            c=md5_GG(c,d,a,b,x[k+11],S23,0x265E5A51);
            b=md5_GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
            a=md5_GG(a,b,c,d,x[k+5], S21,0xD62F105D);
            d=md5_GG(d,a,b,c,x[k+10],S22,0x2441453);
            c=md5_GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
            b=md5_GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
            a=md5_GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
            d=md5_GG(d,a,b,c,x[k+14],S22,0xC33707D6);
            c=md5_GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
            b=md5_GG(b,c,d,a,x[k+8], S24,0x455A14ED);
            a=md5_GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
            d=md5_GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
            c=md5_GG(c,d,a,b,x[k+7], S23,0x676F02D9);
            b=md5_GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
            a=md5_HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
            d=md5_HH(d,a,b,c,x[k+8], S32,0x8771F681);
            c=md5_HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
            b=md5_HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
            a=md5_HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
            d=md5_HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
            c=md5_HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
            b=md5_HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
            a=md5_HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
            d=md5_HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
            c=md5_HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
            b=md5_HH(b,c,d,a,x[k+6], S34,0x4881D05);
            a=md5_HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
            d=md5_HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
            c=md5_HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
            b=md5_HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
            a=md5_II(a,b,c,d,x[k+0], S41,0xF4292244);
            d=md5_II(d,a,b,c,x[k+7], S42,0x432AFF97);
            c=md5_II(c,d,a,b,x[k+14],S43,0xAB9423A7);
            b=md5_II(b,c,d,a,x[k+5], S44,0xFC93A039);
            a=md5_II(a,b,c,d,x[k+12],S41,0x655B59C3);
            d=md5_II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
            c=md5_II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
            b=md5_II(b,c,d,a,x[k+1], S44,0x85845DD1);
            a=md5_II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
            d=md5_II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
            c=md5_II(c,d,a,b,x[k+6], S43,0xA3014314);
            b=md5_II(b,c,d,a,x[k+13],S44,0x4E0811A1);
            a=md5_II(a,b,c,d,x[k+4], S41,0xF7537E82);
            d=md5_II(d,a,b,c,x[k+11],S42,0xBD3AF235);
            c=md5_II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
            b=md5_II(b,c,d,a,x[k+9], S44,0xEB86D391);
            a=md5_AddUnsigned(a,AA);
            b=md5_AddUnsigned(b,BB);
            c=md5_AddUnsigned(c,CC);
            d=md5_AddUnsigned(d,DD);
    }
    return (md5_WordToHex(a)+md5_WordToHex(b)+md5_WordToHex(c)+md5_WordToHex(d)).toLowerCase();
}



/**
 * js背景水印
 * @param {Obj} 设置
 */
function watermark(settings) {
	//默认设置  
	var defaultSettings = {
		watermark_txt: "text",
		watermark_x: 10, //水印起始位置x轴坐标  
		watermark_y: 100, //水印起始位置Y轴坐标  
		watermark_rows: 0, //水印行数  
		watermark_cols: 0, //水印列数  
		watermark_x_space: 30, //水印x轴间隔  
		watermark_y_space: 30, //水印y轴间隔  
		watermark_color: '#000000', //水印字体颜色  
		watermark_alpha: 0.1, //水印透明度  
		watermark_fontsize: '14px', //水印字体大小  
		watermark_font: '微软雅黑', //水印字体  
		watermark_width: 100, //水印宽度  
		watermark_height: 40, //水印长度  
		watermark_angle: 15, //水印倾斜度数  ,
		watermark_id:'', //加水印的对象id
	};
	//采用配置项替换默认值，作用类似jquery.extend  
	if(arguments.length === 1 && typeof arguments[0] === "object") {
		var src = arguments[0] || {};
		for(key in src) {
			if(src[key] && defaultSettings[key] && src[key] === defaultSettings[key])
				continue;
			else if(src[key])
				defaultSettings[key] = src[key];
		}
	}

	var oTemp = document.createDocumentFragment();
	
	if (defaultSettings.watermark_id=='') {
		//获取页面最大宽度  
		var page_width = Math.max(document.body.scrollWidth, document.body.clientWidth);
		//获取页面最大长度  
		var page_height = Math.max(document.body.scrollHeight, document.body.clientHeight);
	}else{
		//获取页面最大宽度  
		var page_width = Math.max(document.getElementById(defaultSettings.watermark_id).scrollWidth, document.getElementById(defaultSettings.watermark_id).clientWidth);
		//获取页面最大长度  
		var page_height = Math.max(document.getElementById(defaultSettings.watermark_id).scrollHeight, document.getElementById(defaultSettings.watermark_id).clientHeight);
	}
	

	//如果将水印列数设置为0，或水印列数设置过大，超过页面最大宽度，则重新计算水印列数和水印x轴间隔  
	if(defaultSettings.watermark_cols == 0 || 　　　　(parseInt(defaultSettings.watermark_x　　　　 + defaultSettings.watermark_width * defaultSettings.watermark_cols　　　　 + defaultSettings.watermark_x_space * (defaultSettings.watermark_cols - 1))　　　　 > page_width)) {
		defaultSettings.watermark_cols = 　　　　　　parseInt((page_width　　　　　　　　　　 - defaultSettings.watermark_x　　　　　　　　　　 + defaultSettings.watermark_x_space)　　　　　　　　　　 / (defaultSettings.watermark_width　　　　　　　　　　 + defaultSettings.watermark_x_space));
		defaultSettings.watermark_x_space = 　　　　　　parseInt((page_width　　　　　　　　　　 - defaultSettings.watermark_x　　　　　　　　　　 - defaultSettings.watermark_width　　　　　　　　　　 * defaultSettings.watermark_cols)　　　　　　　　　　 / (defaultSettings.watermark_cols - 1));
	}
	//如果将水印行数设置为0，或水印行数设置过大，超过页面最大长度，则重新计算水印行数和水印y轴间隔  
	if(defaultSettings.watermark_rows == 0 || 　　　　(parseInt(defaultSettings.watermark_y　　　　 + defaultSettings.watermark_height * defaultSettings.watermark_rows　　　　 + defaultSettings.watermark_y_space * (defaultSettings.watermark_rows - 1))　　　　 > page_height)) {
		defaultSettings.watermark_rows = 　　　　　　parseInt((defaultSettings.watermark_y_space　　　　　　　　　　　 + page_height - defaultSettings.watermark_y)　　　　　　　　　　　 / (defaultSettings.watermark_height + defaultSettings.watermark_y_space));
		defaultSettings.watermark_y_space = 　　　　　　parseInt((page_height　　　　　　　　　　 - defaultSettings.watermark_y　　　　　　　　　　 - defaultSettings.watermark_height　　　　　　　　　　 * defaultSettings.watermark_rows)　　　　　　　　　 / (defaultSettings.watermark_rows - 1));
	}
	var x;
	var y;
	for(var i = 0; i < defaultSettings.watermark_rows; i++) {
		y = defaultSettings.watermark_y + (defaultSettings.watermark_y_space + defaultSettings.watermark_height) * i;
		for(var j = 0; j < defaultSettings.watermark_cols; j++) {
			x = defaultSettings.watermark_x + (defaultSettings.watermark_width + defaultSettings.watermark_x_space) * j;

			var mask_div = document.createElement('div');
			mask_div.id = 'mask_div' + i + j;
			mask_div.appendChild(document.createTextNode(defaultSettings.watermark_txt));
			//设置水印div倾斜显示  
			mask_div.style.webkitTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
			mask_div.style.MozTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
			mask_div.style.msTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
			mask_div.style.OTransform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
			mask_div.style.transform = "rotate(-" + defaultSettings.watermark_angle + "deg)";
			mask_div.style.visibility = "";
			mask_div.style.position = "absolute";
			mask_div.style.left = x + 'px';
			mask_div.style.top = y + 'px';
			mask_div.style.overflow = "hidden";
			mask_div.style.zIndex = "9999";
			//mask_div.style.border="solid #eee 1px";  
			mask_div.style.opacity = defaultSettings.watermark_alpha;
			mask_div.style.fontSize = defaultSettings.watermark_fontsize;
			mask_div.style.fontFamily = defaultSettings.watermark_font;
			mask_div.style.color = defaultSettings.watermark_color;
			mask_div.style.textAlign = "center";
			mask_div.style.width = defaultSettings.watermark_width + 'px';
			mask_div.style.height = defaultSettings.watermark_height + 'px';
			mask_div.style.display = "block";
			oTemp.appendChild(mask_div);
		};
	};
	if (defaultSettings.watermark_id=='') {
		document.body.appendChild(oTemp);
	}else{
		document.getElementById(defaultSettings.watermark_id).appendChild(oTemp);
	}
	
}


/**
 * 模仿PHP的strtotime()函数
 * strtotime('2012-07-27 12:43:43') OR strtotime('2012-07-27')
 * @return 时间戳
 */
function strtotime(str){
    var _arr = str.split(' ');
    var _day = _arr[0].split('-');
    _arr[1] = (_arr[1] == null) ? '0:0:0' :_arr[1];
    var _time = _arr[1].split(':');
    for (var i = _day.length - 1; i >= 0; i--) {
        _day[i] = isNaN(parseInt(_day[i])) ? 0 :parseInt(_day[i]);
    };
    for (var i = _time.length - 1; i >= 0; i--) {
        _time[i] = isNaN(parseInt(_time[i])) ? 0 :parseInt(_time[i]);
    };
    var _temp = new Date(_day[0],_day[1]-1,_day[2],_time[0],_time[1],_time[2]);
    return _temp.getTime() / 1000;
}


/**
 * 模仿PHP的date()函数
 * strtotime('Y-m-d H:i:s');
 * @param format 只支持 'Y-m-d H:i:s','Y-m-d','H:i:s' 三种调用方式
 * @param time 为空时，取当前时间
 * @return 日期格式化的字符串
 */
function date(format,time){
    var _temp = (time != null) ? new Date(time*1000) : new Date();
    var _return = '';

    if(/Y-m-d/.test(format)){
        var _day = [_temp.getFullYear(),addzero(1 + _temp.getMonth()),addzero(_temp.getDate())];
        _return = _day.join('-');
    }
    if(/H:i:s/.test(format)){
        var _time = [addzero(_temp.getHours()),addzero(_temp.getMinutes()),addzero(_temp.getSeconds())];
        _return += ' ' +_time.join(':');
    }
    return _return;
    function addzero(i){
        if(i<=9){
            return '0' + i;
        }else{
            return i;
        }
    }
}