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('../../../scripts/cim/uploadify-v2.1.4/jquery.uploadify.v2.1.4.js');
	require('../../../scripts/cim/uploadify-v2.1.4/swfobject.js');
	require('../../../scripts/cim/uploadify-v2.1.4/uploadify.css');
	require('../../../scripts/cim/uploadify-v2.1.4/uploadify.swf');

	$(function(){	
		 $("#save").click(function(){submitForm();});
		 $("#cancel").click(function(){close();});
		 $("#image").change(function(){ 
			  $("#localImg").show();
			  //setImagePreview();
			  //$('#image').uploadifyUpload();
				var url = $("#saveUrl").val();
				$("#image").uploadify({
//					  'uploader'       : 'js/uploadify.swf',//指定上传控件的主体文件，默认‘uploader.swf’    
//					  'script'         : '../js/uploadify.php',//指定服务器端上传处理文件，默认‘uploadify.php’    
//					  'cancelImg'      : 'js/cancel.png',//指定取消上传的图片，默认‘cancel.png’    
					  'folder'         : '/',//要上传到的服务器路径，默认‘/’ ,将'auto'设置为true,才有效   
					  'sizeLimit'      : 50*1024,//控制上传文件的大小，单位byte    
					  'multi'          : false,    
					  'auto'           : true,//选定文件后是否自动上传，默认false  
					  'script'         : url,
					  'method'         : 'POST',
					  'fileExt'        : '*.jpg;*.gif;*.png;*.jpeg;*.bmp;*.tif;*.psd',    
					  'fileDesc'       : 'Image Files (.JPG, .GIF, .PNG, .JPEG, .BMP, .TIF,.PSD)',    
					  'queueID'        : 'custom-queue',   
					  'fileDataName'   : "image",
					  'queueSizeLimit' : 3,    
					  'simUploadLimit' : 3,    
					  'removeCompleted': false,    
					  'onSelect'       :function(e, queueId, fileObj){ //选择上传文件时解发以下动作    
					        alert(i18n['Uploadify.File.Image.Id'] + queueId + "\r\n" +
				                  i18n['Uploadify.File.Image.Name'] + fileObj.name + "\r\n" +
				                  i18n['Uploadify.File.Image.Size'] + fileObj.size + "\r\n" +
				                  i18n['Uploadify.File.Image.CreateTime'] + fileObj.creationDate + "\r\n" +
				                  i18n['Uploadify.File.Image.LastModifiedTime'] + fileObj.modificationDate + "\r\n" +
				                  i18n['Uploadify.File.Type'] + fileObj.type
					            );
					    },    
					  'onSelectOnce':function(event,data) {    
					      $('#statusMessage').text(data.filesSelected + ' files have been added to the queue.');    
					    }, 
					   'uploadifyError':function(event,date){
					    	alert(event);
					    	alert(data);
					    },
					  'onComplete':function (event, queueID, fileObj, response, data) {  
					    	alert(event);
					    	alert(response);
					    	alert(queueID);
					    	alert(data);
//					        //上传成功后动作，获取上传数据    
//					    	var url = $("#saveUrl").val();
//					        var andExp = /&/g;    
//					        var pcId = $.trim($('#pcId').val()).replace(andExp,escape('&'));    
//					        var pcRemarks = $.trim($('#pcRemarks').val()).replace(andExp,escape('&'));    
//					        var data_content = 'pcId='+pcId+'&pcRemarks='+pcRemarks;    
//					        //上传图片    
//					        $.ajax({    
//					            type: 'POST',    
//					            dataType: 'json',    
//					            url: url,    
//					            data: data_content,    
//					            cache: false,    
//					            async:false,    
//					            success: function(response){  
//					        	     alert(response);
//					                 jQuery('#image').uploadifyClearQueue();//清除上传    
//					             }    
//					         });    
					    }  
				});
		 });
	});
	$(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 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;
	    };
		
		// 函数,提交表单
		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;
		};

});

