define(function(require,exports) {
	//加载JS库
	var $ = require('jquery');
	exports.init = initUploading;
	
	
	var htmlStr = '<table><tr><td><input type="button" id="choseFile"  value="'+i18n["Vehicle.attachment.image.chosing"]+'" /></td></tr></table>';
	
	
	function initUploading(){
		var pos = $("div[id='fileFields']");
		if(pos.length==0){
			alert("init uploadFiles \nCant not find the 'div' with id 'fileFields' !");
			return;
		}
		pos.html(htmlStr);
		pos.append("<div id='files' style='width:0px;height:0px;overflow:hidden;' ></div><div id='files2' style='width:0px;height:0px;overflow:hidden;' ></div>");
		$("#choseFile").click(function(){
			var maxnum = -1;
			$("input[name^='attachments']").each(function(){
				var name = $(this).attr("id");
				var len = name.length;
				var num = Number(name.substring(4,len));
				if(num>maxnum){
					maxnum=num;
				}
			});
			maxnum = maxnum+1;
			var file = "<input type='file' id=file"+maxnum+" />";
			$("#files").html(file);
			$("#file"+maxnum).trigger("click");
		});
		
		$("input[id^='file']").live("change",function(){
			var type = this.files[0].type;
			if(type.indexOf("image")==-1){
				$.msg.alert(i18n['Company.Profile.Image.Only']);
				return;
			}
			var obj = $(this);
			var name = obj.attr("id");
			var len = name.length;
			var num = Number(name.substring(4,len));
			obj.attr("name","attachments["+num+"].file");
			obj.appendTo($("#files2"));
			$("#formTable").append("<tr><th style='width:20%'>"+i18n["Vehicle.attachment.image.name"]+"</th><td  style='width:30%'>"+this.files[0].fileName+"&nbsp;<a href='#;' name="+obj.attr("id")+" id=image"+obj.attr("id")+">"+i18n["Entity.code.delete"]+"</a></td><th  style='width:20%'>"+i18n["Vehicle.attachment.image.desc"]+"</th><td  style='width:30%'><textarea  id='descrition"+num+"' name='attachments["+num+"].descrition'  class='inputbox'></textarea></td></tr>");
		});
		
		$("a[id^=imagefile]").live('click',function(){
			var flag = confirm("确认删除？");
			if(flag){
				var url = $("#deleteImageUrl").val();
				var para={"imageName":$(this).attr("imageName"),"vehicleId":$(this).attr("vehicleId")};
				$.get(url,para);
				$("#"+$(this).attr("name")).remove();
				$(this).parent().parent().remove();
				sortItems();
			}
		});
		
	}

	
	function sortItems(){
		$("input[name^=attachments]").each(function(i,k){
			var type = $(this).attr("type");
			var obj = $(k);
			var name = obj.attr("id");
			var len = name.length;
			var num = Number(name.substring(4,len));
			$("#descrition"+num).attr("name","attachments["+i+"].descrition");
			$("#descrition"+num).attr("id","descrition"+i);
			$("#imagefile"+num).attr("name","file"+i);
			$("#imagefile"+num).attr("id","imagefile"+i);
			if(type=="file"){
				obj.attr("name","attachments["+i+"].file").attr("id","file"+i);
			}
			if(type=="hidden"){
				obj.attr("name","attachments["+i+"].id").attr("id","file"+i);
			}
		});
		
	}

});