define(function(require){
	var $ = require('jquery');
	require('validation')($);
	require('dialog')($);
	require('uriTemplate')($);
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/validation.css');
	//require('../../../js/cimjs/pc/CJL.0.1.js');
	require('../../../js/cimjs/pc/QuickUpload.js');
	require('../../../js/cimjs/pc/ImagePreviewd.js');
	
	var imageMaxSize=50; //指50K
	$(function(){	
		 $("#save").click(function(){submitForm();});
		 $("#cancel").click(function(){close();});
//		 $("#image").change(function(){ 
//			  $("#localImg").show();
//			  if(!checkImageSize()){
//				  $.msg.alert("提示信息","你上传的图片太大,最大不能超过50KB.",{buttons:{"确定":function() {$(this).dialog("close");}}});
//			  }else{
//				  setImagePreview();
//			  }
//		 });
	});
	$(function(){
		// 验证用户正确性
	    $("#newPC").validate({
		  rules:{
		       pcId:{
	              required:true,
	              regex: /^[1-9a-zA-Z]+$/,  // 必须添加转义字符'/'--否则出错
	              rangelength:[0,20],
	              checkPcId:true
	           },
	           image:{
	    	      required:true,
	    	      //checkImageSer:true,
	    	      checkImage:true
	    	   },
	    		pcRemarks:{
	    		  required:true,
	      		  rangelength:[0,100]
	        	}
		  },
		  errorPlacement:function (error,element){
				error.insertAfter(element);
		   },
		  // 用户自定义的键/值对消息;键为一个表单元素的name属性，值为该表单元素将要显示的消息。该消息覆盖元素的title属性或者默认消息
		  messages:{
			   pcId:{
			     required:i18n["Validation.pc.pcId.notNull"],
			     regex:i18n["Validation.pc.pcId.regex"],
			     rangelength:i18n["Validation.pc.pcId.length"]   
			  },
			  image:{
				  required:i18n["Validation.pc.image.notNull"],
				  regex:i18n["Validation.pc.image.regex"]
			  },
			  pcRemarks:{
				  required:i18n["Validation.pc.pcRemarks.notNull"],
				  rangelength:i18n["Validation.pc.pcRemarks.length"]
			  }
		   }
		});
	});
	$(function(){
		 // 验证Pc码的唯一性	
		$.validator.addMethod("checkPcId",function(value,element,param){
			var pcId = $("#pcId").val();
			var validateUrl = new $.Template($("#validateUrl").val());
			params = {"pcId":pcId,"validateType":"new"};
			var urlStr = validateUrl.expand(params)+".json";
			var flag = false;
		    $.ajax({
		    	url:urlStr,
		    	dataType:'json',
				async: false,
			    success: function(data){
		   		    flag = data.flag;
			   	}
		   	});
			return flag;
		},i18n["Validation.pc.pcId.exist"]);
		
		// 验证图片格式
		$.validator.addMethod("checkImage",function(value,element,param){
			var flag = false;
		    flag = /\.(jpg|jpeg|bmp|gif|png|tif|psd|tga|eps)$/.test(value.toLocaleLowerCase());
			return flag;
		},i18n["Validation.pc.image.regex"]);
		
	});
	
	$(function(){
			var previewUrl=$("#previewUrl").val();
			var ip = new ImagePreview( $$("image"), $$("imagePreview"), {
				maxWidth: 200, 
				maxHeight: 200, 
				action: previewUrl,
				onErr:function(ioArgs){ alert(ioArgs); ResetFile($$("image")); },
				onFinish:function(response){alert(response);}
			});
			ip.img.src = ImagePreview.TRANSPARENT;
			ip.file.onchange = function(){ 
				 $("#type").val('preview'); // 设置提交类型为预览
				  if($.trim($("#pcId").val())==""){
				      $("#pcId").val("pc");
				  }
				  if($.trim($("#pcRemarks").val())==""){
					  $("#pcRemarks").val(".");
				  }
				ip.preview(); 
			};
		
		function ResetFile(file){
			$("#pcId").val("");
			$("#pcRemarks").val("");
			file.value = "";//ff chrome safari
			if ( file.value ) {
				if ( $$B.ie ) {//ie
					with(file.parentNode.insertBefore(document.createElement('form'), file)){
						appendChild(file); reset(); removeNode(false);
					}
				} else {//opera
					file.type = "text"; file.type = "file";
				}
			}
		}
	});
		// 预览图片
		function setImagePreview() {
		    var imageObj = $("#image")[0];
		    var imgSrc = "";
	        if(imageObj.files &&  imageObj.files[0]){
	        	imgSrc = imageObj.files[0].getAsDataURL();
        		//火狐下，直接设img属性
	        	$("#imagePreview").css({display:"block",width:"300px",height:"300px"});
	        	$("#imagePreview").attr({src:imgSrc});

	        }else{
	            //IE下，使用滤镜
	            imageObj.select();
	            imgSrc = document.selection.createRange().text;
            	//必须设置初始大小
	            $("#localImg").css({width:"300px",height:"300px"});
	            //图片异常的捕捉，防止用户修改后缀来伪造图片
	            try{
	            	$("#localImg").css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"});
	            	$("#localImg")[0].filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
	            }catch(e){
	            	$("#localImg").hide();
	                return false;
	            }
	            $("#imagePreview").hide();
	            document.selection.empty();
	        }
	        return true;
	    };
	    
		// 验证上传的图片大小是否合适,满足条件返回true,否则返回false
		function checkImageSize(){
			var imageObj = $("#image")[0];
		    var flag = false;

	        if($.browser.mozilla){ // 查看是否是火狐
	        	var fsize = imageObj.files[0].fileSize/1024;
	        	fsize = fsize.toFixed(1);
 		        if(fsize<=imageMaxSize){
 		            flag = true;
 		        }
	        }else if($.browser.msie){// 查看是否是ie
	        	if(imageObj.readyState=="complete"){
	        	   var img = new Image();
	        	 //IE下，使用滤镜
		            imageObj.select();
		            imgSrc = document.selection.createRange().text;
	    		   img.src = imgSrc;
	        	   var fsize = img.fileSize/1024;
	    		   fsize = fsize.toFixed(1);
	    		   if(fsize>imageMaxSize){
	 		            flag = false;
	 		       }else{
	 		    	    flag = true;
	 		       }
	 		    }
	        }else{
	        	flag = true;
	        }
	        return flag;
		};

		// 函数,提交表单
		function submitForm(){
			if($("#newPC").valid()){
				$("#save").attr("href","#"); // 改变href的值
				var url = $("#saveUrl").val();
				$("#newPC").attr("action",url);
				$("#newPC").submit();
			}
		};
		// 关闭窗口
		function close(){
			// 进入查询页面URL
		      var indexUrl= $("#indexUrl").val();
		      window.location = indexUrl;
		}; 
});

