var ImageUploader = Class.create({

	initialize: function(){
		alert('entrar');
		this.limitFotos = 5;
		this.activeFile = 0;
		this.fotos = new Hash();
		this.order_index=0;
		this.current_file = "";
		this.formFieldName = "json_fotos";
		this.listElement = "listFotos";
		this.draw();
		
	},

	setNewLimit: function(limit){

		if(Object.isNumber(limit))
			this.limitFotos = limit;

	},

	mainImage: function mainImage(coords,dimensions){
		if(this.fotos.get(this.current_file)==undefined){
			this.fotos.set(this.current_file,new Hash());
			this.fotos.get(this.current_file).set("filename",this.current_file);
		}
		this.fotos.get(this.current_file).set("x1",coords.x1);
		this.fotos.get(this.current_file).set("y1",coords.y1);
		this.fotos.get(this.current_file).set("x2",coords.x2);
		this.fotos.get(this.current_file).set("y2",coords.y2);
		this.fotos.get(this.current_file).set("order",this.order_index);
		this.uploader.enable();
		
	},
	removeImage: function(file){
		image_order = this.fotos.get(file).get("order");
		this.fotos.each(function(item){
			if(item.value.get("order")>image_order)
				item.value.set("order",item.value.get("order")-1);
		});
		this.fotos.unset(file);
		$(file).remove();
		this.order_index = eval(this.order_index)-1;
		$("rightUploader").update("");
		$("rightUploader").insert(
				new Element("p",{className:"cor_azul02 strong"}).update(
					"Use o bot\343o na parte esquerda da janela para carregar as suas fotografias."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode fazer upload de ficheiros do tipo JPG, GIF (Por favor, n\343o envie imagens com direitos de autor)"
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode enviar um m\341ximo de 5 imagens."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Use o link remover \340 esquerda para retirar uma imagem da lista. Use as setas por baixo de cada imagem para ordenar a listagem"
				)
			);
		if(!this.order_index)
			this.hideTerminateButton();
	},
	move_up: function(file){
		self = this;
		image_order = this.fotos.get(file).get("order");
		if(image_order){
			this.fotos.get(file).set("order",image_order-1);
			this.fotos.each(function(item){
	        	if(item.value.get("order")==image_order-1){
					item.value.set("order",image_order+1);
					return;	
				}
			});
			var tmp = $(file).innerHTML;
			var tmp_id = $(file).id;		
			var tmp_id2 = "dummy";		
			var tmp_id3 = $(file).previous().id;				
			$(file).innerHTML = $(file).previous().innerHTML;
			$(file).previous().innerHTML = tmp;
			$(file).id = tmp_id2;
			$(tmp_id2).previous().id = tmp_id;		
			$(tmp_id2).id = tmp_id3;
			$(file+"up").observe("click",function(){self.move_up(file)})
			$(file+"down").observe("click",function(){self.move_down(file)})
			$(file+"remove").observe("click",function(){self.removeImage(file)})
			$($(tmp_id3).id+"up").observe("click",function(){self.move_up($(tmp_id3).id)})
			$($(tmp_id3).id+"down").observe("click",function(){self.move_down($(tmp_id3).id)})
			$($(tmp_id3).id+"remove").observe("click",function(){self.removeImage($(tmp_id3).id)})						
		}
	},
	move_down: function(file){
		image_order = this.fotos.get(file).get("order");
		if(image_order<this.order_index){
	        	this.fotos.get(file).set("order",image_order+1);
	        	this.fotos.each(function(item){
		        	if(item.value.get("order")==image_order+1){
       	        			item.value.set("order",image_order-1);
				        return;
				}
		        });
			var tmp = $(file).innerHTML;			
			var tmp_id = $(file).id;		
			var tmp_id2 = "dummy";		
			var tmp_id3 = $(file).next().id;				
		        $(file).innerHTML = $(file).next().innerHTML;
    		   	$(file).next().innerHTML = tmp;
			$(file).id = tmp_id2;
			$(tmp_id2).next().id = tmp_id;		
			$(tmp_id2).id = tmp_id3;
			$(file+"up").observe("click",function(){self.move_up(file)})
			$(file+"down").observe("click",function(){self.move_down(file)})
			$(file+"remove").observe("click",function(){self.removeImage(file)})
			$($(tmp_id3).id+"up").observe("click",function(){self.move_up($(tmp_id3).id)})
			$($(tmp_id3).id+"down").observe("click",function(){self.move_down($(tmp_id3).id)})
			$($(tmp_id3).id+"remove").observe("click",function(){self.removeImage($(tmp_id3).id)})			
		}
	},

	showTerminateButton: function(){
				     
		$("terminate_button").style.display="";
		slf = this;
		// IE FIX
		$$("#terminate_button a")[0].stopObserving("click");
		$$("#terminate_button a")[0].observe("click",function(){slf.finalize()});

	},
	hideTerminateButton: function(){
		$("terminate_button").style.display="none";
	},
	save_image: function(){
		file_li = $$('#uploader .files')[0];
		selfObj = this;
		is_checked = ""
		file = selfObj.current_file;
		if(file_li.innerHTML=="")
			is_checked = "checked";
		newLi = new Element('li',{id:selfObj.current_file}).update(
				file+"&nbsp;");
		newLi.insert(new Element("br"));
		newLi.insert(new Element("a",{href:"#",className:"remov",id:file+"remove"}).update("remover").observe("click",function(){selfObj.removeImage(file)}));
		newLi.insert("&nbsp;");
		newLi.insert(new Element("a",{href:"#",title:"descer",id:selfObj.current_file+"down"}).update(
					new Element("img",{src:"backend/img/ico_arrow_down_new.gif",border:0})
					).observe("click",function(){selfObj.move_down(file)})
		);
		newLi.insert("&nbsp;");
		newLi.insert(new Element("a",{href:"#",title:"subir",id:selfObj.current_file+"up"}).update(
					new Element("img",{src:"backend/img/ico_arrow_up_new.gif",border:0})
					).observe("click",function(){selfObj.move_up(file)})
		);
		newLi.id = this.current_file;
		file_li.insert(newLi);
		this.order_index++;
		this.fotos.get(this.current_file).set("saved",true);
		if(this.order_index == 1)
			this.showTerminateButton();
		this.resetCanvas();
	},
	
	resetCanvas: function(){
		$("rightUploader").innerHTML = "";
		if(this.order_index<this.limitFotos){
			$("rightUploader").insert(
				new Element("p",{className:"cor_azul02 strong"}).update(
					"Use o bot\343o na parte esquerda da janela para carregar as suas fotografias."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode fazer upload de ficheiros do tipo JPG, GIF (Por favor, n\343o envie imagens com direitos de autor)"
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode enviar um m\341ximo de 5 imagens."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Use o link remover \340 esquerda para retirar uma imagem da lista. Use as setas por baixo de cada imagem para ordenar a listagem"
				)
			).insert(
			        new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
			                "Quando terminar, carregue no bot\343o 'Gravar' que estar\341 vis\355vel sempre que tiver imagens carregadas."
			        )
			);
		}else{
			$("rightUploader").insert(
				new Element("p",{className:"cor_azul02 strong"}).update(
					"Atingiu o limite de imagens."
				)
			);
		}
	},	
	finalize: function(){
		var index = 1;
		listElement = this.listElement;
		formFieldName = this.formFieldName;
		this.fotos.each(function(item){
			if(item.value.get("saved")==undefined)
				this.fotos.unset(item.value.get("filename"));
			else{
				if(index > 1)
					$(listElement).insert(
						new Element("br")
					);
					
				$(listElement).insert(
					index + ". " + item.value.get("filename")
				);
				index++;
			}
		});

		$(formFieldName).value = this.fotos.toJSON();
		Modalbox.hide();
		
	},
	draw: function(){

		selfIn = this;

		this.mainDiv = new Element("div",{className:"mainUpload"}).update(
			inputDiv = new Element("div",{className:"boxOportunidades",style:"height:auto;float:left;padding-right:10px;padding-bottom:10px;width:247px;",id:"leftUploader"})
		);
		
		inputDiv.insert(ul_uploader = new Element("ul",{style:"margin-left: 0px; list-style-type: none; float: left;"}).update(
			li_uploader = new Element("li",{id:"uploader", className:"uploader_class"}).update(
				new Element("div",{className:"wrapper"}).insert(
					new Element("div",{id:"upload_button",className:"divLoadFotos"}).update("Carregar Imagem"))
				)
			)
		);
		
		li_uploader.insert(
			new Element("p",{className:"uper font size11 float menu_w m_top10 cor_menu01 t_alignRight cor_branco p_Right5 strong"}).update(
				"Imagens Carregadas:"
			)
		).insert(
			new Element("div",{className: "clear"})
		);
		li_uploader.insert(
			new Element("ol",{className:"files"})
		).insert(
			new Element("div",{className:"divLoadFotos",id:"terminate_button"}).update(
				new Element("a",{className:"remov",href:"#"}).update(
					"Gravar"
				).observe("click",function(){selfIn.finalize()})
			)
		);
		
		this.mainDiv.insert(
			canvasDiv = new Element("div",{id:"rightUploader",align:"center"}).insert(
				new Element("p",{className:"cor_azul02 strong"}).update(
					"Use o bot\343o na parte esquerda da janela para carregar as suas fotografias."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode fazer upload de ficheiros do tipo JPG, GIF (Por favor, n\343o envie imagens com direitos de autor)"
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Pode enviar um m\341ximo de 5 imagens."
				)
			).insert(
				new Element("p",{className:"m_top4 justify cor_cinza999 lineHeight18"}).update(
					"Quando terminar, carregue no bot\343o 'Gravar' que estar\341 vis\355vel sempre que tiver imagens carregadas."
                                )
			)

		);
		var self = this;
		Modalbox.show(this.mainDiv,{title: "Carregamento de Imagens", width: 1200, height: 1000, afterLoad: function(){self.init_cropper()}});
	},
	
	init_cropper: function(){
		
		// IE FIX
		$("terminate_button").style.display="none";
		
		var button = $('upload_button'), interval;

		var self = this;

		this.uploader = new Ajax_upload(button, {

			action: '/backend/barcos/upload.php',

			name: 'userfile',
	
			onSubmit: function(file , ext){
				if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
					writeError('upload_button','Ficheiro inválido');
					return false;
				}
				button.update('A Carregar Ficheiros');
				this.disable();
				interval = window.setInterval(function(){
					var text = button.innerHTML;
					if (text.length < 24){
						button.update(text + '.');					
					} else {
						button.update('A Carregar Ficheiros');				
					}
				}, 200);
  			},
		
			onComplete: function(file, response) {
				button.update('Carregar Fotos');
				window.clearInterval(interval);
				session_id = response;
				self.current_file = file;
				$("rightUploader").innerHTML="";
				$("rightUploader").insert(new Element("p",{className:"cor_azul02 strong"}).update("Arraste a caixa para escolher a \341rea que pretende manter e use as arestas e v\351rtices para aumentar ou reduzir o tamanho da sele\347\343o"));
				$("rightUploader").insert(new Element("div",{className:"divLoadFotos"}).update(
						new Element("a",{className:"greylink",href:"#",id:"save_link"}).update(
							"Gravar Imagem"
						).observe("click",function(){self.save_image()})
					)
				);
											   
				$("rightUploader").insert(new Element("div",{style:"float:left;"}).update(
					new Element("img",{src:"backend/images/"+session_id+"/"+file,id:"mainImg",border:0,alt:"Imagem Carregada",style:"max-width:800px;max-height:800px;min-width:237px;min-height:177px;"})
				)
				);
				$("leftUploader").insert(
					new Element("div",{style:"clear:both;"})
				).insert(new Element("div",{id:"previewWrap",style:"margin-left:10px; float:left;"}));
								
				new Cropper.ImgWithPreview("mainImg",{ratioDim: { x:237, y:177}, displayOnInit: true,minWidth: 237, minHeight: 177,previewWrap: 'previewWrap',onEndCrop: function(coords,dimensions){self.mainImage(coords,dimensions)},onloadCoords:{x1:0,y1:0,x2:2000,y2:2000}});
				Modalbox.resizeToContent();
											
			}
		});
		
	}

});

