/*
 * 图片上传，两种模式：append（上传多张）,single（上传单张）
 * param wrap: Element 上传图片的容器
 * param url: String 上传路径
 */
 /*
 var iu_01 = new Fangbole.ImageUploader('banner_upload_01', '<c:url value="/items.html?method=browseItemForKV"/>', {
	fileSize: '1MB', 
	fileWrap: 'photo_01',
	data:'kv_desc_01', 
	//mode:'single',
	imageTemplate: imageTemplate
});
*/
/*
status:2-删除，3-新建，4-编辑回填
*/
Fangbole.ImageUploader = new Class.create({
	initialize: function(wrap, url, options){//wrap:容器,url:上传路径
		this.images = [];
		this.id = 'imageUploader_' + Fangbole.ImageUploader.instances.length;//对象id;
		this.uploadUrl = url;//上传路径
		this.options = Object.extend({
			mode: 'append', //single, append 单张/多张
			imageTemplate: Fangbole.ImageUploader.template.image,//图片显示模板
			//<span class="album_image_box"><img src="#{tURL}" /></span><input type="hidden" value="#{fURL}" />
			fileWrap: '',//上传后的文件标签容器
			fileSize: '1 MB',//上传文件大小
			fileTypes: '*.jpg;*.gif;*.png;*.bmp;*.jpeg',
			fileTypesDesc: '图片文件',
			buttonImageUrl: '/Next/images/upload_btn.gif',//按钮图片路径
			buttonWidth: 51,//按钮宽
			buttonHeight: 23,//按钮高
			beforeAddImage:Prototype.emptyFunction,//图片添加之前接口
			onUploadSuccess: Prototype.emptyFunction,//上传成功接口
			afterAddImage: Prototype.emptyFunction,//图片添加后接口
			cancelable: true,//可取消
			showProgress: true,
			tips: true,
			//指定一个文本输入框（隐藏域）提交、回填数据
			data: null,
			enableDel:false
		}, options || {})
		
		this.element = new Element('div', {id: this.id, className: 'image_uploader'}).update(Fangbole.ImageUploader.template[this.options.mode].evaluate({id: this.id}));
		//根据单张还是多张构造上传控件容器
		$(wrap).insert(this.element);
		//上传控件插入容器
		this.elImageWrapper = $(this.options.fileWrap) || this.element.down('.upload_image_wrap');//图片总容器
		this.elPanel = this.element.down('.upload_panel');
		//this.elCancel = this.element.down('.upload_cancel');
		this.elProgress = this.element.down('.upload_progress');
		this.elMsg = this.element.down('.upload_msg');//上传信息
		
		this.beforeAddImage=this.options.beforeAddImage;
		this.onUploadSuccess = this.options.onUploadSuccess;
		this.afterAddImage = this.options.afterAddImage;
		
		this.SWFUploadSetting = {//上传控件初始化
			// Backend settings
			upload_url: url,
		
			// Flash file settings
			file_size_limit : this.options.fileSize,//文件大小
			file_types : this.options.fileTypes,//文件类型
			file_types_description : this.options.fileTypesDesc,//文件信息

			// Event handler settings 在handler.js里定义
			//swfupload_loaded_handler : swfUploadLoaded,
			file_dialog_start_handler: fileDialogStart,
			file_dialog_complete_handler : fileDialogComplete,
			//file_queued_handler : fileQueued,
			file_queue_error_handler : fileQueueError,			
			upload_start_handler : uploadStart,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,
			// Button Settings
			button_image_url : this.options.buttonImageUrl,
			button_placeholder_id : "buttonPlaceHolder",
			button_width: this.options.buttonWidth,
			button_height: this.options.buttonHeight,
			button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
			button_cursor: SWFUpload.CURSOR.HAND,
			// Flash Settings
			flash_url : "/Next/swf/swfupload.swf",//控件路径
			custom_settings : {
				upload_successful : false
			},
			//SWFobject setting
			minimum_flash_version : "9.0.28",
			swfupload_load_failed_handler : swfUploadLoadFailed,
			swfupload_pre_load_handler : swfUploadPreLoad,

			// Debug settings
			debug: false		
			
		}
		this.SWFUpload = new SWFUpload(this.SWFUploadSetting);//构造上传控件
		this.SWFUpload.imageUploader = this;
		
		//this.elCancel.observe('click', this.cancel.bind(this));
		this.elImageWrapper.observe('click', this.onClick.bindAsEventListener(this));//$(".upload_image_wrap")点击上传后文件容器事件
		if(this.options.data){//初始数据
			this.elData = $(this.options.data)
			if(!this.elData)
				throw 'data field not exsit';
			var initData;
			try{
				initData = $F(this.elData).evalJSON();
			}catch(e){
				initData = [];
			}
			this.loadImage(initData);//用初始数据把图片写入文档
		}
		Fangbole.ImageUploader.instances.push(this);
	},
	onClick: function(e){
		var elt = e.element();
		if(elt.hasClassName('delete_image')){
			var id = parseInt(elt.up('.image_uploaded').id.replace('iu_', ''));
			this.remove(id);
		}
	},
	add: function(oImage, file){//file是通过控件上传时的文件的附件信息
		//var v=this.options.beforeAddImage(this.images)==false?false:true;
		//if(this.options.mode == 'append'&&v){
		this.options.beforeAddImage();
		if(this.options.mode == 'append'){
			var image = this.find(oImage.id);//是否已经添加到(页面)this.images对象数组里,如果已经添加则返回this.images中的该对象
			if(!image){//如果还没有添加
				if(file)//如果存在file(即及时上传文件)就用你file扩展oImage对象
					Object.extend(oImage, {name: file.name, size: file.size, type: file.type})
				oImage.element = new Element('div', {id: 'iu_' + oImage.id, className: 'image_uploaded'}).update(this.options.imageTemplate.evaluate(oImage));
				//构造图片容器(图片,删除按钮,隐藏域)
				oImage.status = 3;//新建
				this.images.push(oImage);//把当前oImage对象添加进this.images集合
				
				if($$('.upload_button')) {
					var imgBox = '<div id="imgTemp" style="height: 0px; overflow: hidden;"><img src="'+oImage.tURL+'" alt="" /></div>'
					//var imgTemp = new Image();
					//imgTemp.src = oImage.tURL;
					$$('.upload_button')[0].insert(imgBox, {positon: 'after'});
				}
				
				//add remove handle
				var elDelete = new Element('a', {className: 'delete_image', href: 'javascript:;'}).update('删除');//构造删除按钮
				oImage.element.insert(elDelete);//把删除按钮添加进oImage容器
				this.elImageWrapper.appendChild(oImage.element);//把该oImage容器添加进指定的总容器
				
				//fix ie8
				if(Prototype.Browser.IE && (this.images.length == 1)){
					this.elImageWrapper.style.zoom = 1;
				}
				
			}else{//如果(页面)this.images对象数组里已经存在该对象,重写改对象
				oImage.element.update(this.options.imageTemplate.evaluate(oImage));//用指定模板构造DOM添加到该对象容器
				Object.extend(image, oImage);//用该对象扩展this.images中同id的对象
				image.status = 4;//回填数据
			}		
		}else if(this.options.mode == 'single'){
			if(!file)
				this.isEdit = true;
			if(this.images.length){
				if(file)
					Object.extend(this.images[0], {name: file.name, size: file.size, type: file.type});
				Object.extend(this.images[0], {fURL: oImage.fURL, tURL: oImage.tURL});
				this.images[0].element=new Element('div', {id: 'iu_' + this.images[0].id, className: 'image_uploaded'}).update(this.options.imageTemplate.evaluate(this.images[0]));

			}else{
				oImage.element = new Element('div', {id: 'iu_' + oImage.id, className: 'image_uploaded'}).update(this.options.imageTemplate.evaluate(oImage));
				this.images.push(oImage);
			}
			if(this.options.enableDel){
				var elDelete = new Element('a', {className: 'delete_image', href: 'javascript:;'}).update('删除');//构造删除按钮
				this.images[0].element.insert(elDelete);//把删除按钮添加进oImage容器
			}
			//this.remove(this.images[0].id)
			this.elImageWrapper.update();
			this.elImageWrapper.insert({top:this.images[0].element});
			this.images[0].status = this.isEdit ? 4 : 3;
		}
		this.afterAddImage();
		return oImage;
	},	
	remove: function(id){
		var removeImage = this.find(id);
		if(removeImage){
			if(this.options.mode == 'single'){
				if(this.isEdit){
					removeImage.status = 2;
					var template=new Template(
						'[{"tURL":"#{tURL}","fURL":"#{fURL}","id":#{id},"exist":"#{exist}","status":#{status}}]'
					)
					var value=template.evaluate(removeImage)
					this.elData.value=value;
				}else
					this.images = [];
			}else if(this.options.mode == 'append'){
				removeImage.status = 2;
			}
			removeImage.element.remove();
		}
	},
	/**
	 *从已经添加到页面(this.images)的文件中查找有没有和指定id相同的文件
	 *
	 */
	find: function(id){
		for(var i = 0, j = this.images.length; i < j; ++ i){
			if(this.images[i].id == id && this.images[i].status != 2){
				return this.images[i];
			}
		}
		return null;
	},
	setProgress: function(percent){
		this.elProgress.style.width = percent;
	},
	setMessage: function(msg, type){
		if(!this.options.tips)return;
		this.elMsg.update(msg);
		switch(type){
			case 0:
				this.elMsg.removeClassName('v-ok');
				this.elMsg.addClassName('v-error');
				break;
			case 1:
				this.elMsg.removeClassName('v-error');
				this.elMsg.addClassName('v-ok');
				break;
		}
		Effect.Appear(this.elMsg,{afterFinishInternal:function(){
			Effect.Fade(this.elMsg)
		}.bindAsEventListener(this)});
	},
	enableCancel: function(){
		this.elCancel.disabled = false;
		this.elCancel.show();
	},
	disableCancel: function(){
		this.elCancel.disabled = true;
		this.elCancel.hide();
	},
	cancel: function(){
		this.SWFUpload.cancelQueue();
		this.elPanel.hide();
	},
	showProgress: function(){
		this.elPanel.show();
	},
	hideProgress: function(){
		this.elPanel.hide();
	},
	//装载图片数据
	loadImage: function(images){
		images.each(function(image){
			this.add(image);
		}, this)
	},
	//提交图片数据
	submitImage: function(element){
		var data = Object.toJSON(this.images);
		if(element)
			$(element).value = data;
		if(this.elData)
			this.elData.value = data;
	}
})

Object.extend(Fangbole.ImageUploader, {
	instances: [],
	template: {
		append: new Template('<div class="upload_button" title="上传图片"><div id="buttonPlaceHolder"></div></div><div class="upload_panel"></div><p class="upload_msg v-info" style="display: none;"></p>'),
		single: new Template('<div class="upload_button" title="上传图片"><div id="buttonPlaceHolder"></div></div><div class="upload_panel"></div><p class="upload_msg v-info" style="display: none;"></p><div class="upload_image_wrap"></div>'),
		image: new Template('<img src="#{tURL}" /><input type="hidden" value="#{fURL}" />')
	}
})
