function compruebaForm()
{
	var form = arguments[0];
	if (form)
	{
		$('input',form).removeClass('error');
		
		for( var i = 1; i < arguments.length; i++ ) {
			valor = jQuery.trim($('#' + arguments[i], form).val());
			if (valor == '' || (arguments[i] == 'email' && !checkEmail(valor))	){
				alert("Por favor comprueba el campo marcado en rojo");
				$('#' + arguments[i], form).addClass('error').get(0).focus();
				return false;
			}
		}
		
		return true;
	}
	
	return false;
}



var index_boxes = {};
var paso_boxes = 3;
function caja_blog_next(id)
{
	if (index_boxes[id] == undefined){
		index_boxes[id] = paso_boxes;
	}
	
	var ntotal = $('#' + id + ' .bc li').css({display:'none'}).size();
	if (index_boxes[id] < ntotal)
	{
		for (i = index_boxes[id]+1, k=0; i <= ntotal && k < paso_boxes; i++,k++) {
			$('#' + id + ' .bc li.n-' + i).fadeIn('fast'); //removeClass('hidden');
		}
		
		if (k < paso_boxes)
			i += paso_boxes - k;
		index_boxes[id] = i-1;
		
		totalPages = Math.ceil(ntotal/paso_boxes);
		currentPage = index_boxes[id]/paso_boxes;
		$('#' + id + ' .page').html(currentPage + '/' + totalPages);
		
		if (index_boxes[id] >= ntotal)
			$('#' + id + ' .siguiente').css({display:'none'});
			
		if (index_boxes[id] > paso_boxes)
			$('#' + id + ' .anterior').removeClass('hidden').css({display:''});
	}
}


function caja_blog_prev(id)
{
	if (index_boxes[id] == undefined){
		index_boxes[id] = paso_boxes;
	}
	
	if (index_boxes[id] >= 0)
	{
		
		var ntotal = $('#' + id + ' .bc li').css({display:'none'}).size();
		i = ((index_boxes[id]-paso_boxes) >= 1)? (index_boxes[id]-paso_boxes):1;
		for ( k = 0; i > 0 && k < paso_boxes; i--,k++) {
			$('#' + id + ' .bc li.n-' + i).fadeIn('fast');
		}

		index_boxes[id] = i+paso_boxes;
		
		totalPages = Math.ceil(ntotal/paso_boxes);
		currentPage = index_boxes[id]/paso_boxes;
		$('#' + id + ' .page').html(currentPage + '/' + totalPages);
		
		if (index_boxes[id] < ntotal)
			$('#' + id + ' .siguiente').removeClass('hidden').css({display:''});
		
		if (index_boxes[id] <= paso_boxes)
			$('#' + id + ' .anterior').css({display:'none'});

	}
}

function blog_update_pages()
{
	$('#nav .box').each(function(i) {
		var ntotal = $('.bc li', this).size();
		totalPages = Math.ceil(ntotal/paso_boxes);
		$('.page',this).html('1/' + totalPages);
	});
}


function blog_reducir (id)
{
	$('#article-' + id + ' .completo').slideUp('normal', function(){ 
		$('#article-' + id + ' .resumen').slideDown('slow', function() {
			$('#article-' + id + ' .resumen, #article-{$i} .completo').toggleClass('hidden'); 
			$('#toolbar-' + id + ' .reducir, #toolbar-' + id + ' .ampliar, #toolbar-' + id + ' .anadir').toggleClass('hidden');
			// $.scrollTo('#article-' + id);
		}); 
	});
}


function blog_ampliar (id)
{
	$('#article-' + id + ' .resumen').slideUp('fast', function(){ 
		$('#article-' + id + ' .completo').slideDown('normal', function() {
			$('#article-' + id + ' .resumen, #article-{$i} .completo').toggleClass('hidden'); 
			$('#toolbar-' + id + ' .reducir, #toolbar-' + id + ' .ampliar, #toolbar-' + id + ' .anadir').toggleClass('hidden');
			// $.scrollTo('#article-' + id + ' .completo');
		}); 
	});
}

///
// Animación / fundido de las fotos de fondo
//
var fotoActual = 0;
var animacionTimeout = null;

function iniciar_animacion_fotos()
{
	var fotos = $('#bgholder img').get();
	if (fotos.length > 1)
	{
		$(fotos[fotoActual]).fadeOut(1000, function() {
			fotoActual = (fotoActual+1)%fotos.length;
			$(fotos[fotoActual]).fadeIn(1000, function() { setTimeout(iniciar_animacion_fotos, 12000); });
		});
	}
}

function animar_fotos()
{
	var fotos = $('#bgholder img').get();
	if (fotos.length > 1)
	{
		fotoIn = (fotoActual+1)%fotos.length;

		// muestro la de abajo
		$(fotos[fotoIn]).css('z-index', 9);	
		$(fotos[fotoIn]).css('display','');
		// out a la de arriba
		$(fotos[fotoActual]).fadeOut(1000, function() {
			fotoActual = fotoIn;
			$(fotos[fotoIn]).css('z-index', 10);	
			animacionTimeout = setTimeout(animar_fotos, 6000);
		}); 
	}
}

function animacion_fotos()
{
	var fotos = $('#bgholder img').get();
	if (fotos.length > 1)
	{
		for (i = 0; i < fotos.length; i++) {
			$(fotos[i]).css('z-index', 10);
			$(fotos[i]).css('position', 'absolute');
			if (i > 0)
				$(fotos[i]).css('display', 'none');
		}
		animar_fotos();
	}
}


var newsbox_current = 0;
var newsbox_total = 0;
function newsbox_next()
{
	newsbox_current = (newsbox_current+1)%newsbox_total;
	$('.articulo').css('display','none');
	$('#article-' + newsbox_current).fadeIn();
	
	return false;
}

function newsbox_prev()
{
	newsbox_current = (newsbox_current-1);
	if (newsbox_current < 0)
		newsbox_current = newsbox_total-1;
	
	$('.articulo').css('display','none');
	$('#article-' + newsbox_current).fadeIn();
	
	return false;
}

$(document).ready(function () {
	// $('#bgholder td').cycle();
	// animacionTimeout = setTimeout(iniciar_animacion_fotos, 8000);
	animacionTimeout = setTimeout(animacion_fotos, 8000);
	
	
	if ($('#page-index').get(0))
	{
		
		var frases = Array('La cocina de la casa roja es hilo transmisor de los sentimientos, las sensaciones y las emociones|Samuel Perea');
		var fraseActual  = 0;
		function iniciar_animacion_frase()
		{
			$('#frase-' + fraseActual).fadeOut(1000, function() {
				fraseActual = (fraseActual+1)%frases.length;
				$('#frase-' + fraseActual).fadeIn(1000, function() { setTimeout(iniciar_animacion_frase, 3000); });
			});
		}
		
		
	/*	$.get( '/paginas/frases-de-la-portada', null, function(datos, textStatus) { 
			
			var parte = datos.split('<div class="pageContents">');
			if (parte[1]) {
				var tmp = parte[1].split('</div>');
				html = tmp[0].replace(/<p>/g,'');
				var pes = html.split('</p>');
				frases = new Array();
				for(i = 0,j=0; i < pes.length; i++) {	
					pes[i] = jQuery.trim(pes[i]);
					if (pes[i] != '')
						frases[j++] = pes[i];
				}
			}
			
			// Crear las otras frases
			if (frases.length > 0)
			{
				for (i = 0; i < frases.length; i++)
				{
					f = $('#frase-original').clone().attr('id', 'frase-' + i).css('display','none').prependTo('#content');
					partes = frases[i].split('|');
					$('p', f).html('"' + partes[0] + '"');
					$('.frase-autor', f).html(partes[1]);
				}
			
				$('#frase-original').css('display','none');
				$('#frase-0').css('display','block');
			}
		
		
		// ANIMACIÓN DE FRASES DESACTIVADA	
		//	setTimeout(iniciar_animacion_frase, 4000);
		
		}, 'html'); */
		
		
	} else if ($('#accordion').get(0))
	{
		options = 	{
			autoHeight: false,
			animations:{duration:1000},
			change: function(event, ui) { $('#accordion .article-content').css({visibility:'visible',display:'none'}).fadeIn('slow'); },
			changestart: function(event, ui) { $('#accordion .article-content').css({visibility:'hidden'}); }
		}
			
		if ($('.blog-carta, .blog-vinos').get(0)) {
			var h1s = $('#accordion .article-content h1').get();
			for (i = 0; i < h1s.length; i++) {
				// $('#accordion h3:eq(' + i + ')').prepend('<span class="h1">' + $(h1s[i]).html() + '</span>');
				$('#accordion h3:eq(' + i + ') a').html($(h1s[i]).html());
			}
			
			$('#accordion .article-content h1').css({display:'none'});
			
			options.active = false;
			options.collapsible = true;	
		} 
		
		
		
		$("#accordion").accordion(options);
		
	} else if ($('#page-blog .box, #page-article .box').get(0))
	{
		blog_update_pages();
	} else {
		$('#fmcontact').submit (function() {
								  return compruebaForm(this, 'nombre','email', 'mensaje');
								  });
	}
});













/*
 *
 * Valida el formato de una cadena que representa una dirección de email
 *
 */
function checkEmail (emailStr) 
{
		/* Verificar si el email tiene el formato usuario@dominio. */
		var emailPat=/^(.+)@(.+)$/ 

		/* Verificar la existencia de caracteres. ( ) < > @ , ; : \ " . [ ] */
		var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" 
		
		/* Verifica los caracteres que son válidos en una dirección de email */
		var validChars="\[^\\s" + specialChars + "\]" 

		var quotedUser="(\"[^\"]*\")" 

		/* Verifica si la dirección de email está representada con una dirección IP Válida */ 
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

		/* Verificar caracteres inválidos */ 
		var atom=validChars + '+'
		var word="(" + atom + "|" + quotedUser + ")"
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
		/* domain, as opposed to ipDomainPat, shown above. */
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
	
		var matchArray=emailStr.match(emailPat)
		if (matchArray==null) 
		{
			// alert("La dirección de correo electrónico introducida parece ser incorrecta")
			return false
		}
		var user=matchArray[1]
		var domain=matchArray[2]

		// Si el usuario "uuarior" es valido 
		if (user.match(userPat)==null) 
		{
			// Si no
			// alert("El nombre de usuario de la dirección de correo electrónico no es válido.")
			return false
		}

		/* Si la dirección IP es válida */
		var IPArray=domain.match(ipDomainPat)
		if (IPArray!=null) 
		{
			for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) 
				{
					// alert("IP de destino del email inválida")
					return false
				}
			}
			return true
		}

		var domainArray=domain.match(domainPat)
		if (domainArray==null) 
		{
			// alert("El dominio parece no ser válido.")
			return false
		}

		var atomPat=new RegExp(atom,"g")
		var domArr=domain.match(atomPat)
		var len=domArr.length
		if (domArr[domArr.length-1].length<2 || 
			domArr[domArr.length-1].length>3) 
		{ 
			// alert("La dirección de email debe tener 3 letras si es .com o 2 si es de algún pais.")
			return false
		}

		if (len<2) 
		{
			// var errStr="La dirección de correo electrónico es errónea"
			// alert(errStr)
			return false
		}

		// La dirección de email ingresada es Válida
		return true;
}




/*   
=============================================================================== 
WResize is the jQuery plugin for fixing the IE window resize bug 
............................................................................... 
                                               Copyright 2007 / Andrea Ercolino 
------------------------------------------------------------------------------- 
LICENSE: http://www.opensource.org/licenses/mit-license.php 
WEBSITE: http://noteslog.com/ 
=============================================================================== 
*/ 
 
( function( $ )  
{ 
    $.fn.wresize = function( f )  
    { 
        version = '1.1'; 
        wresize = {fired: false, width: 0}; 
 
        function resizeOnce()  
        { 
            if ( $.browser.msie ) 
            { 
                if ( ! wresize.fired ) 
                { 
                    wresize.fired = true; 
                } 
                else  
                { 
                    var version = parseInt( $.browser.version, 10 ); 
                    wresize.fired = false; 
                    if ( version < 7 ) 
                    { 
                        return false; 
                    } 
                    else if ( version == 7 ) 
                    { 
                        //a vertical resize is fired once, an horizontal resize twice 
                        var width = $( window ).width(); 
                        if ( width != wresize.width ) 
                        { 
                            wresize.width = width; 
                            return false; 
                        } 
                    } 
                } 
            } 
 
            return true; 
        } 
 
        function handleWResize( e )  
        { 
            if ( resizeOnce() ) 
            { 
                return f.apply(this, [e]); 
            } 
        } 
 
        this.each( function()  
        { 
            if ( this == window ) 
            { 
                $( this ).resize( handleWResize ); 
            } 
            else 
            { 
                $( this ).resize( f ); 
            } 
        } ); 
 
        return this; 
    }; 
 
} ) ( jQuery );