var staticHostHapping = staticHostHapping ? staticHostHapping : ""; 
var securedHostHapping = securedHostHapping ? securedHostHapping : ""; 

var apiHostAndContextRoot = apiHostAndContextRoot ? apiHostAndContextRoot : ""; 
var EntronqueData = {
	isPublic : false,
	typeWindow : null,
	action : null,
	lwTitle : null,
	lwWidth : 825,
	lwHeight : 426,
	lwTop : NaN,
	lwLeft : NaN,
	registryType: null
};

var Logged = {
	tipoRegistro: null,
	fromNav: false,
	reloadPage: false,
	actionPos: null,
	
	checkEntronque : function(isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft)
	{
		return Logged.checkNavigation('C',isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft);
	
	},

	checkPrincipal : function(isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft)
	{
		return Logged.checkNavigation('P',isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft);
	
	},
	
	checkBasico : function(isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft)
	{
		return Logged.checkNavigation('B',isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft);
	
	},
	
	checkCompleto : function(isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft)
	{
		return Logged.checkNavigation('C',isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft);
	
	},
	
	// lwTop y lwleft son optativas
	checkNavigation : function(registryType, isPublic, typeWindow, action, lwTitle, lwWidth, lwHeight, lwTop, lwLeft)
	{
		window.Logged.fromNav=true;
		
		EntronqueData.isPublic = isPublic;
		EntronqueData.typeWindow = typeWindow;
		EntronqueData.action = action;
		EntronqueData.lwTitle = lwTitle;
		EntronqueData.lwWidth = lwWidth;
		EntronqueData.lwHeight = lwHeight;
		EntronqueData.lwTop = lwTop;
		EntronqueData.lwLeft = lwLeft;
		EntronqueData.registryType = registryType;
		
		// si no esta logado, a la pantalla de login
		if( !window.Logged.isLogged() ){
			window.Logged.actionPos=action;
			//myHappingUserApi.openLogin({tipoRegistro:registryType});
			action = "/login" + ((action.indexOf("/",0)==0) ? "" : "/") +  escape(action);
		}
		// segun el tipo de registro entroncamos o vamos a la accion
		//var valid = Logged.convertRegistryTypeToNumber(registryType);
		//var user = Logged.convertRegistryTypeToNumber(window.Logged.tipoRegistro);
		if( false /*!isPublic && valid > user */ ){
		//	window.Logged.actionPos = action;
		//	myHappingUserApi.signup({tipoRegistro:registryType});
		} else {
			if( typeWindow=='L' ){
				// abrir un LW con la accion que viene por param, 
				// un poco diferido, por bug emergente con prototype...
				var diferido = 1;
				new PeriodicalExecuter(
					function(pe) {
						myLightWindow.activateWindow(
							{href: action, title: lwTitle, type: 'external',width: lwWidth,
							height: lwHeight, top: lwTop, left: lwLeft, iframe_embed: true}
						);
				    	pe.stop();
					}, diferido
				);
				
			} else {
				if( typeWindow == 'R' ){
					lwTop = lwTop + lwHeight/2 + 20;
					lwLeft = lwLeft + lwWidth/2 + 3;
					myredwindow.activateWindow( {
						href: action, title: lwTitle, type: 'external', iframe_embed: true,
						width: lwWidth, height: lwHeight, top: lwTop, left: lwLeft
					} );	
				} else {
					//si es object presuponemos un array ['function_name',param1, param2,...]
					//ej: ['alert','hola']
					//ej2: ['mifunc','paramstring1',5,'hola']
					if (typeof( action ) == "object") {
						var f = action[0] + '(';
						if (typeof( action[1] ) != "object") {
							for (i = 1; i < action.length; i++) {
								f += (Object.isString(action[i])) ? '\'' + action[i] + '\'' : action[i];
								if (i < action.length - 1 ) {
									f += ',';
								}
							}
						} else {
							// prototype style
							var h = Logged.convertHashToString($H(action[1]).toArray()); 
							if (h=='{}') h = '';
							f += h; 
						}
						f += ')';
						new PeriodicalExecuter( function(pe) {
							eval (f);
							pe.stop();
						},0.1 );
						window.Logged.fromNav = false;
					} else {
						// action puede ser una URL o una funcion
						if(Object.isFunction(action)){
							action();
						} else {
							// es una url
							document.location.href = action;
						}	
					}
				}
			}
		}
		return false;
	},

	convertHashToString : function (hash) {
		var f = '{';
		var firstAdded = false;
		hash.each(function(pair) {
			if (!Object.isUndefined(pair.value) && pair.value!=null ) {
				if (Object.isString(pair.value) && pair.value!='') {
					if (firstAdded) { f += ','; }
					f += pair.key + ':\'' + pair.value + '\''; firstAdded=true;
				} else if (Object.isNumber(pair.value)) {
					if (firstAdded) { f += ','; }
					f += pair.key + ':' + pair.value; firstAdded=true;
				} else {
					if (!Object.isFunction(pair.value)) {
						var pair_recursive = $H(pair.value).toArray();
						if (Object.isHash(pair_recursive)){
							if (firstAdded) { f += ','; }
							f += pair.key + ':' + Logged.convertHashToString(pair_recursive);
							firstAdded=true;
						}
					}
				}
			}
		});
		f += '}';
		return f;
	},
	
	convertRegistryTypeToNumber : function(registryType){
		if (typeof(registryType)=='undefined') {
			console.log("registryType is undefined!!");
		}
		if (registryType!='undefined' && registryType=='') {
			console.log("registryType is blank!!");
		}
		if ('C' == registryType || 'M' == registryType) {
			return 3;
		}
		if ('P' == registryType) {
			return 2;
		}
		if ('B' == registryType) {
			return 1;
		}
		return 0;
			
	},
	postEntronque : function() {
		if (window.Logged.fromNav) {
			this.checkNavigation(EntronqueData.registryType,
				EntronqueData.isPublic, EntronqueData.typeWindow, window.Logged.actionPos, 
				EntronqueData.lwTitle, EntronqueData.lwWidth, EntronqueData.lwHeight, 
				EntronqueData.lwTop, EntronqueData.lwLeft);
		}
	}, 
	hasDivHeader : function() {
		return ($("hd")!=null);
	},
	inn: function(nickname,gender, registro){
		// no usar directamente prototype, esta funcion es llamada en el callback de engine.js
		if (this.hasDivHeader()) {
			Logged.tipoRegistro = registro;
			Logged.setUser(nickname,gender);
	
			// oculta registrate
			$('alta').hide();

			// show login account links
			$('login').show();

			// hide micuenta
			$('MiCuenta').hide();
			
			// activa mi perfil
			//if( $('nb-mi-perfil') ){
			//	$('nb-mi-perfil').show();
			//}
			//activa mi perfil footer
			if ($('sitemap-miperfil')!=null) {
				$('sitemap-miperfil').show();
			}
			if ($('sitemap-last')!=null) {
				$('sitemap-last').className="last";
			}
			if ($('sitemap-last-dummy')!=null) {
				$('sitemap-last-dummy').hide();
			}
			if (typeof(myVotation)!='undefined') {
				myVotation.loggedInn();
			}
			if ($('mini_ajax_waiting_logout')) {
				$$('#mini_ajax_waiting_logout').each(Element.hide);
			}
		}
	},
	
	out: function(){
	    window.location.reload( false );
		// no usar directamente prototype, esta funcion es llamada en el callback de engine.js
		//Logged.resetUser();
		//if (this.hasDivHeader()) {
			//$('login').hide();
			//$('alta').show();
			//try {
				//header
				//if ($('nb-mi-perfil')!=null) {
				//	$('nb-mi-perfil').hide();
				//}
				//footer
				//if ($('sitemap-miperfil')!=null) {
				//	$('sitemap-miperfil').hide();
				//}
				//if ($('sitemap-last')!=null) {
				//	$('sitemap-last').className="";
				//}
				//if ($('sitemap-last-dummy')!=null) {
				//	$('sitemap-last-dummy').show();
				//}
				
			//} catch( e ){}
			
			if (typeof(myVotation)!='undefined' && $('star-rating')!=null) {
				myVotation.loggedOut();
			}
		//}
	},
	
	setUser: function(nickname,gender){
		if (this.hasDivHeader()) {
			$('user').update(nickname);
			var imgDefault = (gender == 'Hombre')? 'siluetas_33_nene.gif': 'siluetas_33_nena.gif';
			$('user-thumb').setAttribute('src',staticHostHapping + '/img/'+imgDefault);
			$('user-thumb-url').setAttribute('href','/usuario/'+nickname);
		}
	},
	
	resetUser: function(){
		if (this.hasDivHeader()) {
			$('user').update();
			$('user-thumb').setAttribute('src',staticHostHapping +'/img/pixel.gif');
		}
	},
	
	isLogged : function(){
		return myHappingUserApi.isLogged();
	},
		
	setImagen : function(url){
		if (this.hasDivHeader()) {
			$('user-thumb').setAttribute('src',url);
		}
	},
	
	setMsgNuevos : function(nick,msg){
		if (this.hasDivHeader()) {
			$('enlaceBandejaEntrada').update(msg);		
		}
	}
};


var LightHelper = {
	abrirRedLightwindow : function( tipo, url, titulo, ancho, alto, top, left ) {
		var windowType = (tipo == 'R') ? myredwindow : myLightWindow;
		if (windowType != null) {
			windowType.activateWindow( {
				href: url, title: titulo, type: 'external',
				width: ancho, height: alto, top:top, left:left, iframe_embed: true
			} );
		}
		return false;
	},
	mostrar_lightwindow_550x350 : function( url, titulo ) {			
		this.abrirRedLightwindow('L', url, titulo, 560, 420);
		return false;
	},
	mostrar_lightwindow_550x470 : function( url, titulo ) {			
		this.abrirRedLightwindow('L', url, titulo, 560, 540);
		return false;
	},
	mostrar_lightwindow_copa : function( url, titulo ) {			
		this.abrirRedLightwindow('L', url, titulo, 848, 625);
		return false;
	},
	mostrar_lightwindow_ancho_alto : function( url, titulo,ancho,alto ) {			
		this.abrirRedLightwindow('L', url, titulo, ancho, alto);
		return false;
	},
	mostrar_notificacion : function( mensaje, isOk ){
		var notif_div = $$( 'div.notificacion' )[0]; 
	
		var notifHTML = "<div id=\"barra_notificacion\" class='notificacion'></div>";
		new Insertion.Top( 'main-body-inner', notifHTML );
		notif_div = $$( 'div.notificacion' )[0];
		
		notif_div.update( "<p class='" + (isOk ? "ok" : "ups") + "'>" + mensaje + "</p>" );
		new Effect.ScrollTo('barra_notificacion');
		new Effect.Fade('barra_notificacion', { duration: 3.0, delay: 10.0});
	},
	ocultarEnlaceDenuncia: function (id_contenido) {
		Element.hide('bring_charges_' + id_contenido);
	},
	clickear_link_paginacion : function( texto_link ){
		var lis = $$( "div.paginacion ul li a" );
		if ((typeof(lis) != "undefined") && lis!=null) {
			for( var i=0; i < lis.length; i ++ ){
				if( lis[i].title == texto_link ){
					var paginar_onclick = lis[i].onclick;
					if( typeof paginar_onclick == "function" ){
						paginar_onclick();
						//lis[i].fireEvent( "onclick" );
						return;
					}
				}
			}
		}
	}	
};

var BuscadorJS = Class.create();
    	
BuscadorJS.prototype = {
	txtBusca : null,
	btnBusca : null,
	ingresoAlgo : false,
	txtInicial : "",
	
	initialize : function()
	{
		this.txtBusca = $$( "#header_search input[type=text]" );
		if( this.txtBusca.size() > 0 ){
			this.txtBusca = this.txtBusca[0];	
		} else {
			// si no encuentra el input de texto de busqueda, no hace nada.
			return;
		}
		
		this.btnBusca = $$('#header_search_form img.search_button')[0];
		Event.observe( this.btnBusca, "click", this.onClick.bind( this ) );
		                                                            
		Event.observe( this.txtBusca, "keyup", this.txtKeyUp.bind( this ) );
		
		Event.observe( this.txtBusca, "focus", this.txtFocus.bind( this ) );
		
	},
	
	txtFocus : function()
	{
		if( ! this.ingresoAlgo ){
			this.txtInicial     = this.txtBusca.value; 
			this.txtBusca.value = "";
		}
		return true;
	},
		
	txtKeyUp : function( )
	{
	 	if( this.txtBusca.value.length > 0 ){
	 		this.ingresoAlgo = true;
	 		
	 		// habilitar el boton de buscar
//	 		this.btnBusca.onclick=this.onClick();
	 	} else {
//	 		this.btnBusca.onclick=null;
	 	}
	 	return true;
	},
	
	onClick : function() {
		if (($F('struts.busca').length>0)&&($F('struts.busca').toLowerCase()!='buscar usuarios')){
			$('busca').value=$F('struts.busca');

			$('header_search_form').submit();
		} else{
			$('busca').value='';
		}
	}
};

var Menu = {
	setCurrent : function(level1,level2,level3)
	{
		if ($(level1)) {
			$(level1).addClassName('current');
		}
		if( $(level2)!= null ){
			$(level2).addClassName('current');
		}
		if( $(level3)!= null ){
			$(level3).addClassName('current');
		}
	}
};

function muestraBandeja( data ){
	var usuario = $('user').innerHTML;
	Logged.setMsgNuevos( usuario, ( data==null ? 0 : data.umnuMsjNuevo) );
}

function muestraMensajes(){
	if( Logged.isLogged() ){
		servicioPerfil.getMensajesNuevos( {
			callback : function(dataFromServer){   
				muestraBandeja(dataFromServer); 
			}
		} );
	}
}

function muestraMenu(){
	var arr;
	var titulobody = document.body.id; 
	arr = titulobody.split(";-");	
	if (arr.length>=2){
		var level1 = arr[0];
		var level2 = arr[1];
		var level3 = arr[2];

		if (level2.length==0){
			level2=null;
		}
		if ((typeof(level3)=='undefined')||(level3.length==0)){		
			level3=null;
		}
		if( level1.length>0 ){
		 	Menu.setCurrent(level1,level2,level3);
		}
	}
}

function setMiPerfil(nick, registro){
	var cuerpo_perfil = '<ul>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'">Mi perfil</a></li>';
	cuerpo_perfil += '<li><a href="href="/ckactions/editaccount">Editar mis datos</a></li>';
	cuerpo_perfil += '<li><a href="#" onclick="myHappingUserApi.editPermissions();return false;">Editar mis permisos</a></li>';
	cuerpo_perfil += '<li><a href="/mensajeria/buzonEntrada">Mis mensajes</a></li>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'/misfotos">Mis fotos</a></li>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'/misvideos">Mis v&iacute;deos</a></li>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'/misamigos">Mis amigos</a></li>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'/teveo">TeVeo</a></li>';
	cuerpo_perfil += '<li><a href="/usuario/'+ nick +'/misfrases">Mis frases happing</a></li>';
	cuerpo_perfil += '</ul>';
	
	$('enlaces-perfil').update(cuerpo_perfil);
}

function setMiPerfilfooter(nick, registro){

	var cuerpo_perfil = '<dt><a href="/usuario/'+ nick +'">mi perfil</a></dt>';

	cuerpo_perfil += '<dd class="first"><a href="/usuario/'+ nick +'/misamigos" onclick="document.location.href=\'/usuario/'+ nick +'/misamigos\';return false;" title="Mis Amigos">mis amigos</a></dd>';
	cuerpo_perfil +='<dd><a href="/usuario/'+ nick +'/teveo" onclick="document.location.href=\'/usuario/'+ nick +'/teveo\';return false;"> teVeo </a></dd>';
	
	cuerpo_perfil += '<dd id="nb-mis-fotos"><a href="/usuario/'+ nick +'/misfotos" ' + 
						'onclick="document.location.href=this.href;return false;" ' +
						'title="Mis fotos">fotos</a></dd>';
	
	cuerpo_perfil += '<dd><a href="/usuario/' + nick + '/misvideos" onclick="document.location.href=\'/usuario/'+ nick +'/misvideos\';return false;" title="Mis v&iacute;deos"> mis v&iacute;deos</a></dd>';
    cuerpo_perfil += '<dd><a href="/usuario/'+ nick +'/misfrases" onclick="document.location.href=\'/usuario/'+ nick +'/misfrases\';return false;" title="As&iacute; hago happing"> as&iacute; hago happing</a> </dd>';

	$('nb_miperfil').update(cuerpo_perfil);
}

function altaFrase(){
	Logged.checkPrincipal( false, 'L',  '/happingmap/registroFrasesSinPromo.action', 'Cuenta qué te hace feliz', 560, 570 );
}

function fraseAFavoritos(coid){
	Logged.checkPrincipal( false, 'L',  '/happingmap/asociarFrase.action?coid=' + coid, 'Para m&iacute;', 560, 520 );
}

function showMiCuenta(){
	if (!Object.isUndefined(document.getElementById("MiCuenta")) && !Object.isUndefined(document.getElementById("flechaCapaCuenta"))) {
		if(document.getElementById("MiCuenta").style.display != 'block'){
			document.getElementById("MiCuenta").style.display = 'block';
			document.getElementById("flechaCapaCuenta").className = 'mc2';
		}
	}
	return false;
}

function hideMiCuenta(){
	if (!Object.isUndefined(document.getElementById("MiCuenta")) && !Object.isUndefined(document.getElementById("flechaCapaCuenta"))) {
		if(document.getElementById("MiCuenta").style.display = 'block'){
			document.getElementById("MiCuenta").style.display = 'none';
			document.getElementById("flechaCapaCuenta").className = 'mc';
		}
	}
	return false;
}

function swapMiCuenta(){
	if (!Object.isUndefined(document.getElementById("MiCuenta")) && !Object.isUndefined(document.getElementById("flechaCapaCuenta"))) {
		if(document.getElementById("MiCuenta").style.display != 'block'){
			showMiCuenta();
		}
		else{
			hideMiCuenta();
		}
	}
	return false;
}

Event.observe( window,'load', function(){
	// mostrar el header de buscador
	if ($('header_search')) {
		new BuscadorJS();
	}
} );
