//var SITE_URL = 'http://localhost/room23/expoagro/sitio/';
//var SITE_URL = 'http://50.97.131.136/~expoagro/site/';

var SITE_URL = 'http://expoagro.com.ar/site/';

$(document).ready(function() {
/*funciones para todos los PHP, de header, pie, etc*/
/*START*/

	/*INGRESO PRENSA/CLIENTES POP UP*/
	$('#ing_prensa').click(
		function(){
		//$('#ingresoPrensa').css('display','block');
		$('#ingresoPrensa').fadeIn(500);
		$('#ingresoCliente').css('display','none');
	});
	$('#ing_clientes').click(
		function(){
		$('#ingresoCliente').fadeIn(500);
		$('#ingresoPrensa').css('display','none');
	});
	$('#cerrar').click(
		function(){
		$('#ingresoPrensa').css('display','none');
		$('#ingresoCliente').css('display','none');
	});
	$('#cerrarCli').click(
		function(){
		$('#ingresoPrensa').css('display','none');
		$('#ingresoCliente').css('display','none');
	});
	
	/*NEWS*/
	$('#abrirNews').click(
		function(){
		//$('#ingresoPrensa').css('display','block');
		$('#news').slideDown(500).show(function(){
			$(this).show();
		});
	});
	$('#cerrarNews').click(
		function(){
		//$('#ingresoPrensa').css('display','block');
		$('#news').slideUp(500);
	});
	
	/*HOVER BOTONERA*/
	$('#botonera ul li').hover(
		function(){
			$(this).find('#flecha').show(100);
			$(this).find('#submenu').fadeIn(300);
		},
		function(){
			$(this).find('#flecha').hide(100);
			$(this).find('#submenu').css('display','none');
		}
	);
	/*HOVER SUBMENU BOTONERA*/
	$('#submenu li').hover(
		function(){
			$(this).find('#flechaSub').show(100);
			
		},
		function(){
			$(this).find('#flechaSub').hide(100);
			
		}
	);
	/*SLIDER*/
	/*Function Slide set*/
	$('#slides').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 5000,
		pause: 5000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
	
	/*HOVER SLIDER DESCRIPCION*/
	$('#slides #slides_container_js a').hover(
	  function(){
		//alert($(this).find('#bg span').height());
		var heightBg = parseInt($(this).find('#bg span').height() + 40);
		//alert(heightBg);
		$(this).find('#bg').css('height',heightBg+'px');
		$(this).find('#bg').stop().animate({'left': '0%', 'bottom': heightBg + 'px'},200);
	  },function(){
		$(this).find('#bg').animate({'left': '0%', 'bottom': '0px'},200);
	  }
	);
	
	$('#slides .next').hover(
	function()
	{
	//	$(this).stop().animate({opacity:1},300);
	$(this).find('img').attr('src','img/flecha_slider_der_verde.png');
	},function()
	{
	//	$(this).stop().animate({opacity:0.4},300);
	$(this).find('img').attr('src','img/flecha_slider_der.png');
	});
	
	$('#slides .prev').hover(
	function()
	{
	//	$(this).stop().animate({opacity:1},300);
	$(this).find('img').attr('src','img/flecha_slider_izq_verde.png');
	},function()
	{
	//	$(this).stop().animate({opacity:0.4},300);
	$(this).find('img').attr('src','img/flecha_slider_izq.png');
	});
	
/*END*/	
});

	/*AGRANDAR ACHICAR LETRA*/
	var min=8;
	var max=18;
	function agrandarLetra() {
	 
	   var p = $('.agrandar-achicar');
	   for(i=0;i<p.length;i++) {
	 
		  if(p[i].style.fontSize) {
			 var s = parseInt(p[i].style.fontSize.replace("px",""));
		  } else {
	 
			 var s = 12;
		  }
		  if(s!=max) {
	 
			 s += 1;
		  }
		  p[i].style.fontSize = s+"px"
	 
	   }
	}
	function achicarLetra() {
	   var p = $('.agrandar-achicar');
	   for(i=0;i<p.length;i++) {
	 
		  if(p[i].style.fontSize) {
			 var s = parseInt(p[i].style.fontSize.replace("px",""));
		  } else {
	 
			 var s = 12;
		  }
		  if(s!=min) {
	 
			 s -= 1;
		  }
		  p[i].style.fontSize = s+"px"
	 
	   }
	}

/*INDEX.PHP*/
function hacerSlider(){

	
	/* COMPARTIR THUMBS*/
	$('#thumbsShare #thumbs li').show(100);
	$('#thumbsShare div').show(100);
	$('#thumbsShare div span').show(100);
	
}

/*INFORMACION.PHP*/
function informacion(){
	/*HOVER IMG INFORMACION (VER)*/
	$('a#informacionImg').hover(
	  function(){		
		$("a#informacionImg #bg").stop().animate({'left': '0%', 'bottom': '30%'},300);
	  }, 
	  function(){
		$("a#informacionImg #bg").stop().animate({'left': '0%', 'bottom': '0%'},300);
	  }
	);	
}

/* PROXIMOS.PHP*/
function eventosProximos(){
	$('#exponer ul#ulExponer li').hover(
	  function(){		  
		$(this).css({'background-color': '#f78b00'});
	  }, 
	  function(){
		$(this).css({'background-color': '#02772b'});
	  }
	);
	
	/*Fotos - Videos*/
	//HOVERS
	$('#galeria #top div').hover(
		function(){
			$(this).addClass('solapaPress');
		},
		function(){
			$(this).removeClass('solapaPress');			
		}
	);
	
	//CLICK - FOTO
	$('#solapaFoto').click(
		function(){
			$(this).addClass('solapaClick');
			$('#solapaMicro').removeClass('solapaClick');
			$('#solapaVideo').removeClass('solapaClick');
			$('#galeria #contenedor #fotos').show(200);
			$('#galeria #contenedor #micros').hide();
			$('#galeria #contenedor #videos').hide();
			$('#galeria #contenedor').animate({height:'270px'},300);
		}
	);
	
	//CLICL - VIDEO 
	$('#solapaVideo').click(
		function(){
			$(this).addClass('solapaClick');
			$('#solapaMicro').removeClass('solapaClick');
			$('#solapaFoto').removeClass('solapaClick');
			$('#galeria #contenedor #fotos').hide()
			$('#galeria #contenedor #micros').hide();
			$('#galeria #contenedor #videos').show(200);
			$('#galeria #contenedor').animate({height:'375px'},300);

		}
	);

	//CLICL - MICROS 
	$('#solapaMicro').click(
		function(){
			$(this).addClass('solapaClick');
			$('#solapaFoto').removeClass('solapaClick');
			$('#solapaVideo').removeClass('solapaClick');
			$('#galeria #contenedor #fotos').hide()
			$('#galeria #contenedor #videos').hide();
			$('#galeria #contenedor #micros').show(300);
			$('#galeria #contenedor').animate({height:'375px'},300);
		}
	);

	/* Slider Fotos*/
	$('#fSlider').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 3000,
		pause: 1000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
	/* /Fotos - Videos*/
	$('#fSliderVideos').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 0,
		pause: 1000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
	/* /Fotos - Videos*/
	$('#fSliderMicros').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 0,
		pause: 1000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
	

};

/* STAFF.PHP*/
function staff(){

};


/* REGISTRO-CONTACTO.PHP*/
function acred_contacto(){

};
/*VALIDAR FORM*/
function validarForm(){
	var nombre = $.trim( $('#nombre').val() ) || "";
	var email = $.trim( $('#email').val() ) || "";
	var tel = $.trim( $('#telefono').val() ) || "";
	var comentario = $.trim( $('#comentario').val() ) || "";
	$('#email-err').html("");
	$('#tel-err').html("");
	$('#nombre-err').html("");
	$('#comentario-err').html("");
	$('#contacto-gracias').html("");
	
	var error = false;
	if( nombre == '' ){
	$('#nombre-err').html('Completa tu nombre.');
	error = true;
	}
	
	if( comentario == '' ){
	$('#comentario-err').html('Completa tu consulta.');
	error = true;
	}

	var emailcheck1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; 
	var emailcheck2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	if( email == '' ){
		$('#email-err').html('Completa tu email.');
		error = true;
	}else if (  emailcheck1.test( email ) || !emailcheck2.test( email ) ){
		$('#email-err').html('Tu email no es correcto.');
		error = true;
	}
	if( tel == '' ){
	$('#tel-err').html('Completa tu telefono.');
	error = true;
	}
	if(error == false){
		//alert('envia');
		$('#contacto-formu').submit();
	}else{
		
	}
	};
/* EDICIONES_ANTERIORES.PHP*/
function ediciones_anteriores(){

};
/* PRENSA.PHP*/
function prensa(){

};

function cerrarForms(){
	for(i=1;i<=5;i++)$('#ver-categoria'+i).removeClass('press');
}
	
/* REGISTRO EVENTO.PHP*/
function registro_evento(){
	$('.botones a').hover(
		function(){
			$(this).animate({'top':'-5px'},{queue:false, duration:300, easing:"easeOutExpo"});
		},
		function(){
			$(this).animate({'top':'0px'},{queue:false, duration:300, easing:"easeInExpo"});
		}
	);
	$('#ver-categoria1').click(
		function(){
			cerrarForms();
			$(this).addClass('press');
			mostrarContenidoCategoria(1);
	});
	
	$('#ver-categoria2').click(
		function(){
			cerrarForms();
			$(this).addClass('press');
			mostrarContenidoCategoria(2);
	});
	
	$('#ver-categoria3').click(
		function(){
			cerrarForms();
			$(this).addClass('press');
			mostrarContenidoCategoria(3);
	});
	$('#ver-categoria4').click(
		function(){
			cerrarForms();
			$(this).addClass('press');
			mostrarContenidoCategoria(4);
	});
	$('#ver-categoria5').click(
		function(){
			cerrarForms();
			$(this).addClass('press');
			mostrarContenidoCategoria(5);
	});
	$('.botones-eventos a').hover(
		function(){
		//	$(this).animate({'background','#E18200'},100);
		},
		function(){
			//$(this).animate({'background','#AFAFAF'},100);
		}
	);
};
/* GALERIAS.PHP*/
function galerias_detalles(){
	$('#links').hover(
	  function(){
		$("#links #bg").stop().animate({'left': '0%', 'bottom': '35%'},200);
		$("#links #bg span").stop().animate({'left': '5%', 'top': '30%', 'text-decoration': 'none', 'margin': '0'},200);
	  }, 
	  function(){
		$("#links #bg").animate({'left': '0%', 'bottom': '0%'},200);
		$("#links #bg span").animate({'left': '5%', 'top': '0%', 'text-decoration': 'none', 'margin': '0'},200);
	  }
	);	

	
};
		
/* NOTICIAS_DETALLES.PHP*/
function noticias_detalles(){
	$('#imprimirNota').click(function(){
		$('.para im').jqprint({ operaSupport: true});
	});
	

	//CLICK - FOTO
	$('#solapaFoto').click(
		function(){
			$(this).addClass('solapaClick');
			$('#solapaVideo').removeClass('solapaClick');
			$('#galeriaPrensa #fotos').show();
			$('#galeriaPrensa #videos').hide();
		}
	);
	
	//CLICL - VIDEO 
	$('#solapaVideo').click(
		function(){
			$(this).addClass('solapaClick');
			$('#solapaFoto').removeClass('solapaClick');
			$('#galeriaPrensa #fotos').hide()
			$('#galeriaPrensa #videos').show();
			//alert("ASD");
		}
	);


	$('#secDetalle #fotosSlider').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 5000,
		pause: 3000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
	/* /Fotos - Videos*/
	$('#secDetalle #videosSlider').slides({
		preload: true,
		preloadImage: '../img/loading.gif',
		play: 0,
		pause: 1000,
		hoverPause: true,
		fadeSpeed: 1000,
		slideSpeed: 800
	});
		
	$('.pagination li').each(function(index){
		$(this).attr('id','index'+(index+1));
	});
	
	$('.pagination li').click(function(){
		var cual = $(this).attr('id');
		alert(cual);
		resetVideo();
		//$('#'+cual).find('iframe').attr('src',$('#'+cual).find('span').val);
		//mostrarVideoNoticia(cual);
	});
	
};
		
function resetVideo(){
		$('#galeriaPrensa #videos').find('iframe').attr('src','0');
		alert("ASD");
	}		
		
/*
* Append 16-8 by nicolaspar
*/
function writeCookie(name, value ){
	valor = $.ajax({
	  url: SITE_URL+'_ajax-cookie-save.php',
	  data: 'nombre='+name+'&valor='+value,
	  cache: false,
	  async: false
	}).responseText;
	return true;	
}
function readCookie(name){
	  valor = $.ajax({
	  url: SITE_URL+'_ajax-cookie-read.php',
	  data: 'nombre='+name,
	  cache: false,
	  async: false
	}).responseText;	
	return valor;
}

function setFormularioBox(str,append){
	if( append == 1 ){
		$('#formularioBoxCenterStr').append('<br>'+str);
	}else{
		$('#formularioBoxCenterStr').html(''+str);
		if( str != '' ) mostrarFormularioBox();
	}
	return false;
}
function mostrarFormularioBox(cual, parametros){
	$('#formularioBoxCenterStr div').hide();
	if( parametros != '' ){
		var url1 = $('#formularioBoxCenterStr #'+cual+' iframe').attr('src') || '';
		url = url1.split('?')
		$('#formularioBoxCenterStr #'+cual+' iframe').attr('src',url[0]+'?'+parametros);
	}
	$('#formularioBoxCenterStr #'+cual).show();
	$('.formularioBoxOverlay').fadeIn('fast',function(){$('#formularioBoxLayer').animate({'top':'45px'},500);});
}
function ocultarFormularioBox(){
	$('.formularioBox').animate({'top':'-2600px'},500,function(){$('.formularioBoxOverlay').fadeOut('fast');});
}

function soloNum( evento ){var key = evento.which || evento.keyCode; return (key <= 13 || key == 8 || (key >= 48 && key <= 57));}
function fechapartesvalidas(dia, mes, ano){val=dia.value+'-'+mes.value+'-'+ano.value; dr=/^[ ]*[0]?(\d{1,2})[-\/\\](\d{1,2})[-\/\\](\d{4,})[ ]*$/; mc=val.match(dr);if (mc){ var td=new Date(mc[3],parseInt(mc[2],10)-1,mc[1]);	if (td.getDate()==parseInt(mc[1],10) && td.getFullYear()==parseInt(mc[3],10) && (td.getMonth()+1)==parseInt(mc[2],10)) return true;} return false}
function fechavalida(fecha){/*dd-mm-yyyy*/temp = fecha.split('-');val=temp[0]+'-'+temp[1]+'-'+temp[2]; dr=/^[ ]*[0]?(\d{1,2})[-\/\\](\d{1,2})[-\/\\](\d{4,})[ ]*$/; mc=val.match(dr);if (mc){ var td=new Date(mc[3],(parseInt(mc[2],10)-1),mc[1]);	if (td.getDate()==parseInt(mc[1],10) && td.getFullYear()==parseInt(mc[3],10) && (td.getMonth()+1)==parseInt(mc[2],10)) return true;} return false}
function getEdad(anio,mes,dia){hoy=new Date();nacido=new Date(anio,mes-1,dia);if(nacido == 'Invalid Date')return -1;tiempo=hoy-nacido;unanio=1000*60*60*24*365;; tienes=parseInt(tiempo/unanio,10);return tienes;}



function mostrar_msj_error(obj_id){
	$('#alertar_error_'+obj_id).show(); 
}
function ocultar_msj_error(obj_id){
	$('#alertar_error_'+obj_id).hide();
}
function ocultar_msjs_error(){
	$('.label_mensajes_errores').hide(); 
}

function validarNewsletters(){
	botonAguardeNewsletters(1);
	d = document.formulario;
	error = false;
	
	var nombre = $.trim( $('#newsletter_nombre').val() ) || "";
	var email = $.trim( $('#newsletter_email').val() ) || "";
	var provincia = $.trim( $('#newsletter_provincia').val() ) || "";
	var sector = $.trim( $('#newsletter_sector').val() ) || "";
	

	if( nombre == '' ){
		$('#newsletters_mensaje_error').html('Completa tu nombre.');
		error = true;
	}

	var emailcheck1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; 
	var emailcheck2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	if( error == false && email == '' ){
		$('#newsletters_mensaje_error').html('Completa tu email.');
		error = true;
	}else if (  error == false &&  ( emailcheck1.test( email ) || !emailcheck2.test( email ) ) ){
		$('#newsletters_mensaje_error').html('Tu email no es correcto.');
		error = true;
	}


	if(  error == false && provincia == '' ){
		$('#newsletters_mensaje_error').html('Completa tu provincia.');
		error = true;
	}

	if(  error == false && sector == '' ){
		$('#newsletters_mensaje_error').html('Completa el sector al que pertenece.');
		error = true;
	}

	
	if(error == false){
		writeCookie('nombre',nombre);
		writeCookie('email',email);
		$('#newsletters_mensaje_error').html('Estamos enviando sus datos. Aguarde un instante...');
		$.ajax({
			  url: SITE_URL+"_ajax-newsletters-guardar.php",
			  type: "POST",
			  data: "nombre="+escape(nombre)+"&email="+escape(email)+"&sector="+escape(sector)+"&provincia="+escape(provincia),
			  cache: false,
				success: function(datos){
					if( datos == 'ok=1' ){
						botonAguardeNewsletters(0);
						$('#newsletters_mensaje_error').html('Gracias. Pronto tendr&aacute;s novedades nuestras.');
					}else{
						$('#newsletters_mensaje_error').html(datos); 
						botonAguardeNewsletters(0);
					}
				},
			  async: false	
		   });
	}else{
		botonAguardeNewsletters(0);
	}
}
function botonAguardeNewsletters( como ){
	if( como == 0 ){
		$('#newsletters_boton_enviar').show();
	}else{
		$('#newsletters_boton_enviar').hide();
	}
}


function validarComentarios(padre, seccion){
	$('#mensajes_error').html('');
	var error = false;
	var nombre = $.trim( $('#comentarios_nombre').val() );
	var email = $.trim( $('#comentarios_email').val() );
	var comentario = $.trim( $('#comentarios_comentario').val() );

	if( nombre == '' ){
		$('#mensajes_error').html('DEBES COMPLETAR TU NOMBRE.');
		error = true;
	}
	var emailcheck1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; 
	var emailcheck2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

	if( error == false && email == '' ){
		$('#mensajes_error').html('DEBES COMPLETAR TU EMAIL.');
		error = true;
	}else if (error == false && ( emailcheck1.test( email ) || !emailcheck2.test( email ) ) ){
		$('#mensajes_error').html('TU EMAIL NO ES CORRECTO.');
		error = true;
	}
	if( error == false && comentario == '' ){
		$('#mensajes_error').html('DEBES COMPLETAR TU COMENTARIO.');
		error = true;
	}
	
	if( error == false ){
		$('#mensajes_error').html('AGUARDE UN INSTANTE...');
		
		guardarComentario(nombre, email, comentario, padre, seccion);
	}
}
function guardarComentario(nombre, email, comentario, padre, seccion){
	//alert(SITE_URL+"_ajax-comentarios-guardar.php?nombre="+escape(nombre)+"&email="+escape(email)+"&comentario="+escape(comentario)+"&seccion="+escape(seccion)+"&padre="+escape(padre))
	writeCookie('nombre',nombre);
	writeCookie('email',email);
	resultado = $.ajax({
	  url: SITE_URL+"_ajax-comentarios-guardar.php",
	  type: "POST",
	  data: "nombre="+escape(nombre)+"&email="+escape(email)+"&comentario="+escape(comentario)+"&seccion="+escape(seccion)+"&padre="+escape(padre),
	  cache: false,
	  async: false	
   }).responseText;
	if( resultado.substring(0,4) == 'ok=1' ){
		$('#contenedor-comentarios_sin-comentarios').remove();
		$('.contenedor-formulario-comentarios').slideToggle();
		$('#contenedor-comentarios').prepend(resultado.replace('ok=1&html=',''));
	}else{
		$('#mensajes_error').html(resultado);  
	}
}
function limitarTextarea(campo, indicadorBajada, maxlimit) {
	lenghActual =  campo.value.length;
	$('#'+indicadorBajada).show();
	//Si es ie, éste cuenta los enters como dos caracteres, así que por cada uno que encuentre descuento 1 de la suma total
	if($.browser.msie){
		var patron = /\r\n/gi;	
		var encontrados = campo.value.match(patron);
		if( encontrados ){
			//lenghActual = lenghActual - (encontrados.length*2);
			lenghActual = lenghActual - encontrados.length;
		}
	}/*else{ 	//Y para FF  le saco los enters de la cuenta total:
		var patron = /\n/gi;	
		var encontrados = campo.value.match(patron);
		if( encontrados ){
			lenghActual = lenghActual - encontrados.length;
		}
	} Eliminado por ahora ya que desde php se limita tambien, habría que buscar en todos los lugares donde se corta y aplicar lo mismo que aca*/

	if ( lenghActual > maxlimit ){
		out_value = campo.value.substring(0, maxlimit);
	    campo.value = out_value;
	}else if( lenghActual == 0 ){
		$('#'+indicadorBajada).html('');
	}else{
		strTextoIndicadorComentariosTemp = strTextoIndicadorComentarios.replace('%total%',parseInt(maxlimit - lenghActual));
		$('#'+indicadorBajada).html( strTextoIndicadorComentariosTemp);
	}
}
strTextoIndicadorComentarios = 'Restan %total% caracteres';

function reportarComentario(element, codigo){
	if( confirm('Esta por reportar abuso sobre este comentario. Quieres continuar?') ){
		$(element).attr('src','img/preload_comentarios.gif');
		$.ajax({
				type: "POST",
				url: "_ajax_reportar-comentarios.php",
				data: {'codigo':codigo},
				contentType: "application/x-www-form-urlencoded",
				dataType: "html",
				success: function(datos){
					//if(datos == "succes"){
						$(element).remove();
						writeCookie('reporte_comentario_'+codigo,1);
					//}
				}
		});	
	}
}

