
/**
 * Submenu da foto
 */
var MenuFoto = {
	flog:null,
	init:function( flog ) {
		this.flog = flog;
	},
	onMouseOver:function(ahref) {
	},
	onMouseOut:function(ahref) {
	},
	wait:function( text ) {
		this.resizeTo(32);
		var img = this.$new('img');
		img.src = '/estatico/imagens/carregando_gif.gif';	
		img.alt = "Carregando";
		img.title = "Carregando";
		$('opc').appendChild(img);
		if ( text ) {
			var span = document.createElement('span');
			span.innerHTML = text;
			span.style.marginTop = '6px';
			span.style.marginLeft = '4px';
			img.className = 'imgLeft';
			$('opc').appendChild(span);
			
		} else { 
			img.style.margin  = '0px auto 0';
		}
		
	},

	
	addEnterHandler:function( func ) {
		window.onkeydown = this.onKeyDown.bind(this);
		this._enter_handler = func;
	},
	addEscHandler:function( func ) {
		window.onkeydown = this.onKeyDown.bind(this);
		this._esc_handler = func;
	},

	onKeyDown:function( ev ) {
		var ev = ev || window.event
		if ( ev.keyCode == 27 && this._esc_handler ) {
			this._esc_handler();
		} else if ( ev.keyCode == 13 && this._enter_handler ) {
			this._enter_handler();
		}	
	},	
	
	clear:function() {
		document.getElementById('opc').innerHTML = '';
	},
	resizeTo:function(height) {
		if ( height > 0 ) {
			Anotacao.clear2();
			Anotacao.disable();
		} else {
			Anotacao.enable();
		}
		this.clear();
		var h = $('menuFoto').offsetHeight;
		new fx.Height('menuFoto', {transition:fx.quadOut, duration:300}).custom(h, height);
	},


	/*
	 * Copiar soh Albuns - fluxo 
	 */
	copiarSoAlbum:function() {
		this.wait();
		Util.loadAlbuns(this.flog.fotologId, this.onLoadSoAlbum.bind(this) );		
	},
	onLoadSoAlbum:function(json) {
		
		this.clear();
		this.resizeTo(54);
		this.mesmo_album = true;
		var container = document.getElementById('opc');
		
		var label = document.createElement('label');
		label.style.width = '31%';
		label.appendChild(document.createTextNode('Álbuns deste Flog:'));
		container.appendChild(label)
		container.appendChild(document.createElement('br'))
		container.appendChild(document.createElement('br'))
		
		var select = document.createElement('select');
		select.style.width = '135px';
		select.style.marginLeft = '0';
		for( var i = 0; i < json.length; i++ ) 
		{
			select.options[i] = new Option(json[i].titulo, json[i].aid);
		}
		this._select2 = select;

		container.appendChild(select)
		container.appendChild(this._createButton('COPIAR', this.onCopiarAlbum));
		container.appendChild(this._createButton('CANCELAR', this.onClose));		
	
		this.addEnterHandler(this.onCopiarAlbum.bind(this));
		this.addEscHandler(this.onClose.bind(this));		


	},
	/*
	 * Copiar para Album - fluxo 
	 */
	copiarAlbum:function() {
		this.wait();
		this.addEnterHandler(this.onCopiarAlbum.bind(this));
		this.addEscHandler(this.onClose.bind(this));		
		if ( this._fotolog ) {
			this.onLoadFotolog( this._fotolog );
			return;
		}
		Util.loadFotologs( this.onLoadFotolog.bind(this) ); 
		
	},
	onLoadFotolog:function(json) {
		this._fotolog = json;
		this._selectedFotolog = json[0].fid;
		Util.loadAlbuns(json[0].fid, this.onLoadAlbum.bind(this) );
	},
	getSelectedAlbum:function() {
		var s = this._select.options;
		var x = this._select.selectedIndex;
		if ( this._select.options[this._select.selectedIndex].disabled ) {
			this._select.selectedIndex++;
		}
		return this._select.options[this._select.selectedIndex].value;
	},
	onChangeAlbum:function() {
		var x = this.getSelectedAlbum();
		this._selectedFotolog = this.getSelectedAlbum();
		Util.loadAlbuns( this._selectedFotolog, this.onLoadAlbum.bind(this) );
	},
	onLoadAlbum:function(json) {
		

		this.clear();
		this.resizeTo(54);
		

		var container = document.getElementById('opc');
		
		var label = document.createElement('label');
		label.style.width = '31%';
		label.appendChild(document.createTextNode('Meu Flog/Grupos:'));
		container.appendChild(label)
		
		var label = document.createElement('label');
		label.style.width = '69%';
		label.appendChild(document.createTextNode('Álbuns:'));
		container.appendChild(label)
		container.appendChild(document.createElement('br'))
		
		//Fotolog:
		var select = document.createElement('select');
		select.style.width = '125px';
		select.style.marginLeft = '0';
		for( var i = 0; i < this._fotolog.length; i++ ) {
			select.options[i] = new Option(this._fotolog[i].titulo, this._fotolog[i].fid);
			if (this._fotolog[i].subItem == "sim") {
				select.options[i].style.color = "#BDB9B9";
				select.options[i].disabled = "true";
			}
			if ( select.options[i].value == this._selectedFotolog ) {
				select.options[i].selected = true;	
			}		
		}
	
		select.onchange = this.onChangeAlbum.bind(this);

		this._select = select;

		container.appendChild(select)		
		
		var select = document.createElement('select');
		select.style.width = '125px';
		//label.appendChild(document.createTextNode('Escolha o grupo:'));

		

		for( var i = 0; i < json.length; i++ ) {
			
			select.options[i] = new Option(json[i].titulo, json[i].aid);
		}
		this._select2 = select;

		container.appendChild(select)
		
		container.appendChild(this._createButton('COPIAR', this.onCopiarAlbum));
		container.appendChild(this._createButton('CANCELAR', this.onClose));		
		
		this.addEnterHandler(this.onCopiarAlbum.bind(this));
		this.addEscHandler(this.onClose.bind(this));		

	},
	onCopiarAlbum:function() {
		var albumId = this._select2.options[this._select2.selectedIndex].value;
		this._select2 = null;
		
		var fotologIDOrigem = this.flog.fotologId;
		var fotologIDDestino;
		if (  this.mesmo_album ) {
			fotologIDDestino = fotologIDOrigem;
		} else {
			fotologIDDestino = this._select.options[this._select.selectedIndex].value;
		}
		this.mesmo_album = false;
		

		this.wait('Copiando foto para álbum');
		// albumIDOrigem, fotosIDOrigem, albumIDDestino, fotologIDOrigem, fotologIDDestino, callback, errorCallback
		Fotolog.copiarParaAlbum( this.flog.albumId, this.flog.fotoId, albumId, fotologIDOrigem, fotologIDDestino, this.onCopiarAlbumSucesso.bind(this), this.onErro.bind(this) );
	},
	onCopiarAlbumSucesso:function( json ) {
		if ( json.isEditorial ) {
			this.sucesso('Foto enviada! Aguarde aprovação para visualizar a foto.');
		} else {
			this.sucesso('Copiada com sucesso.');
		}
	},
	
	loadInterface:function( url, callback ) {
		new glb.Ajax( url, {'update':'opc', onComplete:callback });
	},
	
	/**
	 * Enviar email
	 */
	 
	 
	enviarEmail:function( nome ) {
		this.nome = nome;
		this.resizeTo( 150 );	
		this.loadInterface('/fotolog/fotolog/foto_enviar_email.jsp', this.onEnviarEmailInterface.bind(this) );
	},
	onEnviarEmailInterface:function() {
		document.getElementById('nome').value = this.nome;
		document.getElementById('enviarBtn').onclick = this.onEnviarEmail.bind(this);
		document.getElementById('cancelarBtn').onclick = this.onClose.bind(this);

		this.addEnterHandler(this.onEnviarEmail.bind(this));
		this.addEscHandler(this.onClose.bind(this));	
	},
	onEnviarEmail:function() {
		var nome = document.getElementById('nome').value;
		var endereco = [];
		for ( var i = 1; i <= 4; i++  ) {
			var email = document.getElementById('email' + i).value;
			if ( email.length > 0 ) {
				endereco.push( email );
			}
		}
		this.wait('Enviando foto...');
		Fotolog.enviarFotoEmail(this.flog.albumId, this.flog.fotoId, this.flog.fotologId, nome, endereco, this.onEnviarEmailSucesso.bind(this), this.onErro.bind(this));
	},
	onEnviarMais:function() {
		//this.resizeTo(0);
		setTimeout( this.enviarEmail.bind(this), 500);
	},
	onEnviarEmailSucesso:function( json ) {
		this.resizeTo(32);
		var container = document.getElementById('opc');
		var label = document.createElement('label');
		label.innerHTML = 'Foto enviada com sucesso.';
		container.appendChild(label);
		container.appendChild(this._createButton('ENVIAR MAIS', this.onEnviarMais.bind(this) ));		
		container.appendChild(this._createButton('FECHAR', this.onClose));

		this.addEnterHandler(null);
		this.addEscHandler(this.onClose.bind(this));		
	
	
	},
	
	




	/**
	 * Excluir foto
	 */
	excluirFoto:function() {
		this.clear();
		this.resizeTo(32);
	 	
		//Monta tela.
		
		var container = document.getElementById('opc');
		
		var label = document.createElement('label');
		if( this.flog.tipoAlbum == "1") {
			label.appendChild(document.createTextNode('Confirma a exclusão da foto deste fotolog?'));
		}
		else {
			label.appendChild(document.createTextNode('Confirma a exclusão da foto deste álbum?'));
		}		
		container.appendChild(label);
		container.appendChild(this._createButton('EXCLUIR', this.onExcluirFoto));
		container.appendChild(this._createButton('CANCELAR', this.onClose));

		this.addEnterHandler(this.onExcluirFoto.bind(this));
		this.addEscHandler(this.onClose.bind(this));		


	},
	onExcluirFoto:function() {
		this.wait('Excluindo foto...');
		Fotolog.excluirFoto( this.flog.albumId, this.flog.fotoId, this.onExcluirFotoSucesso.bind(this) );
	},
	onExcluirFotoSucesso:function(json) {
		
		var ahref = document.getElementById('lnkProxima');
		if ( ahref == null ) {
			ahref = document.getElementById('lnkAnterior');
		}

		if ( ahref == null ) {
			ahref = (document.location+"").split("#")[0]; 	
		} else {
			ahref = ahref.href;
		} 

		document.location = ahref;

	},
	


	
	/**
	 * Denunciar
	 */
	denunciar:function() {
		//this.wait();
		if ( this._tipoDenuncia ) {
			this.onLoadDenuncias( this._tipoDenuncia );
			return;
		}		
		var tipoDenuncia = 0 // denuncia de foto
		Util.loadTipoDenuncias(tipoDenuncia, this.onLoadDenuncias.bind(this));
	},
	
	onLoadDenuncias:function( json ){
		if ( json.STATUS == 'ABORT' ) {
			this.clear()	
			this.resizeTo(0);
			return;
		}
		
		this.resizeTo(32);
		
		if ( !this._tipoDenuncia ) {
			this._tipoDenuncia = json;
		}
		
		var container = document.getElementById('opc');
		
		var label = document.createElement('label');
		label.appendChild(document.createTextNode('Escolha o motivo:'));
		container.appendChild(label)
		
		var select = document.createElement('select');
		this.denuncia = select;
		select.style.width = '120px';
		select.style.marginLeft = '0';

		for( var i = 0; i < this._tipoDenuncia.length; i++ ) {
			select.options[i] = new Option(this._tipoDenuncia[i].descricao, this._tipoDenuncia[i].fid);
		}
		container.appendChild(select)
		container.appendChild(this._createButton('DENUNCIAR', this.onDenunciar));
		container.appendChild(this._createButton('CANCELAR', this.onClose));	

		this.addEnterHandler(this.onDenunciar.bind(this));
		this.addEscHandler(this.onClose.bind(this));		
	
	
	},
	getDenunciaId:function() {
		var s = this.denuncia;
		return s.options[s.selectedIndex].value;
	},
	onDenunciar:function() {
		var denunciaId = this.getDenunciaId();
		this.wait("Denunciando usuário");		
		Fotolog.denunciar(this.flog.fotologId, this.flog.albumId, this.flog.fotoId, denunciaId, '', this.onDenunciarSucesso.bind(this) );
	},
	onDenunciarSucesso:function( json ) {
		if ( json.STATUS == "ERRO" ) {
			this.problem(json.ERROR);		
		} else {
			this.resizeTo(32);
			var container = document.getElementById('opc');
			var label = document.createElement('label');
			label.innerHTML = 'Usuário denunciado.';
			container.appendChild(label);
			container.appendChild(this._createButton('FECHAR', this.onClose));

			this.addEnterHandler(this.onClose.bind(this));
			this.addEscHandler(this.onClose.bind(this));		
		}
		
	},

	onErro:function( json ) {
		if ( json.STATUS == "ERRO" ) {
			this.problem(json.ERROR);
		} else {
			this.clear();	
		}	
	},
	

	

	sucesso:function( text ) {
		this.resizeTo(32);
		var container = document.getElementById('opc');
		Element.addClassName(container, 'copiarGrupoSucesso');
		var label = document.createElement('label');
		label.innerHTML = text;
		container.appendChild(label);
		container.appendChild(this._createButton('FECHAR', this.onClose));

		this.addEnterHandler(this.onClose.bind(this));
		this.addEscHandler(this.onClose.bind(this));		


	},

	onClose:function() {
		this.resizeTo(0);
		this.addEnterHandler(null);
		this.addEscHandler(null);
	},
	
	_createButton:function( label, event ) {
		var a = document.createElement('a');
		a.appendChild(document.createTextNode(label));
		a.onclick = event.bind(this);
		a.className = 'botao3';
		return a;
	},
	
	
	problem:function( texto ) {
		this.resizeTo(32);
		var container = document.getElementById('opc');
		var label = document.createElement('label');
		label.innerHTML = texto;
		container.appendChild(label);
		container.appendChild(this._createButton('FECHAR', this.onClose));

		this.addEnterHandler(this.onClose.bind(this));
		this.addEscHandler(this.onClose.bind(this));		

	},
	
	$new:function(name) {
		return document.createElement(name);
	}
}; //MenuFoto


/*
 * Tags
 */
var Tags = {
	alertId:'ajaxGrupoPalCha', 
	divId:'tags',
	clear:false,
	working:false,
	clearUL:function() {
		if ( !this.clear ) {
			Element.cleanWhitespace(this.divId);
			this.clear = true;
		}
	},
	add:function( webloggerID, fotoID, albumID ) {
		this.clearUL();

		this._webloggerID = webloggerID;
		this._fotoID = fotoID;
		this._albumID = albumID;
		
		document.getElementById(this.alertId).style.display = '';
		document.onkeyup = this.onKeyUp.bind(this);
	
	},
	onKeyUp:function( ev ) {
		var ev = ev || window.event;
		if ( ev.keyCode == 27 ) {
			this.onCancelar();
			document.onkeyup = null;
		}			
	},
	remove:function( ahref, webloggerID, fotoID, albumID, tagID ) {
		this.onCancelar();
		this.clearUL();
		Album.excluirTag( webloggerID, tagID, albumID, fotoID, this._onRemove.bind(this) );
		this._removing = ahref;
	},
	_onRemove:function() {
		try {
			var li = this._removing.parentNode;
			li.parentNode.removeChild(li);		
			this._removing = null;
		} catch( e ) {}
	},
	onSalvar:function( tag ) {
		this._tag = tag;
		Album.inserirTag( this._webloggerID, this._albumID, this._fotoID, tag, this._onComplete.bind(this));
		this.onCancelar();
	},
	_onComplete:function( json ) {

		//remove:function( ahref, webloggerID, fotoID, albumID, tagID ) {
		var tags = json.tags;
		for (var i=0; i<tags.length;i++) {
			
			var li = document.createElement('li');
			var a = document.createElement('a');
			a.href = 'javascript:;';
			a.className = 'lnk2P';
			a.appendChild( document.createTextNode(tags[i].descricao) );
			li.appendChild(a);
			
			li.appendChild( document.createTextNode(' ('));
			
			var a = document.createElement('a');
			a.href = 'javascript:;';
			a.className = 'lnk2P';
			
			var _webloggerID = this._webloggerID;
			var _fotoID = this._fotoID;
			var _albumID = this._albumID;
			
			var tag = {
				webloggerID:_webloggerID,
				fotoID:_fotoID,
				albumID:_albumID,
				tagID:tags[i].tagId,
				ahref:a,
				remove:function( ahref ) {
					Tags.remove(this.ahref, this.webloggerID, this.fotoID, this.albumID, this.tagID);
				}
			}
			a.onclick = tag.remove.bind(tag);
			a.appendChild( document.createTextNode( 'x' ) );
			li.appendChild(a);
			li.appendChild( document.createTextNode(')'));
			Element.cleanWhitespace( this.divId );	
			document.getElementById(this.divId).insertBefore(li, document.getElementById(this.divId).lastChild);		
		}
	},
	onCancelar:function() {
		document.getElementById(this.alertId).style.display = 'none';
	}
};




function getLoadFoto() {
	//var base = (document.location+"").split('#')[0];
	var tokens = (document.location+"").split('#');
	if ( tokens.length == 2 ) {
		return tokens[1];
	}
	return false;
}

var Navegacao = {
	///_regex:/^a([0-9]+)-([0-9]+)$/,
	
	_regexP:/^(http:\/\/[^\/]*)\/([^\/]+)\/flog(\/a([0-9]+))?(\/([0-9]+))?/, //Para Link de album pessoal
	_regexG:/^(http:\/\/[^\/]*)\/grupo\/([^\/]+)\/flog(\/a([0-9]+))?(\/([0-9]+))?/, //Para link de Grupo
	_regex:null,
	
	_location:null,
	_base:null,
	init:function(isLogado) {
		
		this.isLogado = isLogado;
		var base = ( document.location + "").split('#').shift();
		
		var a;
		
		//É grupo
		if ( a = base.match( this._regexG )) {
			this._base =  "/grupo/" + a[2] + "/flog/";
			this._regex = this._regexG;
		}
		
		//É Pessoal
		if ( a = base.match( this._regexP )) {
			this._base =  "/" + a[2] + "/flog/";
			this._regex = this._regexP;
		}
		
		this.updateLocation();
		
		setInterval( this.onCheckChange.bind(this), 400);
	
		this.loadFoto( document.location + "");
	},
	
	//Atualiza location
	updateLocation:function() {
		this._location = document.location + "";
	},


	// retorna a foto
	extractFoto:function( url ) {
		var t;
		if ( t  = url.match( /#a([0-9]+)-([0-9]+)/ ) ) {
			return {
				albumId:(t[1])?parseInt(t[1]):null,
				fotoId:(t[2])?parseInt(t[2]):null
			};
		} else if ( t  = url.match( /#([0-9]+)/ ) ) {
			return {
				albumId:null,
				fotoId:(t[1])?parseInt(t[1]):null
			};
		} else {
			var t = url.match( this._regex );
			if ( t && t[3] ) {
				return {
					albumId:(t[4])?parseInt(t[4]):null,
					fotoId:(t[6])?parseInt(t[6]):null
				};			
			} else {
				return {
					albumId:null,
					fotoId:(t[6])?parseInt(t[6]):null
				};				
			}
		}
	},
	
	
	
	loadFoto:function( a ) {
		
		if ( typeof a == 'string' ) {
			var foto = this.extractFoto(a);
		} else if ( typeof a == 'object' && a.nodeName == 'A' ) {
			var foto = this.extractFoto(a.href);	
		} else if ( typeof a == 'object' ) {
			var foto = a;
		} else {
			return false;
		}
		
		var loc = (document.location+"").split("#").shift() + '#'; 
		var url = this._base; 	

		if ( foto.albumId ) {
			url += 'a' + foto.albumId + "/";
			loc += 'a' + foto.albumId;
		}
		if ( foto.fotoId ) {
			url += foto.fotoId + "/";
			if ( foto.albumId ) {
				loc += "-";
			}
			loc += foto.fotoId;
		}
		this.ultimaUrl = url;		
		url += 'foto?hash=' + new Date().getTime();
		
		document.location = loc; 
		this.updateLocation();
		this.updateCarregando();
		new glb.Ajax( url, {update:'meio', 'method':'get', onComplete:this.onLoad.bind(this)});
	},	
	
	onLoad:function( json ) {
		if ( json ) { 
			if ( typeof this.isLogado != "undefined" && typeof json.flog.isLogado != "undefined" && json.flog.isLogado != this.isLogado ) {
				document.location = this.ultimaUrl;
				return;
			}
		
			if ( json.flog.isDonoFoto ) {
				new f8p.Inline('fotoTitulo', json.flog, Album.saveInlineTituloFoto, false, false, 50);
				new f8p.Inline('fotoDescricao', json.flog, Album.saveInlineDescricaoFoto, 'Clique para editar', true, 6000);
			}
			
			var atual = document.getElementById('album_'+json.flog.albumId);
			if ( atual != null ) {
				var albuns = atual.parentNode;
				for( var i = 0; i < albuns.childNodes.length; i++ ) {
					if ( albuns.childNodes[i].nodeType != 1 ) {
						continue;	
					}
					if ( albuns.childNodes[i] == atual ) {
						albuns.childNodes[i].style.display = 'none';
					} else {
						albuns.childNodes[i].style.display = '';
					}	
				}
			}
			MenuFoto.init( json.flog );
			Comentario.init(json.flog);
			
			
			var foto = document.getElementById('foto');
			if ( foto == null ) {
				return;
			}
			
			//Verifica se existe anotação
			var hasAnotacoes = ( typeof json.flog.hasAnotacoes == "undefined" || json.flog.hasAnotacoes == true);
			var img = document.createElement('img');
			img.onload = function() {
				var area = document.getElementById('area');
				Anotacao.init('area', json.flog, hasAnotacoes);
			}
			img.src = foto.src;

		}
	},
	
	onCheckChange:function() {
		var l = document.location + "";
		if ( this._location == null ) {
			return false;
		}
		if ( this._location != l ) {
			this.updateLocation();
			this.loadFoto( document.location + "" );
		};
	},
	
	
	updateCarregando:function() {
		document.getElementById('meio').innerHTML = '';
		var img = document.createElement('img');
		img.src = '/estatico/imagens/carregando_fotolog.gif';
		img.className = 'loading';
		document.getElementById('meio').appendChild(img);
	}

	
	


	
};

//Navegacao.init();



function loadFotoByUrl( url, anchor ) {
	Navegacao.loadFoto( url );
}



function loadFoto( a ) {
	Navegacao.loadFoto( a );
	return false;
}


function trocarConteudo(json) {	
}

function loadComentarios(foto, album, page)
{
	Comentario.load(page);
}
function loadComentariosGrupo(foto, album, page)
{
	Comentario.loadGrupo(page);
}

/**
 * Remove os options de um combo
 */
function removeComboOptions(combo)
{
	var size = combo.options.length;
	for (var i = 0; i < size; i++)
	{
		combo.options[0] = null;
	}
}


var Comentario  = {
	flog:false,
	init:function( flog ) {
		this.flog = flog;
		if ( document.getElementById("FormComent") != null ) {
			f8p.util.updateRest('comentario', 'contComentario', 1000);		
		}
		if ( document.getElementById("FormRespComent") != null ) {
			f8p.util.updateRest('comentarioResp', 'contComentarioResp', 1000);		
		}
	},
	load:function( pagina ) {
		var url = "/users/ComentariosVisualizar.ssp?"
		url += "foto="+this.flog.fotoId;
		url += "&album="+this.flog.albumId;
		url += "&pg="+pagina;
		url += "&random="+Math.random();
		new glb.Ajax( url, {update:'coment', 'method':'get', 'onComplete':this.onLoad.bind(this)});		
	},
	loadGrupo:function( pagina ) {
		var url = "/grupos/ComentariosVisualizar.ssp?"
		url += "foto="+this.flog.fotoId;
		url += "&album="+this.flog.albumId;
		url += "&pg="+pagina;
		url += "&random="+Math.random();
		new glb.Ajax( url, {update:'coment', 'method':'get', 'onComplete':this.onLoad.bind(this)});		
	},
	onLoad:function() {
		if ( this.moderado ) {
			var el = document.getElementById("avisoComentario");
			if ( el ) {
				el.style.display = "block";
			}
		}
	},
	onSend:function( ahref ) {
		try {
			
			var comentario = document.getElementById('FormComent').value;
			if (comentario.trim().length == 0) {
				return;
			}
			
			var imgRoboResp = document.getElementById('imagemAntiRoboResp');
			if ( imgRoboResp != null && imgRoboResp.style.display == '' ) {
				document.getElementById("btEnviarResp").style.display = ''
				document.getElementById("imagemAntiRoboResp").style.display = 'none';		
				document.getElementById("FormAntiRoboResp").value = '';	
			}
			
			var imgRobo = document.getElementById('imagemAntiRobo');
			
			if ( imgRobo.style.display == 'none' ) {
				ahref.style.display = 'none';
				imgRobo.style.display = '';
				setTimeout(function() {
					document.getElementById('imgRobo').src = '/flog/publico/imagemAntiRobo.ssp?'+ Math.random();
				}, 100);
				return;
			}

			
			document.getElementById('contComentario').innerHTML = '1000';

			var nome = document.getElementById('FormNome');
			var url = document.getElementById('FormURL').value;
			var stringAntiRobo = document.getElementById('FormAntiRobo');
			var urlPost = "";
			if ( nome != null ) {
				urlPost = "/flog/publico/ajax/comentarioIncluir.ssp";
				this.post( nome.value, comentario, url, stringAntiRobo.value, urlPost);	
				return;
			}
			
			var usuario = document.getElementById('FormUsuario');
			if ( usuario != null ) {
				urlPost = "/flog/logado/ajax/comentarioIncluir.ssp";
				this.post( usuario.value, comentario, url, stringAntiRobo.value, urlPost);				
				return;	
			}
		
			
		} catch( e ) { alert(e); }			
	},
	post:function(nome, texto, url, stringAntiRobo, urlPost) {
		var box = document.getElementById('BoxFormComent');
		Fotolog.inserirComentario(
			this.flog.albumId,
			this.flog.fotoId,
			nome,
			texto,
			this.flog.fotologId,
			url,
			stringAntiRobo,
			urlPost,
			"",
			this.onPost.bind(this)
		);
		
	},
	onPost:function( json ) {
		if ( json.STATUS == 'ERRO' ) {
			Erro(json.ERROR);
			document.getElementById('imgRobo').src = '/flog/publico/imagemAntiRobo.ssp?'+ Math.random(); 
			document.getElementById('FormAntiRobo').value = '';
		} else {
			try {
				document.getElementById('btEnviar').style.display = '';
				document.getElementById('FormComent').value = '';
				document.getElementById('FormAntiRobo').value =  '';
				document.getElementById('imagemAntiRobo').style.display = 'none';
				document.getElementById('FormNome').value = '';
			} catch (e) {};
			this.moderado = json.moderado;
			this.load(json.PAGINA);
		}

	},
	excluir:function( ahref, comentarioId ) {
		this._remove = ahref.parentNode;
		Fotolog.excluirComentario( comentarioId, this.flog.albumId, this.flog.fotoId, this.onExcluir.bind(this));
	},
	onExcluir:function(json) {
		var eff = new fx.Opacity(this._remove, {onComplete:function(){
				Element.remove( this.el );
				try {
					var total = document.getElementById('totalComentario').innerHTML;
					document.getElementById('totalComentario').innerHTML = --total;
					if ( total == 0 ) {
						Comentario.load(1);	
					}
				} catch( e ){ }
			}
		});
		this._remove = null;
		eff.now = 0;
		eff.setOpacity(1);
		eff.custom(1, 0);		
	},
	responder:function( ahref, userDestino, apelidoDestino ) {
		var box = ahref.parentNode;
		var tmp = document.getElementById("BoxFormRespComent");
		tmp.style.display = 'none';

		//limpando tudo
		document.getElementById("btCancelarResp").style.display = ''
		document.getElementById("btEnviarResp").style.display = ''
		document.getElementById("imagemAntiRoboResp").style.display = 'none';		
		document.getElementById("FormAntiRoboResp").value = '';
		document.getElementById("FormRespComent").value = '';
		document.getElementById('contComentarioResp').innerHTML = '1000';
		
		if ( tmp ) {
			var p = tmp.parentNode;
			var c = p.removeChild(tmp);
			box.appendChild(c);
			c.style.display = '';
		}
		
		this.userDestino = userDestino;
		this.apelidoDestino = apelidoDestino;
	},
	
	cancelarResposta:function( ahref ) {
		document.getElementById('BoxFormRespComent').style.display = 'none';
	},
	
	criarAviso:function(obj, titulo, texto, url, classe) {
		var div = document.createElement("div");
		div.className = "avisoComentario " + classe;
		div.style.clear = "both";
		var a = document.createElement("a");
		a.className = "fechar";
		a.innerHTML = "x";
		a.href = "javascript:;";
		a.onclick = function(){this.parentNode.style.display='none';};
		div.appendChild(a);
		
		var h3 = document.createElement("h3");
		h3.innerHTML = titulo;
		div.appendChild(h3);

		if ( url == undefined ) { //e um erro.
			div.style.backgroundColor = "#FFF0B5";
			div.style.borderColor = "#FF8C03";		
			var span = document.createElement("span");
			span.innerHTML = texto;					
			div.appendChild(span);
		} else {
			var link = document.createElement("a");
			link.href = url;
			link.innerHTML = texto;					
			div.appendChild(link);
		}
		obj.appendChild(div);
	},

	onSendResp:function( ahref ) {
		try {
			
			var comentario = document.getElementById('FormRespComent').value;
			if (comentario.trim().length == 0) {
				return;
			}
						
			var imgRobo = document.getElementById('imagemAntiRobo');
			if ( imgRobo != null && imgRobo.style.display == '' ) {
				document.getElementById("btEnviar").style.display = ''
				document.getElementById("imagemAntiRobo").style.display = 'none';		
				document.getElementById("FormAntiRobo").value = '';	
			}
			
			var imgRoboResp = document.getElementById('imagemAntiRoboResp');
			
			if ( imgRoboResp.style.display == 'none' ) {
				ahref.style.display = 'none';
				imgRoboResp.style.display = '';
				setTimeout(function() {
					document.getElementById('imgRoboResp').src = '/flog/publico/imagemAntiRobo.ssp?'+ Math.random();
				}, 100);
				return;
			}
			
			document.getElementById('contComentarioResp').innerHTML = '1000';

			document.getElementById('FormURLResp').value = document.getElementById('FormURL').value;
			
			var url = document.getElementById('FormURLResp').value;

			var stringAntiRoboResp = document.getElementById('FormAntiRoboResp');
			var urlPost = "";
			
			var usuario = this.userDestino;

			if ( usuario != null ) {
				urlPost = "/flog/logado/ajax/comentarioResponder.ssp";
				this.postResponder( usuario, comentario, url, stringAntiRoboResp.value, urlPost);				
				return;	
			}
		
			
		} catch( e ) { alert(e); }			
	},
	postResponder:function(nome, texto, url, stringAntiRobo, urlPost) {
		var box = document.getElementById('BoxFormComent');
		Fotolog.inserirComentario(
			this.flog.albumId,
			this.flog.fotoId,
			nome,
			texto,
			this.flog.fotologId,
			url,
			stringAntiRobo,
			urlPost,
			this.apelidoDestino,
			this.onPostResponder.bind(this)
		);
		
	},
	onPostResponder:function( json ) {
		var titulo = "";
		var texto = "";
		var origem = (json.origemCadun == 'FLOG' || json.origemCadun == 'GRUPO');
		var classe = "avisoComentarioExtraFlog";
		
		if(json.origemCadun == 'GRUPO') {
			classe = "avisoComentarioExtraGrupo";
		}
		
		if ( json.STATUS == 'ERRO' ) {
			
			if (json.erroPop) {
				Erro(json.ERROR);
				if(!origem) {
					document.getElementById('imgRoboResp').src = '/flog/publico/imagemAntiRobo.ssp?'+ Math.random(); 
					document.getElementById('FormAntiRoboResp').value = '';
				}
			}
			else {
				titulo = "Ops! mensagem não enviada";
				if (json.semFoto && !origem) {
					texto = this.apelidoDestino + " " + json.ERROR;
				}else if (json.semFoto && origem) {
					texto = json.apelido + " " + json.ERROR;
				} else {
					texto = json.ERROR;
				}

			if(!origem) {
				document.getElementById("BoxFormRespComent").style.display = 'none';
				this.criarAviso(document.getElementById('BoxFormRespComent').parentNode, titulo, texto, link);
			} else {
				this.criarAviso(document.getElementById('tableFlog').parentNode, titulo, texto, link, classe);
			}
				
			}
		} else {
			try {
				document.getElementById('btCancelarResp').style.display = '';
				document.getElementById('btEnviarResp').style.display = '';
				document.getElementById('FormRespComent').value = '';
				document.getElementById('FormAntiRoboResp').value =  '';
				document.getElementById('imagemAntiRoboResp').style.display = 'none';
				document.getElementById("BoxFormRespComent").style.display = 'none';
			} catch (e) {};
			
			titulo = "Resposta enviada com sucesso!";
			var link = json.urlDestino;
			
			if(!origem) {
				texto = json.mensagem + " " + this.apelidoDestino + " »";
				this.criarAviso(document.getElementById('BoxFormRespComent').parentNode, titulo, texto, link);
			} else {
				texto = json.mensagem + " " + json.apelido + " »";
				this.criarAviso(document.getElementById('tableFlog').parentNode, titulo, texto, link, classe);
			}
		}
	},	

	login:function() {
		document.location =  urlLogin + "?url="+ document.location.pathname.substring(1);	
	},
	//POG FUNCAO CHAMADA APOS O SUCESSO LOGIN
	send:function() {
		Navegacao.loadFoto( this.flog );
	}
};



var Blast = {
	opened:false,
	handler:null,
	div:null,
	color:'#E80202',
	perfil:function( ref, webloggedId, tipoUsuarioWebloggerId ) {
		this.open(ref, webloggedId, tipoUsuarioWebloggerId, Fotolog.saveBlast);
	},
	grupo:function( ref, webloggedId ) {
		this.open(ref, webloggedId, 0, Grupo.saveBlast);
	},
	open:function( element_ref, webloggerId, tipoUsuarioWebloggerId, handler ) {
		/*var mensagem = '';
		for ( var i = 0; i < element_ref.childNodes.length; i++ ) {
			var node = element_ref.childNodes[i];
			if ( node.nodeType == 3 ) {
				mensagem += node.nodeValue;			
			}
		}*/
		var mensagem = document.getElementById("blast_save").innerHTML;
			
		//mensagem = mensagem.replace(/\n/g, "");
		this.element = element_ref;
		this.webloggerId = webloggerId;
		this.handler = handler;
		this.texto = mensagem;
		this._restore = mensagem;

		if ( this.div == null ) {
			if(tipoUsuarioWebloggerId > 1) {
				new glb.Ajax('/fotolog/global/edit_blast_generico.jsp', {onComplete:this.onLoad.bind(this)});
			}
			else {
				new glb.Ajax('/fotolog/global/edit_blast.jsp', {onComplete:this.onLoad.bind(this)});
			}		
		}
	},
	onLoad:function( x, transport ) {
		var tmp = document.createElement('div');
		tmp.innerHTML = transport.responseText;
		this.div = tmp.removeChild( tmp.firstChild );
		var offset = cumulativeOffset( this.element );
		this.div.style.top = offset[1] + 'px';
		this.div.style.left = offset[0] + 'px';
		offset = null;
		var eff = new fx.Opacity(this.div, {duration:300});
		eff.now = 0;
		eff.setOpacity(0); 
		document.body.appendChild(this.div);
		document.getElementById('FormDigMsg').value = this.texto;
		tmp = null;
		eff.custom(0,1);
		document.onkeyup = this.onKeyDown.bind(this);
	},
	onKeyDown:function( ev ) {
		var ev = ev || window.event
		if ( ev.keyCode == 27 ) {
			this.close();
		} else if ( ev.keyCode == 13 ) {
			this.onSave( document.getElementById('FormDigMsg').value );
		}	
	},
	
	onClick:function( element ) {
		this.color = glb.util.rgb2hex(element.style.backgroundColor);
	},
	onSave:function( text ) {
		this.handler( this.webloggerId, this.color, escape(text), this.onSaveComplete.bind(this) );
		this.element.style.backgroundColor = this.color;
		if ( text.length == 0 ) {
			this.empty = true;
			this.element.innerHTML = "clique e coloque sua mensagem";
			this.color = '#E80202';
			document.getElementById("blast_save").innerHTML = "";
		} 
		else {
			this.empty = false;
			//this.element.innerHTML = text;
		}
		this.element.style.backgroundColor = this.color;
		this.close();
	},
	onSaveComplete:function( json ) {
		if ( json.STATUS == 'ERRO' ) {	
			Erro(json.ERROR);		
			this.element.innerHTML = this._restore;
		}
		else
		{
			if(json.TEXTO.length == 0 ) {
				this.element.innerHTML = "clique e coloque sua mensagem";
				document.getElementById("blast_save").innerHTML = "clique e coloque sua mensagem";
			} else {
				this.element.innerHTML = json.TEXTO;			
				document.getElementById("blast_save").innerHTML = json.ORIGINAL;
			}
		}
		this.close();
	},
	onCancel:function() {
		this.close();
	},
	close:function() {
		document.onkeyup = null;
		try {
			document.body.removeChild( this.div );
			this.div = null;
		} catch (e) {}
	}
};


function divOpen( ahref, divId, prepend ) {
	if ( ahref.innerHTML == (prepend||'')+'[+]' ) {
		document.getElementById(divId).style.display = '';
		ahref.innerHTML = (prepend||'')+'[-]';
	} else {
		document.getElementById(divId).style.display = 'none';	
		ahref.innerHTML = (prepend||'')+'[+]';
	}

}

var Box = {
	boxList:[],
	registered:false,
	init:function( boxId ) {
		if ( !this.registered ) {
			Event.observe(window, 'load', this.onLoad.bind(this));
			this.registered = true;
		}
		this.boxList.push( boxId );
	},
	onLoad:function() {
		for ( var i = 0; i < this.boxList.length; i++ ) {
			this.initBox(this.boxList[i]);
		}
	},
	initBox:function( boxId ) {
		var div = document.getElementById(boxId);
		Element.cleanWhitespace(div);
		if ( div.firstChild.nodeName == 'H3' ) {
			Element.cleanWhitespace(div.firstChild);
			var a = div.firstChild.lastChild;
			
			if ( div.childNodes[1].className != 'line' ) {
				return;
			}			
			var content = div.childNodes[2];
			
			content.id = boxId + '$';
			
			var eff = new RememberBox(content, {transition:fx.quadIn, onComplete:function(){
					var size = parseInt(this.el.style.height);
					if ( size > 0 ) {
						this.el.style.height = '';
					}
				}});
				
			if ( eff.closed ) {
				a.innerHTML = '[+]';
			} else {
				a.innerHTML = '[-]';		
			}
	
			a.onclick = function() {
				this.blur();
				if ( parseInt(eff.fx.el.style.height) == 0 ) {
					this.innerHTML = '[-]';
				} else {
					this.innerHTML = '[+]';		
				}
				eff.toggle();
				return false;
			}			
		}
	}
};

function popFotoPerfil( perfilId ) {
	var url = "/flog/logado/fotologUploadPerfilVisualizar.ssp?perfilID=" + perfilId;
	glb.util.popup(url, "popImagemPerfilPessoal", 300, 270, "");
}

function popFotoGrupo( grupoId ) {
	var url = "/flog/logado/fotologUploadPerfilVisualizar.ssp?fotologGrupoID=" + grupoId;
	glb.util.popup(url, "popImagemPerfilGrupo", 300, 270, "");
}

function msgCallBack(json){
	if(json.STATUS=="OK"){
		showAlert("Novo contato incluído com sucesso no seu 8P!");
		document.getElementById("linkMe").style.display="none";
	}
	//document.getElementById("linkMe").style.display="none";
}


var LinkMe = {
	ahref:null, //backup do link.	
	parentNode:null,
	link:function( ahref, webloggerId, isLogado ) {
		
		this.parentNode = ahref.parentNode; 
		this.ahref = this.parentNode.removeChild( ahref );
		if(isLogado) {
			var img = document.createElement('img');
			img.src = '/estatico/imagens/carregando_gif.gif';
			this.parentNode.appendChild( img );
		}
		User.addFlogLink( webloggerId, this.onCallback.bind(this) );
	
	},
	onCallback:function( json ) {
		//removendo imagem
		while ( this.parentNode.firstChild != null ) {
			this.parentNode.removeChild( this.parentNode.firstChild );
		}
		
		if ( json.STATUS == 'OK' ) {
			showAlert("Novo contato incluído com sucesso no seu 8P!");
			this.parentNode.style.display="none"	
		} else {
			if ( json.STATUS == 'ERRO' ) {
				Erro( json.ERROR );
			}
			//recupera link anterior
			this.parentNode.appendChild( this.ahref );
		}
		this.parentNode = null;
		this.ahref = null;
	}
};


/* carrega album */
function loadAlbum( fotologId, albumId, page, obj ){
	if ( obj ) {
		loadFoto(obj);
	}
//	var url = "/users/FotosVerTodas.ssp?albumId="+albumId+"&fotologId="+fotologId+"&box=true&pg="+page;
	var url = "/fotolog/fotolog/action_fotosvertodas.jsp?albumId="+albumId+"&fotologId="+fotologId+"&box=true&pg="+page;
	new glb.Ajax(url, {update:'BoxAlbumAtual$'} );
}

/* carrega album */
function loadAlbumGrupo( fotologId, albumId, page, obj ){
	if ( obj ) {
		loadFoto(obj);
	}
//	var url = "/grupos/FotosVerTodas.ssp?albumId="+albumId+"&fotologId="+fotologId+"&box=true&pg="+page;
	var url = "/fotolog/fotologgrupo/action_fotosvertodas.jsp?albumId="+albumId+"&fotologId="+fotologId+"&box=true&pg="+page;
	new glb.Ajax(url, {update:'BoxAlbumAtual$'} );
}


var Convite = {
	grupoComunidadeID:null,
	webloggerID:null,

	open:function( webloggerID, grupoComunidadeID) {
		this.grupoComunidadeID = grupoComunidadeID;
		this.webloggerID = webloggerID;

		glb.dom.show('ajaxGrupoEmail');
		new fx.Scroll().scrollTo('ajaxGrupoEmail');
		$('email1').focus();
	},
	close:function() {
		for ( var i = 1; i <= 3; i++ ) {
			$('email'+i).value = "";
		}
		glb.dom.hide('ajaxGrupoEmail');
	},
	send:function() {
		var apelidos = [];
		
		for ( var i = 1; i <= 3; i++ ) {
			if ( $('email'+i).value.trim().length > 0 ) {
				apelidos.push( $('email'+i).value.trim() );
			}
		}
		
		if ( apelidos.length > 0 ) {		
			Grupo.enviarConvite( this.webloggerID, this.grupoComunidadeID, apelidos, this.onSend.bind(this));
			glb.dom.hide('ajaxGrupoEmail');
			glb.dom.show('ajaxEmailDef');
		}
	},
	onSend:function( json ) {
		if ( json.STATUS == 'ERRO' ) {
			glb.dom.hide('ajaxEmailDef');
			glb.dom.show('ajaxGrupoEmail');
			Erro(json.ERROR);
		} else {
			glb.dom.hide('ajaxEmailDef');
			document.getElementById('msgFinalEmail').innerHTML='Convite(s) enviado(s) com sucesso.';
			glb.dom.show('ajaxEmailDefSuc');
			//limpando
			for ( var i = 1; i <= 3; i++ ) {
				$('email'+i).value = '';
			}
		}
	}

};

function atualizarImagem(imagemID)
{
	var img = document.getElementById("imgPerfil");
	if ( img != null ) {
		img.src = "/flog/logado/visualizarFoto?imagemID=" + imagemID;
		return;
	}
	var img = document.getElementById("boxFotoPerfil");
	if ( img != null ) {
		img.style.backgroundImage = "url(/flog/logado/visualizarFoto?imagemID=" + imagemID + ")";
		return;
	}
	
	
	
}