function carga_novedad()
{
	loadContent($(this).attr('href'), '#caja_novedades .articulos', function() {
		$('#novedades_anterior_link').click(carga_novedad);
		$('#novedades_siguiente_link').click(carga_novedad);
	}); 
	return false; 
}


$(document).ready(function () {
	
	$('.cycle').cycle();
	
	$('#novedades_anterior_link').click(carga_novedad);
	$('#novedades_siguiente_link').click(carga_novedad);
	
	h = (jQuery.browser.msie)? 650:620;
	$('a.popup').fancybox({centerOnScroll:false,hideOnContentClick:false, frameWidth:580, frameHeight:h, callbackOnStart:function() {$('#fancy_inner').addClass('pagepopup'); }, callbackOnClose:function() {$('#fancy_inner').removeClass('pagepopup'); },
 	callbackOnShow:function() { $('#fmcontacto').submit (function() {
		console.log('fmcontacto');
								  return compruebaForm(this, 'nombre','email', 'mensaje');
								  }); }
 	});
	
	if ($('#ficha').get(0))
	{
		// $('a.lightbox,a.lightbox2').lightBox();
		$('a.lightbox,a.lightbox2').fancybox();
		
		var enlace = $('#product-info a:last').attr('href');
		if (enlace && enlace.indexOf('.pdf') != -1) {
			if (current_language != 'es')
				archivo = 'icono_pdfmanual_' + current_language + '.png';
			else
				archivo = 'icono_pdfmanual.png';
			var rep = '<a href="' + enlace + '" target="_blank"><img class="pdfjs" src="' + asset_url + archivo + '" alt="Manual PDF" /></a>';
			
			$('#product-info a:last').remove();
			$('#product-info').append(rep);
			var portada = $('#product-info img:eq(1)').attr('src');
			var ancho = $('#product-info img:eq(1)').attr('width');
			if (portada && ancho>550) {
				$('#galeria img:first').attr('src', portada);
				$('#product-info img:eq(1)').remove();
				$('#product-info h2:empty, #product-info p:empty:first').remove();
			}
		}
		
	}
	
	/*if ($('#page-page').get(0))
	{
		 var imagenes = $('#page-page .pageContents table:first td:first img');
		 var html = '';
		 for ( i = 0; i < imagenes.length; i++)
		 {
		 	height = $(imagenes[i]).height();
		 	html = html + '<img src="' + $(imagenes[i]).attr('src') + '" />';
		 }
		 $('#page-page .pageContents table:first td:first').html(' ').css('padding-bottom',10);
		 // 
		 $('#page-page .pageContents table:first').before('<div id="slides">' + html + '</div>');
		 if (!jQuery.browser.msie)
			 $('#slides').cycle({timeout:5000});
		 //$('#page-page .pageContents table:first td:first div').cycle({timeout:5000});
	}
	else */ if ($('#page-blog #nav, #page-article #nav').get(0))
	{
		blog_update_pages();
	} else if ($('.blog-distribuidores').get(0)) {
		$('.item').each(function(i) {
			var imagen = $('img:first', this);
			$('img:first', this).replaceWith('<div class="imagendistrib"></div>');
			$('.imagendistrib', this).append(imagen);
		});
		
	}
	
	if ($('#messages').get(0))
		setTimeout( function(){ $('#messages').fadeOut('fast'); }, 3000);								  
});


function add_product (handle)
{
	var nombre = $('#option-' + handle).html();
	$('#option-' + handle).remove();
	$('#lista-cesta').append('<li id="li-' + handle + '">' + nombre + ' <img style="float:right" onclick="remove_product(\'' + handle + '\', \'' + nombre + '\')" title="' + nombre + '" src="' + asset_url + 'papelera.gif" /><input type="hidden" name="productos[]" value="' + nombre + '" /></li>');
}


function remove_product (handle, nombre)
{
	$('#lista-productos').append('<option id="option-' + handle + '" value="' + handle + '">' + nombre + '</option>');
	$('#li-' + handle).remove();
}




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 compruebe que ha rellenado todos los campos obligatorios");
				if ($('#' + arguments[i], form).get(0))
					$('#' + arguments[i], form).addClass('error').get(0).focus();
				return false;
			}
		}
		
		return true;
	}
	
	return false;
}



/*
 *
 * 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;
}


var index_boxes = {};
var paso_boxes = 2;
function caja_blog_next(id)
{
	if (index_boxes[id] == undefined){
		index_boxes[id] = paso_boxes;
	}
	
	var ntotal = $('#' + id + ' ol 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 + ' ol 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 = Math.ceil(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 + ' ol 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 + ' ol li.n-' + i).fadeIn('fast');
		}

		index_boxes[id] = (i+1)+paso_boxes;
		
		totalPages = Math.ceil(ntotal/paso_boxes);
		currentPage = Math.ceil(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()
{
	
	var ntotal = $('#miniarticles ol li').size();
	totalPages = Math.ceil(ntotal/paso_boxes);
	$('#miniarticles .page').html('1/' + totalPages);
}


function caja_novedades_showhide()
{
	if ($('#caja_novedades h2 a').hasClass('open')) // cerrarla
	{
		$('#caja_novedades .flechas').addClass('hidden');
		$('#caja_novedades').animate({marginTop:'352px',height:'26px'}, 400, null, function() { $('#caja_novedades h2 a').removeClass('open');  }); 
		$('#caja_novedades ul').animate({height:0}, 100, null, function(){ $('#caja_novedades ul').css('display','none'); }); 
	} else { // abrirla
		$('#caja_novedades').animate({marginTop:0,height:'378px'}, 400, null, function() { $('#caja_novedades h2 a').addClass('open'); $('#caja_novedades ul').animate({height:'269px'}, 100); $('#caja_novedades .flechas').removeClass('hidden'); }); 
		
	}
	
	return false;
}


function loadContent(url, destino, onsuccess)
{
	$.ajax({
			   type: "GET",
			   url: url + '?ajax', // '/paginas/' + id,
			   data: null,
			   dataType: 'html',
			   success: function(msg){
			   	$(destino).html(msg);
			   	if (onsuccess)
			   			onsuccess();
			   },
			   complete: function (XMLHttpRequest, textStatus) { }
			 });
}

/*
 * Plugin para explorer y los PNG transparentes.
 *
 */
jQuery.fn.supersleight = function(settings) {
	settings = jQuery.extend({
		imgs: true,
		backgrounds: true,
		shim: 'x.gif',
		apply_positioning: true
	}, settings);
	
	return this.each(function(){
		if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 7 && parseInt(jQuery.browser.version, 10) > 4) {
			jQuery(this).find('*').andSelf().each(function(i,obj) {
				var self = jQuery(obj);
				// background pngs
				if (settings.backgrounds && self.css('background-image').match(/\.png/i) !== null) {
					var bg = self.css('background-image');
					var src = bg.substring(5,bg.length-2);
					var mode = (self.css('background-repeat') == 'no-repeat' ? 'crop' : 'scale');
					var styles = {
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='" + mode + "')",
						'background-image': 'url('+settings.shim+')'
					};
					self.css(styles);
				};
				// image elements
				if (settings.imgs && self.is('img[src$=png]')){
					var styles = {
						'width': self.width() + 'px',
						'height': self.height() + 'px',
						'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + self.attr('src') + "', sizingMethod='scale')"
					};
					self.css(styles).attr('src', settings.shim);
				};
				// apply position to 'active' elements
				if (settings.apply_positioning && self.is('a, input') && (self.css('position') === '' || self.css('position') == 'static')){
					self.css('position', 'relative');
				};
			});
		};
	});
};

