var gLoadImage	= '/public/imgs/loading.gif';
var gFailImage 	= '/public/imgs/loading.gif';
var iLoader		= '<img class="loader" src="' + gLoadImage + '" />';
/*
 * FUNCTIONS to WEB
 *==========================================*/

function setVisor(){
	//VISOR
	
	if($("#visor").length != 0){
		$('#visor').lofJSidernews( { 
			interval:5000,
			duration:1500,
			auto:true		
		});	
	}
}
/*
 * SET max height of elements
 *==========================================*/
function setMaxheight(){
	$('.grid-list .block').each(function(){
		maxH = 0;
		$(this).find('img').each(function(){	
			thisH = parseInt($(this).css('height').replace('px',''));	
			if(thisH > maxH){maxH = thisH;}	
			else{}
		});
		$(this).find('img').each(function(){
			thisH = parseInt($(this).css('height').replace('px',''));	
			$(this).animate({'padding-top': '+'+ (maxH - thisH)})
		});		
		//Effect Hover
		$(this).find('.elem').hover(function(){ $(this).toggleClass('sel')});		
	});	
}

/*
 * FUNCTION: validate()
 * DESCRIPTION: validación registro
 * =========================================================
 */
function vInputsEmpty(form){
	var errors = 0;
	$(form).find('.req').each( function(i){	
		
		//Inputs
		oIn = $(this).find('input')[0];
		group = $(oIn).parent();
		if ($(oIn).val() == ""){ $(group).addClass('error'); $(group).find('.legend').html('Este campo no puede estar vacío'), errors++;}
		else{  $(group).removeClass('error');$(group).find('.legend').html('')}
		
	});
	
	//Radios
	oIn = $('#condiciones');
	group = $(oIn).parent().parent();
	if($(oIn).attr("checked") == ""){$(group).addClass('error'); $(group).find('.legend').html('Debes aceptar los términos y condiciones'); errors++;}
	else{$(group).removeClass('error'); $(group).find('.legend').html('');}
	
	return errors;
}

function vNickName(){
	target = $("#info_nickname").parent();
	$(target).attr('class', 'req loading');
	$.ajax({
		  url: "/registrate/validar/"+$('#nickname').val(),
		  context: document.body,
		  success: function(response){
			$($("#info_nickname").parent()).removeClass('loading');					
		    if(response){$(target).addClass('success'); $(target).find('.legend').html('Tu nombre de usuario está disponible')}
		    else{$(target).addClass('error'); $(target).find('.legend').html('Este nombre de usuario ya está en uso')}				    
		  }
	});
}

function vPass(){
	if($('#g_pass1 input').val().toString().length < 6){
		$('#g_pass1').addClass('error');
		$('#g_pass1 .legend').html('Tu contraseña debe tener más de 6 carácteres');
		return false;
	}
	else if($('#g_pass2 input').length > 0){ 
		if($('#g_pass1 input').val() == $('#g_pass2 input').val()){return true}
		else{
			$('#g_pass2').addClass('error');
			$('#g_pass2 .legend').html('Las contraseñas no coinciden.');
			$('#g_pass2 input').val('');
			return false;
		}
	}
	else {return true}	
}

function validate(form){
	var errors = 0;
	if(vInputsEmpty(form) == 0){
		if(vPass()){	}
		else{ errors++; }
	}
	else{ errors++; }	
	if(!errors){form.submit();}
	else{}
	return false;
}

function submitLogin(form){
	$('#fancy_login input').attr('disabled', 'disabled');
	$('#fancy_login .legend').html('procesando ...');
	$.ajax({
		  url: "/login/true",
		  type: "POST",
		  context: document.body,
		  data: "user="+$("#nickname").val()+"&pass="+$("#pass1").val(),
		  success: function(response){			
			if(response == "1"){location.reload(true) }	
			else{
				$(".fancy_login_box .error").html('el usuario o contraseña son incorrectos').show();
				$('#fancy_login input').attr('disabled', '');
				$('#fancy_login .legend').html('');
			}
		  }
	});
}

function vota(url, id, post){		
	votos = $("#"+id).html();
	id_cm = $("#"+id).attr('rel');
	if(!$.cookie("comment-"+id_cm)){
		$("#"+id).html('votando...');
		$.ajax({
			  url: url,
			  type: "POST",
			  context: document.body,
			  data: post,
			  success: function(response){
				$("#"+id).html(parseInt(votos)+1);
				$.cookie("comment-"+id_cm, '1', { path: "/" });
			  }
		});
	}
	else{
		alert("ya has votado este comentario");
	}
}

/* Denúncia */
function submitReport(){
	id = $("#comm_denuncia_id").val();
	$.ajax({
		  url: "/comentario/denunciar",
		  type: "POST",
		  context: document.body,
		  data: "id="+id+"&denuncia="+$("#comm_denuncia_texto").val(),
		  success: function(response){
			$.fancybox.close();
			$('#c_'+id).addClass('denunciado');
			$($('#c_'+id).find('.denuncia')[0]).attr('href', "#");
			$($('#c_'+id).find('.denuncia')[0]).html(' Nos has comunicado que este mensaje es inapropiado');
			$($('#c_'+id).find('.denuncia')[0]).addClass('red');
			$.cookie("denuncia-"+id, '1', { path: "/" });
		  }
	});
}

/*
 * FUNCTION: LoadImage()
 * DESCRIPTION: Precarga de imágenes
 * =========================================================
 */
function LoadImageAsyn(target, fCallBack){
    var loader = $(target);
    loader.html(iLoader); 
    LoadThisImageAsyn(loader, fCallBack);
}

/*
 * FUNCTION: LoadThisImage()
 * DESCRIPTION: Precarga de imágenes
 * =========================================================
 */
function LoadThisImageAsyn(loader, fCallBack){
    image_src = loader.attr('src');
    image_id  = loader.attr('id');
    image_alt  = loader.attr('alt');
    img = new Image();
    $(img).hide();
 
    $(img).load(function() {
        cb_js = loader.get(0).getAttribute('onload');  
        onload_cb = function(){
            eval(cb_js);
        }       
 
        $(loader.parent()).html(this);
    
        loader.remove();
        $(this).show(); 
        if (onload_cb){                
            onload_cb();
        }              
        if (fCallBack){
            cb = fCallBack;
            cb($(this));
        }        
    })
    .error(function() { $(this).attr('src', gFailImage).show().addClass('load_error').css('width', 'auto'); loader.parent().find('.view').hide() })
    .attr('src', image_src)
    .attr('id', image_id)
    .attr('alt', image_alt)
    .addClass('elem-thumb')
    .click(function() {
    	select($(this).attr('id'));
    })
    .dblclick(function() {
    	setSelect($(this).attr('id'));
    	saveSelection();
    })
    .show();
}

/*
 * FUNCTION: LoadAllImages()
 * DESCRIPTION: Precarga de imágenes
 * =========================================================
 */
function LoadAllImagesAsyn(){
    $('.loadable-image').each(function(){   
        var loader = $(this);
        loader.html(iLoader);
       LoadThisImageAsyn(loader);    	
    });
}


/**
 * Gallery
 * @param curr
 * @param next
 * @param opts
 * @param forwardFlag
 */
function onAfter(curr, next, opts, forwardFlag){
	var index = opts.currSlide;
	slider = $(next).parent().parent().parent();
	$(slider).find('.album li').removeClass('active');
	$(next).addClass('active');
	if($(slider).hasClass('multi-cover') && $(slider).hasClass('large')){
		$('#'+slider.attr('id')+' .info-slide').html((opts.slideCount - index)+"/"+opts.slideCount);
	}
	else{
		$('#'+slider.attr('id')+' .info-slide').html((index+1)+"/"+opts.slideCount);
	}
	$('.text-slides li').css('left', '-9999em').hide();
	$('.text-slides li:eq(' + (index) + ')').css('left', 'auto').show();
	$('#prev')[index == 0 ? 'removeClass' : 'addClass']('active');
    $('#next')[index == opts.slideCount - 1 ? 'removeClass' : 'addClass']('active');   	
}

function onBefore(curr, next, opts, forwardFlag){
	var slider = $(next).parent().parent().parent();
	var pag = Math.floor(($(next).index())/slider.attr('pagination'));
	$($('#'+slider.attr('id')+' .carousel-pagination a').get(pag)).click();
	//Si coinicide con el tipo, reescalamos la altura del contenido
	if(slider.hasClass('rosa')){
		var oImg =  $(next).find('img');
		if(oImg.height() == null){ 
			var oLoader = $($(next).find('.loadable-image:first'));
			var func = function(){slider.find('.album ul').height($(next).height())};
			LoadThisImageAsyn(oLoader, func)
		}
		slider.find('.album ul').height($(next).height());
	}
}

/**
 * COVER functionality
 */
function showContent(index){
	$('.text-slides li').css('left', '-9999em').hide();
	$('.text-slides li:eq(' + (index) + ')').css('left', 'auto').show();
	$('.detail li').css('left', '-9999em').hide();
	$('.detail li:eq(' + (index) + ')').css('left', 'auto').show();
}

function initCovers(){
	//Multi
	if($('.multi-cover.large').length!=0){
		$(".multi-cover.large .thumbnails").carousel( { pagination: true, dispItems: 3, animSpeed: "slow", direction:'vertical' } );
		$(".multi-cover.large .thumbnails").parent().attr('pagination', 3);
		$(".multi-cover.large .more-info").click(
			function(){
				$(this).parent().parent().find('li.active .desc').toggle();
				return false;
			}
		);
		$(".multi-cover.large").hover(
			function(){
				$(this).find(".next").animate({opacity:1});
				$(this).find(".prev").animate({opacity:1});
				$(this).find(".thumbnails li").animate({opacity:1});
			},
			function(){
				$(this).find(".next").animate({opacity:0.4});
				$(this).find(".prev").animate({opacity:0.4});
				$(this).find(".thumbnails li").animate({opacity:0.3});
			}
		)
		
	}
	//Multi
	if($('.multi-cover.normal').length!=0){
		$(".multi-cover.normal .thumbnails").carousel( { pagination: true, dispItems: 3, animSpeed: "slow" } );
		$(".multi-cover.normal .thumbnails").parent().attr('pagination', 3);
		$(".multi-cover.normal .more-info").click(
			function(){
				$(this).parent().parent().find('li.active .desc').toggle();
				return false;
			}
		);
	}
	if($('.multi-cover.rosa').length!=0){
		$(".multi-cover.rosa .thumbnails").carousel( { pagination: true, dispItems: 4, animSpeed: "slow" } );
		$(".multi-cover.rosa .thumbnails").parent().attr('pagination', 4);		
	}	
	if($('.cover-text.large').length!=0){
		showContent(0)
	    $(".cover-text.large .thumbnails").carousel( { pagination: true, dispItems: 3, animSpeed: "slow"} );	   
		$(".cover-text.large .thumbnails").parent().attr('pagination', 3);
		$(".cover-text.large").each(function(){
			sel = '#'+$(this).attr('id');			
			$($(sel + ' .cnt')[0]).height($(sel + ' .album').height());
		});
	}
	if($('.cover-text.small').length!=0){
		showContent(0)
	    $(".cover-text.small .thumbnails").carousel( { pagination: true, dispItems: 3, animSpeed: "slow"} );	   
		$(".cover-text.small .thumbnails").parent().parent().attr('pagination', 3);
		$(".cover-text.small").each(function(){
			sel = '#'+$(this).parent().attr('id');
			//$(sel + ' .cnt').height($(sel + ' .album').height());
			$($(sel + ' .cnt')[0]).height($(sel + ' .album').height());
		});
	}
}

function putInCenter(selector){
	if($(selector).length!=0){
		var parent = $(selector).parent();
		$(selector).css("position","absolute");
		//$(selector).css("top", (($(parent).height() - $(selector).outerHeight()) / 2) +"px");
		$(selector).css("left", (($(parent).width() - $(selector).outerWidth()) / 2) + 2 + "px").fadeIn('normal');
	}
}


$(document).ready(function(){
		/*
		if (jQuery.browser.safari && document.readyState != "complete"){
			//console.info('ready...');
			setTimeout( arguments.callee, 100 );
			return;
		} 
		*/	
	
		if ($.browser.msie) {
		   $(document.body).addClass('IE');
		}
		
		/*Footer*/
		$('#footer').find('li.main').hover(
			function(){
				$($(this).find('ul:first')).show();	
				$(this).addClass('hover');
			},
			function(){
				$($(this).find('ul:first')).hide();
				$(this).removeClass('hover');
			}
		);
	
		if($("#descarga").length!=0){ window.open($("#descarga").attr('href'), '_blank'); }
		
		
		//logout Button
		$('.logout').click(function(){
			$('#f_logout').submit();			
			return false;
		})
		//Escondemos imágenes del álbum
		if($('.album ul').length!=0){
			//imágenes
			start = document.location.hash.replace("#", "");
			if(start=="" || start=="comments-list") start = 0;
			$('.album ul img').hide();
			$($('.album ul img').get(start)).show();
			//vídeos
			$('.album ul .video').hide();
			$($('.album ul .video').get(start)).show();		
			
			//Visor
			//$(".thumbnails").carousel( { pagination: true, dispItems: 6, animSpeed: "slow", buttonNextHTML: null, buttonPrevHTML: null } );
		}
		
		//Trucos
		if($(".comp.trucos li").length > 0){
			$('.comp.trucos li').hover(
				function(e){				
					elem = $($(this).find('em:first'));	
					elem.addClass('show');			
					elem.stop().animate({height:50});
				},
				function(e){
					elem = $($(this).find('em:first'));				
					elem.stop().animate({height:0}, function(){$(this).removeClass('show');});
				}
			); 
		}
		
		//Home
		setVisor();
		
		//Regalos
		if($("#regalos").length > 0){
			$("#regalos").carousel( { 
		        autoSlide: true, 
		        direction: "vertical" 
			} );
		}
		
		updateFancyBox();	
			
		//GRID
		if($('.grid-list').length!=0){ setMaxheight(); }
		
		//famosos listado
		if($(".par .photo").length != 0){
			//$(".par .photo").imgr({size:"3px",color:"#8ea30a",radius:"13px"});
			//$(".impar .photo").imgr({size:"3px",color:"#f03b30",radius:"13px"});
		}		
		if($(".facebook ul li").length != 0){
			$(".facebook ul li").hover(function(){$(this).find('.name').animate({height:'+80'});}, function(){$(this).find('.name').animate({height:'20'});});
		}
		
		//SE LLEVA
		$('.se-lleva.block img').each(function(){
			var rango_superior = 20;  
			var rango_inferior = -20;  
			var aleatorio = Math.floor(Math.random()*(rango_superior-(rango_inferior-1))) + rango_inferior;  
			$(this).rotate(aleatorio);
			$(this).fadeIn('slow');
		});
				
		
		/**
		 * GALLERIES	
		 * */	
		//slideshow
		$("#slideshow .thumbnails").carousel( { pagination: true, dispItems: 6, animSpeed: "slow" } );
		$("#slideshow").attr('pagination', 6);
		$("#slideshow .album").append('<img src="/public/imgs/css/icons/zoom_in.png" class="zoom hide-accessible">');
		$("#slideshow .album li a").hover(function(){ 
			$('#slideshow .zoom').toggleClass('hide-accessible').toggleClass('active')}
			);
		$('#slideshow .zoom').click( function(){
			$('#slideshow .album li.active a.fancybox').click();
			});
		//min
	    $(".fotos.carousel .gallery").carousel( { pagination: true, dispItems: 2, animSpeed: "slow" } );
	    $(".fotos-2.carousel .gallery").carousel( { pagination: false, dispItems: 4, animSpeed: "slow" } );
	    $(".carousel .gallery").find('li:first').addClass('first');
	    //end GALLERIES
	    
	    /**
	     * TEST
	     */	    
	    $('form.form_test').submit( function(){		
	    	if($(this).find("input:checked").length < $(this).find("ul.question").length){
	    		alert('debes terminar el test');
	    		return false;
	    	}	    	
	    });
	    if($('.content.test').length > 0){
	    	$('.content.test').find('input.option').addClass('hide-accessible').each(function(){	    		
	    		if($(this).attr("checked")){$($(this).parent()).addClass('sel')}
	    	});
	    	$('.question').find('li').click(function(){
	    		$($(this).parent()).find('li').removeClass('sel');
	    		$(this).toggleClass('sel');
	    		$($(this).find('.option:first')).attr("checked","checked");
	    	})
	    	.hover(function(){$(this).toggleClass('over')});
	    	
	    }
	    
	    /**
	     * BATALLA
	     */
	    putInCenter('.batalla .vs');
	   
	    $('a.vota').click( function(){	    	
	    	value = $(this).attr('class').replace('vota n_','');
	    	oF = $($(this).parent());
	    	while( !oF.hasClass('form_batalla') ){
	    		oF = oF.parent();
	    	}
	    	oF.find('input').val(value);	    
	    	oF.find('.vota-ico').remove();
	    	//oF.find('.result').show();
	    	oF.submit();
	    	return false;
	    });
	    
		$('form.form_batalla').submit( function(){			
			$.ajax({
				type: 'POST',
				data: 'option='+$(this).find('input').val(),
				url: $(this).attr('action'),
				context: $(this).find('.inner'),
				success: function(resp){					
					res = resp.split(':::');	
					//RES 1
					oTarget1 = $(this).find('.image:first');
					oImg1 = $(this).find('.image:first .elem');					
					pos1 = oImg1.position();
					barra1 = $('<div class="res"><span class="percent hide"></span></div>').css('position', 'absolute').css('height', oImg1.height()+15).css('left', pos1.left+'px');
					barra1.append($('<div class="animation"></div>').animate({top: '-='+res[0]+'%'}, 3000, function(){
						$(this).parents('.res').find('.percent').html(res[0]+'%').show('slow');
					}));
					oTarget1.append(barra1);
					//RES 2
					oTarget2 = $(this).find('.image:last');
					oImg2 = $(this).find('.image:first .elem');					
					pos2 = oImg2.position();
					barra2 = $('<div class="res"><span class="percent hide"></span></div>').css('position', 'absolute').css('height', oImg2.height()+15).css('left', pos2.left+'px');
					barra2.append($('<div class="animation"></div>').animate({top: '-='+res[1]+'%'}, 3000, function(){
						$(this).parents('.res').find('.percent').html(res[1]+'%').show('slow');
						var battle = $(this).parents('.form_batalla');
						if(parseInt(res[1])>parseInt(res[0])){
							battle.find('.image:last').addClass('sel');
							battle.find('.image:first').fadeTo('slow', 0.5);
						}
						else{
							battle.find('.image:first').addClass('sel');
							battle.find('.image:last').fadeTo('slow', 0.5);
						}
						battle.find('.animation').hide('slow');
					}));
					oTarget2.append(barra2);
					
					/*
					$(this).find('.res:first').animate({width: res[0]+'%'}, 3000, function(){
						$(this).find('strong').removeClass('hide-accessible');			
						if(parseInt(res[0])>parseInt(res[1])){
							$($(this).parent().parent().parent()).find('.image:first').addClass('sel');
							$($(this).parent().parent().parent()).find('.image:last').fadeTo('slow', 0.5);
						}
						}).html('<strong class="hide-accessible">'+res[0]+'%</strong>');		
					$(this).find('.res:last').animate({width: res[1]+'%'}, 3000, function(){
						$(this).find('strong').removeClass('hide-accessible');				
						if(parseInt(res[1])>parseInt(res[0])){
							$($(this).parent().parent().parent()).find('.image:last').addClass('sel');
							$($(this).parent().parent().parent()).find('.image:first').fadeTo('slow', 0.5);
						}
						}).html('<strong class="hide-accessible">'+res[1]+'%</strong>');	
					oF = $($(this).parent());
			    	while( !oF.hasClass('form_batalla') ){
			    		oF = oF.parent();
			    	}
			    	*/
					$.cookie(oF.attr('id'), '1', { expires: 1, path: "/" });
					//setcookie($section."/".$poll->path,"1",time()+86400);
				}		
			});
			return false;
		})
	    
	    /**
		 * Directorio (mini)	
		 * */
		//listado
		if($(".listado").length!=0){
			
			$(".faces").carousel( { 
				pagination: false, 
				dispItems: 10, 
				animSpeed: "slow",
				buttonNextHTML: null,
	       	 	buttonPrevHTML: null 
			} );
			$('.list').easyListSplitter({ 				
				colNumber: 4, 				
				direction: 'vertical' 
			});
			$('#content').append('<div class="overlay">');
			$('#col3-4').append('<div class="overlay">');
			$('#col1-4').append('<div class="overlay">');
			$(".listado").hide();
			$(".overlay").hide();
			$("#all").click( function(){
			    $(".listado").slideToggle( function(){
					$('.listado').jScrollPane({showArrows: true});				
				});				
				$(".overlay").toggle();	
				$(".open-abc").toggleClass('close');	
				$('.list > li').show();	
			});	
			
			$('.abecedario a').click(function(){
				if($(".listado:hidden").length > 0){$("#all").click();}
				$('.list > li').hide();		
				$("#li-"+$(this).attr('href').replace("#","")).fadeIn();
				return false;
			});
		}
		
				
		/**
		 * RELATED - celebrities*/
		$(".celebrities-rel").hover(
			function(){
				$(this).find('span').css('left', 0);			
			},
			function(){
				$(this).find('span').css('left', '-999em');			
			}
		);
		$(".celebrities").hover(
				function(){
					$(this).find('span').css('left', 0);			
				},
				function(){
					$(this).find('span').css('left', '-999em');			
				}
			);
		
		/**
		 * FORM - CLUB
		 *==================*/
		$('form.club button.send').click( function(){
			form = $(this).parent().parent();
			if(validate(form)){ form.submit();}
			else{ return false }			
		});
		
		$('form.club .radio').click( function(){
			p = $(this).parent();
			p.find('.radio').addClass("review"); 
			$(this).removeClass('review');	
			p.find('input:radio.review').attr("checked", ""); 
			p.find('.radio.review').removeClass("sel"); 
			$(this).toggleClass('sel');	
			if($(this).find('input:radio').attr("checked") == ""){
				$(this).find('input:radio').attr("checked", "checked"); 
			}
			else{
				$(this).find('input:radio').attr("checked", ""); 
			}
			
		});
		
		$("#form_login").submit(function(){
			sub = null;
			$(this).find('input').each(function(){
				if($(this).val() == ""){sub = false; $(this).val('debes rellenar este campo'); $(this).addClass('error');  }
			});
			if(sub == null){
				user = $($(this).find('.user')).val();
				pass = $($(this).find('.pass')).val();
				path = $($(this).find('#path')).val();
				$.ajax({
					  url: "/login/true",
					  type: "POST",
					  context: document.body,
					  data: "pass="+pass+"&user="+user+"&path="+path,
					  success: function(response){
						if(response == 1){
							window.location = path;
						}
						else{
							$($(this).find('input.pass')).addClass('error');
							$($(this).find('input.user')).addClass('error');
						}
					  }
				});				
			}
			return false
		})
		
		/*$("#nickname").blur(function(){
			vNickName();
		});
		
		$('a.add.comment').click(function(){
			$("#add_comment").show();
		});
		
		$('.comments-all .reply').click(function(){			
			id = $(this).attr('id').replace("target_", "add_comment_")
			$("#"+id).show();
		});
		
		$('.comments-all .suma.ok').click(function(){			
			id = $(this).attr('id').replace("suma_", "")
			post = "id="+id;
			url = $(this).attr('href');
			vota(url, $(this).attr('id'), post);
			return false;
		});
		
		$('.comments-all .resta.ok').click(function(){			
			id = $(this).attr('id').replace("resta_", "")
			post = "id="+id;
			url = $(this).attr('href');
			vota(url, $(this).attr('id'), post);
			return false;
		});*/
		updateCommentEvents();
		
		setCelos();

});
//End onready


$(window).load(function() {
	
	$('.stars').show();	
	
	// FICHA FAMOSO 
	if($('.ficha .cnt').length!=0){		
		
		$('.ficha').css('height', $(".ficha img.child").attr('height'));
		$('.ficha .cnt').removeClass('hide-accessible');
				
		//fotos verticales
		if($(".ficha img.child").attr('width') < $(".ficha img.child").attr('height')){		
			$('.ficha .cnt').css('width', $(".ficha").css('width').replace("px","") - $(".ficha img.child").attr('width')-40);		
			normal_h = $(".ficha .cnt").height()+25;
			type = 'v';
			if($(".ficha img.child").height() > $('.ficha .cnt').height()){
				$('.ficha .cnt').height($(".ficha img.child").height());
				$('.ficha .open').hide();
			}
		}
		//Fotos panorámicas
		else{
			//$(".ficha img.child").css('width', '100%');
			$(".ficha img.child").animate({ width: '100%'}, 200);
			normal_h = $(".ficha .cnt").height()+$(".ficha img.child").attr('height')+20;
			type = 'h';
			$('.ficha').css('height', $(".ficha img.child").attr('height') +60);			
		}
			
		$('.ficha').attr('normal-h', normal_h);
		$('.ficha').attr('type', type);
		$('.ficha .cnt').animate({
				opacity: 1
			}, 500	
		);
		
		//Button function
		$('.open').toggle(
			function(){
				if($('.ficha').attr('normal-h') > $(".ficha img.child").height()){
					$('.ficha').animate({
						height: $('.ficha').attr('normal-h')									   
					}, 800);
					$(this).attr("class","close");	
				}
			},
			
			function(){
				h = $(".ficha img.child").height();
				if( $('.ficha').attr('type') == 'h'){ h = h + 50;}
				$('.ficha').animate({
					height: h								   
				}, 800);
				$(this).attr("class","open")					
			}		
		);		
	}			
	// end FICHA FAMOSO */
	
	/**
	 * Galleries
	 * * * * * * * * */	
	
	if($('.album ul li').length > 1){
		start = document.location.hash.replace("#", "");
		if(start=="" || start=="comments-list") start = 0;
		$('.album ul').each( function(){
			$(this).cycle({
			   fx:     'fade',
			   timeout: 0,
			   pager:  '#'+$(this).parent().parent().attr('id')+' .slides-nav', 
			   prev:   '#'+$(this).parent().parent().attr('id')+' .nav .prev',  
			   next:   '#'+$(this).parent().parent().attr('id')+' .nav .next', 		   
			   startingSlide: start,
			   before: onBefore, 
			   after: onAfter,
			   pagerAnchorBuilder: function(idx, slide) {			 
				  return '#'+$(slide).parent().parent().parent().attr('id')+' .slides-nav li:eq(' + (idx) + ') a';			  
			   }
			});			
		});
		$('.album ul img').show();
		$('.album ul .video').show();
	}
	else{
		//Controls
		$('#prev').hide();
		$('#next').hide();		
	}	
	
	/* COVERS
	 **/
	initCovers();
	LoadAllImagesAsyn();
});

function viewComments(page){ 
    
    path = $('#comment_visor_path').val();
    type = $('#comment_visor_type').val();
    $('#comments-list').css('height', $('#comments-list').height()+"px");
    $('#comments-list').html('<img class="loader" src="' + gLoadImage + '" /> Cargando...');

    $.ajax({    	
        type: 'POST',
        url: BASE_URL+'comentario/get/'+page, 
        data: 'path='+path+'&type='+type,
        success: function(resp) {         	
    		//p = $('#comments-list').parent();    		
    		//$('#comments-list').detach();    		
        	$('#comments-list').html($(resp).html());
        	$('#comments-list').css('height', 'auto');
    		updateCommentEvents();
    		updateFancyBox();
    		
        }
    });    
}

function updateCommentEvents(){
	
	$("#nickname").blur(function(){
		vNickName();
	});
	
	$('a.add.comment').click(function(){
		$("#add_comment").show();
	});
	
	$('.comments-all .reply').click(function(){			
		id = $(this).attr('id').replace("target_", "add_comment_")
		$("#"+id).show();
	});
	
	$('.comments-all .suma.ok').click(function(){			
		id = $(this).attr('id').replace("suma_", "")
		post = "id="+id;
		url = $(this).attr('href');
		vota(url, $(this).attr('id'), post);
		return false;
	});
	
	$('.comments-all .resta.ok').click(function(){			
		id = $(this).attr('id').replace("resta_", "")
		post = "id="+id;
		url = $(this).attr('href');
		vota(url, $(this).attr('id'), post);
		return false;
	});
	
	
	$('textarea#comment').keyup(function() {
		var max = 600; 
        var len = this.value.length;
        if (len >= max) {
            this.value = this.value.substring(0, max);
        }
        ($(this).parent()).find('.limit').text(max - len);
    });
	
	$('textarea#relato').keyup(function() {
		var max = 1000; 
        var len = this.value.length;
        if (len >= max) {
            this.value = this.value.substring(0, max);
        }
        ($(this).parent()).find('.limit').text(max - len);
    });
}

function updateFancyBox(){
	//fancybox
	if($("a.fancybox").length > 0){
		$("a.fancybox").fancybox({'width': '90%', 'autoDimensions': false});
	}
	if($("a.fancy_login").length > 0){
		$("a.fancy_login").fancybox({'width': '400', 'height': '280', 'autoDimensions': true});
	}
	
	$("form.login input.user").focus(function(){
		if($(this).val() == "tu correo electrónico")$(this).val("");			
	});
	$("form.login input.user").blur(function(){
		if($(this).val() == "")$(this).val("tu correo electrónico");			
	});
	
	$("form.login input.pass").focus(function(){
		if($(this).val() == "contraseña")$(this).val("");			
	});
	$("form.login input.pass").blur(function(){
		if($(this).val() == "")$(this).val("contraseña");			
	});
}

function newImage(src, c){
	c = c || "";
    img = new Image();
     
    $(img)
    .attr('src', src)
    .attr('class', c);
    
    return img;
}

function setCelos(){
	if($('.chiste').length > 0){
		$('.col3-4 .chiste').append(newImage('/public/imgs/css/chistes/celo-left.png', 't-left'));
		$('.col3-4 .chiste').append(newImage('/public/imgs/css/chistes/celo-right.png', 'b-right'));
		
		$('.col1-4 .chiste:first').append(newImage('/public/imgs/css/chistes/clip.png', 'clip t-right'));
		$($('.col1-4 .chiste').get(1)).append(newImage('/public/imgs/css/chistes/chincheta-left.png', 't-right'))
	}	
}
