// JavaScript Document
switchBannerInterval=null;
nextPreviewInterval=null;
pagePreviewCounter=0;
previewTime = 10000;
bannerTime	= 10000;
$(document).ready(function(){
	switchBannerInterval= setInterval('switchBanners();',bannerTime);
	resetPreviewInterval();
	$('a.fancyGallery').fancybox({'titlePosition': 'over'});
	$('a.fancyAjax').fancybox({'type':'ajax'});
	
	if($('div.article_content').length>0) 
		acomodatePics();
	if($('input[name=vote]').length>0){
		rated = ($('div.action_balls').hasClass('rated'))?true:false;
		$('div.action_balls').stars({
			split: 2,
			oneVoteOnly: true,
			cancelShow:false,
			callback: califica,
			disabled:rated,
			starWidth:20});
	}
	
	startGallery();
});

/* PARAM:
  obj: dom element that fire the event
  pag: page to load articles */
function paginatePreviews(obj, pag){
	if($(obj).hasClass('dotOver')) return false;
	pages = $('a.dot').length;
	$('a.dotOver').removeClass('dotOver');
	$(obj).addClass('dotOver');
	$.get('articulo/getSectionPage/page:'+pag,function(data){
		$('div.articles').html(data);
		resetPreviewInterval();
		pagePreviewCounter=0;
	});
	return false;
}

/* Get Actual page and fire event of the next one*/
function nextPage(){
	pages= $('a.dot').length;
	actual = $('a.dotOver');
	if(actual.next().length>0)
		next = actual.next();
	else 
		next = $('a.dot:first');
	next.trigger('click');
}

/* PARAM:
  obj: dom element that fire the event
  id: section_id to replace article previews */
function changeSection(obj,id){
	$('div.sectionOver').remove();
	$(obj).children().eq(0).before('<div class="sectionOver"></div>');
	$.get('articulo/getSectionPage/seccion:'+id,function(data){
		$('div.articles').html(data);
		resetPreviewInterval();
		pagePreviewCounter=0;
	});
	return false;
}

/* PARAM:
  obj: dom element that fire the event
  num: div number to select
  Obtiene el numero de preview actual segun el click y el siguiente y manda hacer el intercambio
*/
function changePreview(obj,num){
	if($(obj).find('div.miniviewOver').length>0) return false;
	parent = $(obj).parent();
	old = parent.find('div.miniviewOver');
	oldNum = old.attr('name').replace('miniview','');
	switchPreview(oldNum,num);
	clearInterval(nextPreviewInterval);
	setTimeout('resetPreviewInterval();',previewTime);
	return false;
}

/* 
  Obtiene el numero de preview actual segun el orden y el siguiente y manda hacer el intercambio
*/
function nextPreview(){
	count =$('div.articles-miniview').length;
	if(count>0){		
		pagePreviewCounter++;
		if(pagePreviewCounter==3){
			nextPage();
			return false;
		}else if(pagePreviewCounter>3){
			return false;
		}
		
		last = $('div.articles-miniview').eq(count-1).attr('name').replace('miniview','');
		actual = $('div.miniviewOver').attr('name').replace('miniview','');
		next = (actual*1)+1;
		if(next>last){
			next=$('div.articles-miniview').eq(0).attr('name').replace('miniview','');
		}
		switchPreview(actual,next);
	}
	
}

/*
	Clear preview Interval and create a new one
*/
function resetPreviewInterval(interval){
	if(isNaN(interval)) interval=previewTime;
	clearInterval(nextPreviewInterval);
	pagePreviewCounter=0;
	nextPreviewInterval = setInterval('nextPreview();',interval);
}

/* PARAM:
  obj: dom element that fire the event
  num: div number to select
  Oculta el preview anterior mostrando el nuevo
  Remueve el over al miniview anterior colocandolo al nuevo
*/
function switchPreview(oldNum,newNum){		
	$('div[name=miniview'+oldNum+']').removeClass('miniviewOver');
	$('div[name=preview'+oldNum+']').addClass('hide');
	$('div[name=miniview'+newNum+']').addClass('miniviewOver');
	$('div[name=preview'+newNum+']').removeClass('hide');
}

/* If therhe is more than one banner switch beetween them according to the interval call
*/
function switchBanners(){
	banner = $('#header div.header_banners');
	count = banner.find('div.banner').length;
	if(count>1){
		next=0;
		act=0;
		banner.find('div.banner').each(function(idx,obj){
			if(!$(obj).hasClass('hide')){
				next=(idx*1)+1;
				if(next>=count){
					next=0;
				}
				act=idx;
				return false;
			}
		});
		banner.find('div.banner').eq(act).addClass('hide');
		banner.find('div.banner').eq(next).removeClass('hide');
	}
}

/* take the images and videos at the bottom of the article and acomodate them every tree <br> tags (Or More if posible) alternating float:left and float:right
*/
function acomodatePics(){
	obj=$('div.article_content');
	
	images = obj.find('a img').parent();
	countImages = images.length;
	
	videos = obj.find('div.article_video');
	countVideos = videos.length;
		
	breaks = obj.find('br');
	countBreaks = breaks.length;
	
	defaultSeparation=3;
	if( (countBreaks/(countImages+countVideos)) >defaultSeparation) {
		defaultSeparation= countBreaks/(countImages+countVideos);
	}
	
	inserted = 0;
	breaks.each(function(idx,paragraph){
		if(idx%defaultSeparation==0){
			if(inserted<countImages){
				$(paragraph).after(images.eq(inserted));
			}else{
				if(inserted<(countImages+countVideos))
					$(paragraph).after(videos.eq(inserted-countImages));
			}
			inserted++;
		}
	});
}

/* Envia el voto actualiza el contador y muestra la confirmacion*/
function meGusta(obj,id){
	$.get('setVoto/article:'+id,function(data){
		if(data=='0'){
			message = 'Solo puedes votar una vez por artículo';
		}else{
			message = 'Gracias por tu voto';
			$('a.action_button').eq(0).html('Me gusta ('+data+')');
		}
		$('#message').html(message);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Respuesta'});
	});
}

/* Envia la calificacion, y muestra la confirmacion */
function califica(ui, type, value, event){	
	articulo = ui.options.title
	$.get('setRate/article:'+articulo+'/rate:'+value,function(data){
		if(data=='0'){
			message = 'Solo puedes calificar el articulo una vez';
		}else{
			message = 'Gracias emitir tu calificacion';
		}
		$('#message').html(message);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Respuesta'});
	});

}

/* Validate the form and send the new comment adding it to the comments list and cleaning the form*/
function newComment(obj){
	if(obj.comment.value=='' || obj.name.value==''){
		$('#message').html('Completa los campos obligatorios (Nombre y comentario)');
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Error'});
		return false;
	}
	$.post('setComment/',$(obj).serialize(),function(data){
		$('#article_comments').children().eq(0).before(data);
	});
	obj.reset();
	return false;
}

/* Valida los campos del formulario, envia el correo y muestra la confirmacion */
function sendEmail(obj){
	var message = '';
	if(obj.from.value=='' || obj.to.value=='' || obj.content.value ==''){
		message = 'Completa todos los campos ';
	}else if(!validEmail(obj.from.value)){
		message = 'Formato de correo "De" incorrecto';
	}else{
		arr = obj.to.value.split(',');
		var incorrecto = false;
		for(indice in arr){
			if(!validEmail(arr[indice]))
				incorrecto = true;
		}
		if(incorrecto)
			message = 'Formato de correo "Para" incorrecto';
	}
	if(message!=''){
		$('#message').html(message);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Error',zIndex: 3999});
		return false;
	}
	$.post('sendEmail/',$(obj).serialize(),function(data){
		obj.reset();
		$('div.email_form').html(data);
	});
	return false;
}

/* valida el formato de la direccion de correo enviada como parametro */
function validEmail(email){
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
	return emailPattern.test(email); 
}

function send_suscripcion(obj){
	message='';
	if(obj.nombre.value=='')
		message+='*Nombre<br>';
	if(obj.apellidos.value=='')
		message+='*Apellidos<br>';
	if(obj.email.value=='')
		message+='*E-mail<br>';
	if(obj.telefono.value=='')
		message+='*Teléfono<br>';
	if(obj.calle.value=='')
		message+='*Calle<br>';
	if(obj.no_ext.value=='')
		message+='*No Ext.<br>';
	if(obj.colonia.value=='')
		message+='*Colonia<br>';
	if(message.length>0){
		$('#message').html('Completa los siguientes campos:<br>'+message);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Error',zIndex: 3999});
		return false;
	}
	
	$.post('suscripcion/sendSuscription/',$(obj).serialize(),function(data){
		obj.reset();
		$('#message').html(data);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Respuesta',zIndex: 3999});
		//obj.reset();
	});
	return false;
}

function send_contacto(obj){
	message='';
	if(obj.nombre.value=='')
		message+='*Nombre<br>';
	if(obj.email.value=='')
		message+='*E-mail<br>';
	if(obj.mensaje.value=='')
		message+='*Mensaje<br>';
	if(message.length>0){
		$('#message').html('Completa los siguientes campos:<br>'+message);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Error',zIndex: 3999});
		return false;
	}
	
	$.post('contacto/sendMessage/',$(obj).serialize(),function(data){
		obj.reset();
		$('#message').html(data);
		$('#message').dialog({modal:true, draggable:false, resizable:false, title:'Respuesta',zIndex: 3999});
		//obj.reset();
	});
	return false;
}

function startGallery(){
	var galleries = $('.ad-gallery').adGallery({
	  loader_image: 'loader.gif',
	  width: 600, // Width of the image, set to false and it will read the CSS width
	  height: 400, // Height of the image, set to false and it will read the CSS height
	  display_next_and_prev: true, // Can you navigate by clicking on the left/right on the image?
	  display_back_and_forward: true, // Are you allowed to scroll the thumb list?
	  scroll_jump: 0, // If 0, it jumps the width of the container
	  slideshow: {
		enable: true,
		autostart: true,
		speed: 5000,
		start_label: 'Iniciar',
		stop_label: 'Detener',
		stop_on_scroll: true, // Should the slideshow stop if the user scrolls the thumb list?
		countdown_prefix: ' Cambio en: ', // Wrap around the countdown
		countdown_sufix: ' segs',
	  },
	  enable_keyboard_move: true, // Move to next/previous image with keyboard arrows?
	  cycle: true, // If set to false, you can't go from the last image to the first, and vice versa
	  // All callbacks has the AdGallery objects as 'this' reference
	  callbacks: {
		// Executes right after the internal init, can be used to choose which images
		// you want to preload
		init: function() {
		  // preloadAll uses recursion to preload each image right after one another
		  this.preloadAll();		
		},
		// This gets fired right after the new_image is fully visible
		afterImageVisible: function() {
		  // For example, preload the next image
		  var context = this;
		  this.loading(true);
		  this.preloadImage(this.current_index + 1,
			function() {
			  // This function gets executed after the image has been loaded
			  context.loading(false);
			}
		  );		
		},		
	  }
	});

}
