/*
*/

function getLoading1(hidden) {
	if (typeof hidden == "undefined") hidden = false;
	disp = (hidden)? "display:none; " : "";
	return '<div id="loading1" style="'+disp+'padding:20px; 0px; border:1px solid #ccc; text-align:center;"><img src="'+asset_path+'imgs/load1.gif" alt="carregando"/><br/><p>carregando...</p></div>';
}

function flashPutHref(href) { location.href = href; }
function flashPutTitle(title) { document.title = title; }
function chama_link_ssp(destino) {
	alert("chama_link_ssp: " + destino);
}
function sspToggleDisplayMode() {
	$("ssp_id").sspToggleDisplayMode();
}
function sspLoadAlbum(album) {
	$("ssp_id").sspLoadAlbum(album);
}

function notifyAlbumLoaded(album_uri) {
	var elementoListaAlbuns = "ul_albuns";
	if (typeof AlbumDeUsuario == "object") {
		elementoListaAlbuns = AlbumDeUsuario.elementoListaAlbuns;
	}
	if ($(elementoListaAlbuns)) {
		var elmts = $(elementoListaAlbuns).immediateDescendants();
		for (var i=0;i<elmts.length;i++) {
			elmt_li = elmts[i];				
			elmt_anchor = elmt_li.firstDescendant();
			if (i == 0) {
				var first_anchor_offsetTop = elmt_anchor.offsetTop;					
			}				
		    if (elmt_anchor.id == 'album_'+album_uri) {
				elmt_anchor.addClassName("active");			    	
				$(elementoListaAlbuns).scrollTop = elmt_anchor.offsetTop - first_anchor_offsetTop;					    	
			} else {
				elmt_anchor.removeClassName("active")
			}
		}
	}
}

var AlbumDeUsuario = {
	elementoAlbum: "album",
	elementoUpdate: "wrap_arearestrita",
	elementoListaAlbuns: "ul_albuns",
	scrollContainer: "scroll-container",
	urlBase: base_url + "arearestrita/",
	urlUpdate: "",
	urlMontagem: "",
	urlVisualizacao: "",
	urlFinalizacao: "",
	fase: "",
	fotos: new Array(),	
	debug: function(msg) {
		if (typeof console != "undefined") {
			console.log("__ADU: " + msg);
		}
	},
	initialize: function() {
		this.debug("inicializando " + this.fase);

		this.urlUpdate = this.urlBase + "updatealbum/";
		this.urlMontagem = this.urlBase + "index/";
		this.urlVisualizacao = this.urlBase + "visual/";
		this.urlFinalizacao = this.urlBase + "finalizacao/";
		
		//botao visualizar
		if ($("nav_rest_visu")) {
	        $("nav_rest_visu").firstDescendant().onclick = function() {
		        //url = this.getAttribute("href");
				return AlbumDeUsuario.visualizarAlbum();
	        };
	        $("nav_rest_visu").firstDescendant().writeAttribute("href", "");
		}
        if ($("btVisualizar")) {
	        $("btVisualizar").onclick = function() {
		       	//url = this.getAttribute("href");
				return AlbumDeUsuario.visualizarAlbum();
	        };
		}    
		/*
		if ($("nav_rest_mont")) {
	        $("nav_rest_mont").firstDescendant().onclick = function() {
				return AlbumDeUsuario.montarAlbum();
	        };
	        $("nav_rest_mont").firstDescendant().writeAttribute("href", "");	        
		}
		*/
		if ($("nav_rest_fina")) {
	        $("nav_rest_fina").firstDescendant().onclick = function() {
				return AlbumDeUsuario.finalizarAlbum();
	        };
	        $("nav_rest_fina").firstDescendant().writeAttribute("href", "");	        
		}
		if ($("btFinalizar")) {
	        $("btFinalizar").onclick = function() {
				return AlbumDeUsuario.finalizarAlbum();
	        };
		}	    
		if (typeof fotos_cached == "object") {
			if (fotos_cached.length > 0) {
				this.debug("CACHED fotos: " + fotos_cached.length);
				this.fotos = fotos_cached;
				if ($(this.elementoAlbum)) {
					this.debug("criando thumbs a partir do cache");					
					for (i=0;i<this.fotos.length;i++) {			
						this.adicionaLIThumb(this.fotos[i]);
					}
					this.createSortable(false);	
				}
			}
		}
	},
	montarAlbum: function() {
		this.debug("montarAlbum " + this.fase);
    	this.ajaxUpdate(this.urlMontagem, true);
    	return false;
	},	
	visualizarAlbum: function() {
		this.debug("visualizarAlbum " + this.fase);
        if (this.fotos.length < 1) {
        	alert("ainda não há fotos no seu álbum");
	        $("nav_rest_visu").firstDescendant().removeClassName("active");		        
	      	return false; //bypass href
        }
        url = this.urlVisualizacao;
        
        if (this.fase == "montagem") {
	    	this.createSortable(false);  
	    	url = this.urlUpdate;
        }
    	this.ajaxUpdate(url, true);
    	return false;
	},
	finalizarAlbum: function(url) {
		if (typeof url == "undefined") {
			url = this.urlFinalizacao;
		}	
		this.debug("finalizarAlbum "+ url);
        if (this.fotos.length < 1) {
        	alert("ainda não há fotos no seu álbum");
	        $("nav_rest_visu").firstDescendant().removeClassName("active");		        
	      	return false; //bypass href
        }
    	this.ajaxUpdate(url, true);
    	return false;
	},
	adicionaFoto: function(_tb_url, _img_file, _album_uri) {
		this.debug("adicionaFoto: "+_tb_url);

		var maior_idnum = 0;
		for (i=0;i<this.fotos.length;i++) {
			if (this.fotos[i].tb_url == _tb_url) {
		 		$(this.scrollContainer).scrollLeft = Math.max($("item_"+this.fotos[i].idnum).offsetLeft-20, 0);
		 		//new Effect.Highlight($("item_"+this.fotos[i].idnum),{startcolor: "#ff7777"});
		 		new Effect.Shake($("item_"+this.fotos[i].idnum),{duration: 1});
				alert("Esta foto já está no álbum!");
				return;
			}
			if (this.fotos[i].idnum > maior_idnum) {
				maior_idnum = this.fotos[i].idnum;
			}		
		}
		_idnum = maior_idnum + 1;	
		var obj = {idnum: _idnum, tb_url: _tb_url, img_file: _img_file, album_uri: _album_uri};
		this.fotos.push(obj);
		this.adicionaLIThumb(obj);
		this.createSortable(true);			
		//$(this.scrollContainer).scrollLeft = $(this.scrollContainer).scrollWidth + 150;		
	},
	adicionaLIThumb: function(obj) {
		$(this.elementoAlbum).innerHTML +=
			'<li id="item_'+obj.idnum+'">'+
			"<span class=\"btdel\" onclick=\"AlbumDeUsuario.removeFoto(this)\">del</span>"
			+"<img src=\"" + obj.tb_url  + "\" /></li>";	
		$(this.scrollContainer).scrollLeft = $("item_"+obj.idnum).offsetLeft;				
	},
	removeFotoSemEfeito: function(spanElement) {
		AlbumDeUsuario._removeFoto(spanElement.parentNode.id); 	
	},
	removeFoto: function(spanElement) {
		var id = spanElement.parentNode.id;
		//efeitos ok: Fade, DropOut
		new Effect.DropOut(id, 
			{
				duration: 0.5,
				afterFinish: function() { AlbumDeUsuario._removeFoto(id); }
			}
		);
	},	
	_removeFoto: function(liElement) {
		Element.remove(liElement);
		var pos = liElement.lastIndexOf("_");
		var str = liElement.substring(pos+1, liElement.length);
		
		var idnum = parseInt(str);
		for (var i=0;i<this.fotos.length;i++) {
			if (this.fotos[i].idnum == idnum) {
				this.fotos.splice(i, 1);
				break;
			}
		}					
		this.createSortable(true);
	},
	ajaxUpdate: function(url, booUpdateElement) {
		if (typeof url != "string") url = AlbumDeUsuario.urlUpdate;
		url += parseInt(Math.random()*999999999) + "/";
		if (typeof booUpdateElement == "undefined") booUpdateElement = false;
		
		AlbumDeUsuario.debug("ajaxUpdate: "+url + " " + booUpdateElement);		
		
		booSortableExists = (typeof Sortable.sortables[AlbumDeUsuario.elementoAlbum] != "undefined");
		
		_pars = "fotos=" + Object.toJSON(AlbumDeUsuario.fotos);
		if (booSortableExists) {
		 	_pars += "&" + Sortable.serialize(AlbumDeUsuario.elementoAlbum);
		}
		_pars += '&rand=' + parseInt(Math.random()*99999999);

		if (booUpdateElement) {
 			url += "1";	 			
 			if (booSortableExists) Sortable.destroy(AlbumDeUsuario.elementoAlbum);	
			$(AlbumDeUsuario.elementoUpdate).update(getLoading1(true));
			new Effect.Appear($("loading1"),{duration: 0.5});			
		}

		new Ajax.Updater(
			(booUpdateElement)? AlbumDeUsuario.elementoUpdate : "", 
			url, 
			{
				asynchronous:true, 
			 	evalScripts:true, 
			 	onComplete:function(request){
			 		if (booUpdateElement) {
			 			AlbumDeUsuario.initialize();
			 			if (Lightbox) Lightbox.prototype.updateImageList();
			 		}
			 		//new Effect.Highlight(AlbumDeUsuario.elementoAlbum,{});
			 	}, 
			 	parameters: _pars
			}
		)
	},	
	createSortable: function(booUpdate) {
		this.debug("createSortable: "+booUpdate);		
		
		//tratamento das abas e botôes
		if (this.fotos.length > 0) {
			$("nav_rest_visu").firstDescendant().removeClassName("inactive");
			$("nav_rest_fina").firstDescendant().removeClassName("inactive");
			if ($("btVisualizar")) {
				new Effect.Appear($("btVisualizar"),{duration: 0.5});
			}
		} else {
			$("nav_rest_visu").firstDescendant().addClassName("inactive");
			$("nav_rest_fina").firstDescendant().addClassName("inactive");			
			if ($("btVisualizar")) {
				new Effect.Fade($("btVisualizar"),{duration: 0.5});			
			}
		}
		
		Position.includeScrollOffsets = true;		
		Sortable.create(
			AlbumDeUsuario.elementoAlbum, 
			{ 	
				onUpdate: AlbumDeUsuario.ajaxUpdate, 				
				constraint:"horizontal", 
				overlap:"horizontal",			
				scroll:this.scrollContainer,
				scrollSensitivity:50
			}
		);	
		
		if (typeof booUpdate == "undefined") booUpdate = false;
		if (booUpdate) this.ajaxUpdate();
	}
}

