TopUp.addPresets({
	"#content a[rel=lightbox]": {
   		title: "{alt} ({current} de {total})",
     	group: "screenshots",
		layout: "quicklook",
		overlayClose: 1, 
     	readAltText: 1,
		//height: $(window).height()*0.8,
		resizable: 0,
     	shaded: 1
   }
 });

TopUp.addPresets({
	"#flickr a[rel=lightbox]": {
   		title: "{alt} ({current} de {total})",
     	group: "Flickr",
		layout: "quicklook",
     	readAltText: 1,
		resizable: 0,
		overlayClose: 1
	}
 });

$(function(){
	bookmarks();
	imgLink();
	autogrow();
	menu();
	$('form.form').autoForm();
	autoclean();
	testimonios();
	setTimeout("twitter()",3000);//3 seg

	if (!Modernizr.csstransitions) $("h1 a,#menu a").blend();
	else $("h1 a").blend();
});

//añade la clase .current comparando el enlace con la url
function menu(){
	var url = location.href.split('/').pop();
	url = '/' + url;
	$('#menu a[href=' + url + ']').addClass('current');
}

// plugin para el efecto hover
$.fn.crossfade = function(){
	return this.each(function(){
		var $$ = $(this);
		$$.not('.current').hover(function(){
			$$.stop().animate({opacity:0},300);
		},function(){
			$$.stop().animate({opacity:1},600);
		});
	});
};

//cargo bookmarks
function bookmarks(){
	$('#bookmarks h2').after('<ul></ul>');
	$.getJSON("http://feeds.delicious.com/v2/json/hunab?callback=?",
	    function(data){
	      $.each(data, function(i,item){
			$('#bookmarks ul').append('<li><a href="' + data[i].u + '">' + data[i].d + '</a></li>');
	        if ( i == 9 ) return false;
	      });
	    });

}

//efecto para los enlaces de las imágenes
function imgLink(){
	$('#flickr li a img').after('<span class="img-default"></span>');
	
	$('#flickr li a').hover(function(){
		$('span',$(this)).stop().animate({opacity:0},150, function(){
			$(this).removeClass('img-default').addClass('img-hover').animate({opacity:1},300);
		});
	},function(){
		$('span',$(this)).stop().animate({opacity:0},150, function(){
			$(this).removeClass('img-hover').addClass('img-default').animate({opacity:1},300);
		});
	});
	
	//para imagenes de trabajo
	/*if ($('.work-list').is('ul') || $('.recent-list').is('div')){
		$('.work-list li a.img img, .recent-list li a.img img').after('<span class="img-big-default"></span>');

		$('.work-list li a.img, .recent-list li a.img').hover(function(){
			$('span',$(this)).stop().animate({opacity:0},150, function(){
				$(this).removeClass('img-big-default').addClass('img-big-hover').animate({opacity:1},300);
			});
		},function(){
			$('span',$(this)).stop().animate({opacity:0},150, function(){
				$(this).removeClass('img-big-hover').addClass('img-big-default').animate({opacity:1},300);
			});
		});
	}*/
	
	if ($('.work-list').is('ul') || $('.recent-list').is('div')){
		$('.work-list li a.img img, .recent-list li a.img img').after('<span class="zoomin"></span>');
	}
}

//para cargar los ultimos posts en twitter
function twitter(){
	if ($('#twitter').is('div')){
		$("#twitter").getTwitter({
				userName: "marciobarrios",
				numTweets: 5,
				loaderText: "Cargando tweets...",
				slideIn: true,
				showHeading: false,
				headingText: "Últimos Tweets",
				showProfileLink: false
			});
	}
}

//en :focus limpiamos el texto
var autoclean = function(){
	$('input.autoclean,textarea.autoclean')
		.each(function(){
			$(this).data('defaultVal',$(this).val());
		})
		.focus(function(){
			var $$ = $(this);
			if ($$.val() == $$.data('defaultVal')) $$.val('');
		})
		.blur(function(){
			var $$ = $(this);
			if ($$.val() == '' ) $$.val( $$.data('defaultVal') );
		});
};

//amplia la altura de los textareas automaticamente
function autogrow(){
	$('form.form textarea,form#testimonios textarea').autogrow({
			maxHeight: 300,
			minHeight: 100,
			lineHeight: 20
		});
}

//formulario testimonios
var testimonios = function(){
	if (document.getElementById('testimonios')){
		
		$('#testimonials-doit a').toggle(function(){
			$(this).parent().parent().find('form#testimonios').slideDown();
			return false;
		},function(){
			$(this).parent().parent().find('form#testimonios').slideUp();
			return false;
		});
		
		$('#testimonios').submit(function(){
			var $$ = $(this);
		    var error = 0;

			$('label.error, p.message').remove();
			$('input.error,textarea.error').removeClass('error');

			$('.obligatorio',this).each(function(){
				
				if ($(this).val() == '' || $(this).val() == $(this).attr('title')){//comprobamos si está vacío o si es el texto por defecto
					error = 1;
					$(this).addClass('error').after('<label class="error">El ' + $(this).attr('name') + ' es obligatorio</label>');
				}
				else if($(this).is('.mail')){
					if(!validarEmail($(this).val())){
						error = 1;
						$(this).addClass('error').after('<label class="error">El ' + $(this).attr('name') + ' no es válido</label>');
					}
				}	
			});
			
			if (!error){
				//ponemos boton a disabled
				$('button',this).attr('disabled','disabled').find('span').html('<img src="/img/ajax-loader.gif" alt="" /> Enviando...');

				$.post("/includes/ajax.php?" + $$.serialize(),
				  function(data){
					$$.slideUp('fast',function(){
						$(this).before(data);
					});
					
					setTimeout(function(){ $('p.message').fadeOut(); }, 5000);
					
					//ponemos campos por defecto
					$$.find('input').val('Escribe aquí tu nombre').end().find('textarea').val('Escribe aquí tu testimonio');
					
					$$.find('input,textarea').val('').end().find('button').removeAttr('disabled').find('span').html('Enviar testimonio');
				  });
			}

			return false;
		});
	}
};

//plugin para validar y enviar via ajax formularios de manera sencilla
(function($) {
  $.extend($.fn, {
    autoForm : function() {
		this.submit(handleSubmit);
      	return this;
    }
  });

  function handleSubmit(e) {
	var $$ = $(this);
    var error = 0;
	
	$('label.error, p.message').remove();
	$('input.error,textarea.error').removeClass('error');
	
	$('.obligatorio',this).each(function(){
		
		if ($(this).val() == ''){//comprobamos si está vacío
			error = 1;
			$(this).addClass('error').after('<label class="error">El ' + $(this).attr('title') + ' es obligatorio</label>');
		}
		else if($(this).is('.mail')){
			if(!validarEmail($(this).val())){
				error = 1;
				$(this).addClass('error').after('<label class="error">El ' + $(this).attr('title') + ' no es válido</label>');
			}
		}	
	});
	
	//llamada ajax (por defecto a /includes/ajax.php, esto debería dejarlo opcional para utilizarlo en otros sitios) si todo es válido
	if (!error){
		//ponemos boton a disabled
		$('button',this).attr('disabled','disabled').find('span').html('<img src="/img/ajax-loader.gif" alt="" /> Enviando...');
		
		$.post("/includes/ajax.php?" + $$.serialize(),
		  function(data){
		    $('#primary-content h2').before(data);
			setTimeout(function(){ $('p.message,p.error').fadeOut(); }, 5000);
			$$.find('input,textarea').val('').end().find('button').removeAttr('disabled').find('span').html('Contactar');
		  });
	}
	
	e.preventDefault();
	return !error; //si hay error (=1) devuelvo falso (=0) y viceversa
  }
})(jQuery)

function validarEmail(valor) {
	return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(valor);
}