Namespace = new Object();
Namespace.register = function(fullNS)
{
	var nsArray = fullNS.split('.');
	var sEval = "";
	var sNS = "";
	var count = nsArray.length;
	for (var i = 0; i < count; i++)
	{
		if (i != 0) sNS += ".";
		sNS += nsArray[i];
		sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
	}
	if (sEval != "") eval(sEval);
};
Namespace.register("MMT.CONF");
Namespace.register("MMT.DATA");
Namespace.register("MMT.FN");
Namespace.register("MMT.EUI");
Namespace.register("MMT.ACT");
Namespace.register("MMT.MSG");
Namespace.register("MMT.DTY");
$(function() {
	MMT.DATA = {};
	MMT.DTY = {};
	MMT.MSG = {
		show:function(content,title){
			$.messager.show({
				title:title||'操作提示',
				msg: content,
				showType:'slide',
				style:{
					right:'',
					top:document.body.scrollTop+document.documentElement.scrollTop,
					bottom:''
				}
			});
		},
		confirm:function(content,title){
			$.messager.confirm(title||'操作提醒', content, function(r){
				return r;
			});
		},
		alert:function(content,title,icon){
			$.messager.alert(title||'操作警告',content,icon||'warning');
		},
		content:function(content,title,width,height){
			if (width) {
				$.messager.show({
					title:title||'信息',
					width:width,
					height:height,
					timeout:0,
					msg:'<div style="width:100%;height:100%;overflow:auto;">'+content+'</div>',
					style:{
						'word-break':'break-word',
						'white-space':'pre-wrap',
						right:'',
						bottom:''
					}
				});
			}else{
				$.messager.show({
					title:title||'信息',
					width:'auto',
					height:'auto',
					timeout:0,
					msg:content,
					style:{
						'word-break':'break-word',
						'white-space':'pre-wrap',
						right:'',
						bottom:''
					}
				});
			};
		},
		webuploaderMsg:function(code){
			switch(code){
				case 'Q_EXCEED_NUM_LIMIT':
					MMT.MSG.alert('文件数量超出限定值！');
				break;
				case 'Q_EXCEED_SIZE_LIMIT':
					MMT.MSG.alert('文件大小超出限制！');
				break;
				case 'Q_TYPE_DENIED':
					MMT.MSG.alert('为了保障系统安全，禁止上传该类型的附件！可以压缩成ZIP文件后上传');
				break;
				default:
					MMT.MSG.alert('上传文件重复！');
			}
		},
	};
	MMT.FN = {
		htmlspecialchars:function(str){
			if (!str) {return};
			str = str.replace(/&/g, '&amp;');
			str = str.replace(/</g, '&lt;');
			str = str.replace(/>/g, '&gt;');
			str = str.replace(/"/g, '&quot;');
			str = str.replace(/'/g, '&#039;');
			return str;
		},
		htmlspecialchars_decode:function(str){
			if (!str) {return};
			str = str.replace(/&amp;/g, '&');
			str = str.replace(/&lt;/g, '<');
			str = str.replace(/&gt;/g, '>');
			str = str.replace(/&quot;/g, '"');
			str = str.replace(/&#039;/g, "'");
			return str;
		},
		// 获取选中项id
		getCheckedId:function(contain,type){
			var ids = [];
			if ('datagrid' == type) {
				var checked = $('#' + contain + type).datagrid('getChecked');
				var length = checked.length;
				for (var i = 0; i < length; i++) {
					if (checked[i].id!=0) {
						ids.push(checked[i].id);
					};
				}
			}else if('treegrid' == type){
				var checked = $('#'+contain + type).treegrid('getChecked');
				var length = checked.length;
				for (var i = 0; i < length; i++) {
					if (checked[i].id!=0) {
						ids.push(checked[i].id);
					};
				}
			};
			return ids;
		},
		array2tree:function(data,idFiled,textFiled,parentField,rootItem){
			var idFiled = idFiled||'id';
			var textFiled = textFiled||'text';
			var parentField = parentField||'pid';
			var rootItem = rootItem||false;
			var i,l,treeData = [],tmpMap = [];
			var count = data.length;
			for (i = 0, l = count; i < l; i++) {
				tmpMap[data[i][idFiled]] = data[i];
			}
			for (i = 0, l = count; i < l; i++) {
				if (tmpMap[data[i][parentField]] && data[i][idFiled] != data[i][parentField]) {
					if (!tmpMap[data[i][parentField]]['children'])
						tmpMap[data[i][parentField]]['children'] = [];
					data[i]['text'] = data[i][textFiled];
					tmpMap[data[i][parentField]]['children'].push(data[i]);
				} else {
					data[i]['text'] = data[i][textFiled];
					treeData.push(data[i]);
				}
			}
			if (rootItem) {
				var root = [{
					id:0,
					pid:0,
					text:'根目录',
					level:0,
					children:treeData
				}];
				return root;
			}else{
				return treeData;
			};
		},
		datadict2tree:function(data,rootItem){
			var rootItem = rootItem||false;
			var treeData = [];
			for (key in data){
				if (data[data[key]['pid']] && data[key]['id'] != data[key]['pid']) {
					if (!data[data[key]['pid']]['children'])
						data[data[key]['pid']]['children'] = [];
					data[data[key]['pid']]['children'].push(data[key]);
				} else {
					treeData.push(data[key]);
				}
			}
			if (rootItem) {
				var root = [{
					id:0,
					pid:0,
					text:'根目录',
					level:0,
					children:treeData
				}];
				return root;
			}else{
				return treeData;
			};
		},
		unixtostr:function(unix){
			var timestampNow = Math.round(new Date().getTime()/1000);
			var dif = timestampNow-unix;
			var outPut ="";
			var date = new Date(unix*1000);
			var hours = date.getHours();
			var minutes =date.getMinutes();
			if(hours<10) hours = "0"+hours;
			if(minutes<10) minutes="0"+minutes;
			outPut = date.getFullYear()+ "-" + Number(date.getMonth() + 1)+"-"+date.getDate()+" "+hours+":"+minutes;
			return outPut;
		},
		createTableHeadMenu:function(contain,type){
			var fields;
			if ('treegrid' == type) {
				fields = $('#'+contain+type).datagrid('getColumnFields');
			}else{
				fields = $('#'+contain+type).treegrid('getColumnFields');
			};
			var count = fields.length;
			for(var i=0; i < count; i++){
				var field = fields[i];
				var col = $('#'+contain+type).datagrid('getColumnOption', field);
				if (col.hidden) {
					$('#'+contain+type+'HeadMenu').menu('appendItem', {
						text: col.title,
						name: field,
						iconCls: 'icon-blank'
					});
				}else{
					$('#'+contain+type+'HeadMenu').menu('appendItem', {
						text: col.title,
						name: field,
						iconCls: 'icon-ok'
					});
				};
			}
			return $('#'+contain+type+'HeadMenu').menu();
		},
		renderPic:function(picker,thumbcontainer){
			var uploader = WebUploader.create({
				auto: true,
				swf: MMT.CONF.WebUploader.swf,
				server: MMT.CONF.WebUploader.server,
				pick: picker,
				fileNumLimit:1,
				accept: {
					title: 'Images',
					extensions: 'gif,jpg,jpeg,bmp,png',
					mimeTypes: 'image/*'
				}
			});
			uploader.on( 'error', function(code) {
				MMT.MSG.webuploaderMsg(code);
			});
			uploader.on( 'uploadSuccess', function( file,data ) {
				if (data.status) {
					$(thumbcontainer).textbox('setValue',MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename);
				}else{
					MMT.MSG.alert(data.info);
				};
			});
			uploader.on( 'uploadError', function( file ) {
				MMT.MSG.alert('上传出错');
			});
			uploader.on( 'uploadComplete', function( file ) {
				MMT.MSG.show('上传完成');
			});
		},
		renderPics:function(picker,thumbcontainer){
			var uploader = WebUploader.create({
				auto: true,
				swf: MMT.CONF.WebUploader.swf,
				server: MMT.CONF.WebUploader.server,
				pick: picker,
				accept: {
					title: 'Images',
					extensions: 'gif,jpg,jpeg,bmp,png',
					mimeTypes: 'image/*'
				}
			});
			uploader.on( 'error', function(code) {
				MMT.MSG.webuploaderMsg(code);
			});
			uploader.on( 'uploadError', function( file ) {
				MMT.MSG.alert('上传出错');
			});
			uploader.on( 'uploadSuccess', function( file,data ) {
				if (data.status) {
					var textboxvalue = $(thumbcontainer).textbox('getValue');
					if (textboxvalue) {
						$(thumbcontainer).textbox('setValue',$(thumbcontainer).textbox('getValue')+'\r\n'+MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename+'|'+data.info.name);
					}else{
						$(thumbcontainer).textbox('setValue',MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename+'|'+data.info.name);
					};
				}else{
					MMT.MSG.alert(data.info);
				};
			});
			uploader.on( 'uploadComplete', function( file ) {
				MMT.MSG.show('上传完成');
			});
		},
		renderFile:function(picker,thumbcontainer){
			var uploader = WebUploader.create({
				auto: true,
				swf: MMT.CONF.WebUploader.swf,
				server: MMT.CONF.WebUploader.server,
				pick: picker,
				fileNumLimit:1,
				accept: {
					title: 'File',
					extensions: 'gif,jpg,jpeg,bmp,png,zip,rar,pdf',
					mimeTypes: '*/*'
				}
			});
			uploader.on( 'error', function(code) {
				MMT.MSG.webuploaderMsg(code);
			});
			uploader.on( 'uploadError', function( file ) {
				MMT.MSG.alert('上传出错');
			});
			uploader.on( 'uploadSuccess', function( file,data ) {
				if (data.status) {
					$(thumbcontainer).textbox('setValue',MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename);
				}else{
					MMT.MSG.alert(data.info);
				};
			});
			uploader.on( 'uploadComplete', function( file ) {
				MMT.MSG.show('上传完成');
			});
		},
		renderFiles:function(picker,thumbcontainer){
			var uploader = WebUploader.create({
				auto: true,
				swf: MMT.CONF.WebUploader.swf,
				server: MMT.CONF.WebUploader.server,
				pick: picker,
				accept: {
					title: 'File',
					extensions: 'gif,jpg,jpeg,bmp,png,zip,rar,pdf',
					mimeTypes: '*/*'
				}
			});
			uploader.on( 'error', function(code) {
				MMT.MSG.webuploaderMsg(code);
			});
			uploader.on( 'uploadError', function( file ) {
				MMT.MSG.alert('上传出错');
			});
			uploader.on( 'uploadSuccess', function( file,data ) {
				if (data.status) {
					var textboxvalue = $(thumbcontainer).textbox('getValue');
					if (textboxvalue) {
						$(thumbcontainer).textbox('setValue',$(thumbcontainer).textbox('getValue')+'\r\n'+MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename+'|'+data.info.md5+'|'+data.info.size+'|'+data.info.name);
					}else{
						$(thumbcontainer).textbox('setValue',MMT.CONF.SYS.upload_dir+data.info.savepath+data.info.savename+'|'+data.info.md5+'|'+data.info.size+'|'+data.info.name);
					};
				}else{
					MMT.MSG.alert(data.info);
				};
			});
			uploader.on( 'uploadComplete', function( file ) {
				MMT.MSG.show('上传完成');
			});
		},
	};
	MMT.EUI = {
		// 渲染头部菜单
		fetchheadmenu:function(contain,type){
			if (type == 'datagrid') {
				$('#'+contain+'datagridHeadMenu').menu({
					onClick: function(item){
						if (item.iconCls == 'icon-ok'){
							$('#'+contain+'datagrid').datagrid('hideColumn', item.name);
							$(this).menu('setIcon', {
								target: item.target,
								iconCls: 'icon-empty'
							});
						} else {
							$('#'+contain+'datagrid').datagrid('showColumn', item.name);
							$(this).menu('setIcon', {
								target: item.target,
								iconCls: 'icon-ok'
							});
						}
					}
				});
			} else if (type == 'treegrid') {
				$('#'+contain+'treegridHeadMenu').menu({
					onClick: function(item){
						if (item.iconCls == 'icon-ok'){
							$('#'+contain+'treegrid').treegrid('hideColumn', item.name);
							$(this).menu('setIcon', {
								target: item.target,
								iconCls: 'icon-empty'
							});
						} else {
							$('#'+contain+'treegrid').treegrid('showColumn', item.name);
							$(this).menu('setIcon', {
								target: item.target,
								iconCls: 'icon-ok'
							});
						}
					}
				});
			};
		},
	};
	MMT.ACT = {
		// 异步下载数据
		asyncData:function(url,queryParams,name){
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'JSON',
				data: queryParams||{type: 'alldata'},
				success:function(data){
					if (name == undefined) {
						MMT.DATA = data;
						MMT.MSG.show('成功更新页面缓存！');
					}else{
						MMT.DATA[name] = data; 
						MMT.MSG.show('成功更新页面缓存！');
					};
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					MMT.DATA[name||'temp'] = undefined;
					MMT.MSG.alert('数据请求失败：'+textStatus+' '+errorThrown+'<br />请求地址:'+url+'<br />AJAX请求信息：'+JSON.stringify(this)+'<br /><span style="color:red">如无法解决该问题，请联系MMT官方获取帮助</span>');
				}
			});
		},
		del:function(url,ids,contain,type){
			var str = undefined;
			if ($.isArray(ids)) {str = ids.join();}else{str = ids};
			if (str == '') {
				return false;
			};
			$.messager.confirm('操作提醒','确定将ID为：<br />'+str+'<br />的数据删除？', function(r){
				if (r){
					$.ajax({
						url:url,
						type:'POST',
						data:{
							ids:ids
						},
						dataType:'JSON',
						success:function(data){
							if (!data.status) {
								MMT.MSG.alert(data.info);
							}else if($.isArray(ids)){
								MMT.MSG.show(data.info);
								if ('datagrid' == type) {
									$('#'+contain+type).datagrid('reload');
								}else{
									$('#'+contain+type).treegrid('reload');
								};
							}else{
								MMT.MSG.show('删除成功');
								if ('datagrid' == type) {
									$('#'+contain+type).datagrid('deleteRow',MMT[contain].selectedIndex);
								}else{
									$('#'+contain+type).treegrid('remove',MMT[contain].selectedIndex);
								};
							}
						}
					});
				}
			});
		},
		dels:function(url,contain,type){
			var ids = MMT.FN.getCheckedId(contain,type);
			MMT.ACT.del(url,ids,contain,type);
		},
		status:function(url,ids,value,contain,type){
			if (!$.isEmptyObject(ids)){
				$.ajax({
					url:url,
					type:'POST',
					dataType:'JSON',
					data:{
						ids:ids,
						value:value
					},
					success:function(data){
						if (!data.status) {
							MMT.MSG.alert(data.info);
						}else if($.isArray(ids)){
							MMT.MSG.show(data.info);
							if ('datagrid' == type) {
								$('#'+contain+type).datagrid('reload');
							}else{
								$('#'+contain+type).treegrid('load');
							};
						}else{
							// MMT.MSG.show('修改成功');
							if ('datagrid' == type) {
								$('#'+contain+type).datagrid('updateRow',{
									index:MMT[contain].selectedIndex,
									row:data.info
								});
							}else{
								$('#'+contain+type).treegrid('update',{
									id:MMT[contain].selectedIndex,
									row:data.info
								});
							};
						};
					}
				});
			}
		},
		// 批量改变状态
		statuss:function(url,value,contain,type){
			var ids = MMT.FN.getCheckedId(contain,type);
			MMT.ACT.status(url,ids,value,contain,type);
		},
		// 异步提交
		ajaxPost:function(url,queryParams,fun){
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'JSON',
				data: queryParams||{},
				success:function(data){
					if (fun) {
						fun(data);
					}else{
						if (data.status) {
							if (data.info) {
								MMT.MSG.show(data.info);
							};
						}else{
							MMT.MSG.alert(data.info);
						};
					};
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					MMT.MSG.alert('数据请求失败：'+textStatus+' '+errorThrown+'<br />请求地址:'+url+'<br />AJAX请求信息：'+JSON.stringify(this)+'<br /><span style="color:red">如无法解决该问题，请联系官方获取帮助</span>');
				}
			});
		},
		formSubmit:function(url,queryParams,fun){
			$.ajax({
				url: url,
				type: 'POST',
				dataType: 'JSON',
				data: queryParams||{},
				success:function(data){
					if (fun) {fun(data);};
				},
				error:function(XMLHttpRequest, textStatus, errorThrown){
					MMT.MSG.alert('数据请求失败：'+textStatus+' '+errorThrown+'<br />请求地址:'+url+'<br />AJAX请求信息：'+JSON.stringify(this)+'<br /><span style="color:red">如无法解决该问题，请联系官方获取帮助</span>');
				}
			});
		},
	};
});