//Mostrar un alert
var oAlert = alert;
function alert(txt) {
    try {
	    
		var idioma = $("#lang_cita").attr("value");
		
        if(idioma == 2) jAlert(txt, 'Information Notice');
		else jAlert(txt, 'Aviso Informativo');
		
    } catch (e) {
        oAlert(txt);
    }
}


//Agragar un comentario 
function addComment(id_contenido){
  
  var comentario = $("#comentario").attr("value");
  
  if(comentario != '') {
  
    getDataV1('addComentario','ajax.php?object=addComment&id_contenido='+id_contenido+'&texto='+comentario,'','inner');
	
  } else { alert('Debe introducir texto'); }
  
} // Fin de la función


//Enviar calificación de un comentario 
function envCal(id_contenido,calificacion){
  
  var status_calificacion = $("#st_cal").attr("value");
  
  if(status_calificacion == 0) {
  
    getDataV1('calificacion','ajax.php?object=envCal&id_contenido='+id_contenido+'&calificacion='+calificacion,'','inner');
	$("#st_cal").attr("value",1);
	
  } // Fin del if
  
} // Fin de la función


//Añadir a contenidos favoritos 
function addContentFavorito(id_contenido,id_categoria){

  getDataV1('addFavorito','ajax.php?object=addContentFavorito&id_contenido='+id_contenido+'&id_categoria='+id_categoria,'','inner');
  
} // Fin de la función


//Eliminar de contenidos
function delContent(){
  
  var ids_eliminar = $("#ids_eliminar").attr('value');
  
  getDataV1('delContent','ajax.php?object=delContent&ids_eliminar='+ids_eliminar,'','inner');
  
} // Fin de la función



//Eliminar de contenidos favoritos
function delContentFavorito(){
  
  var ids_eliminar = $("#ids_eliminar").attr('value');
  
  getDataV1('delFavorito','ajax.php?object=delContentFavorito&ids_eliminar='+ids_eliminar,'','inner');
  
} // Fin de la función


function suscripcionBoletin(email){

	//Copia el contenido original en el backup para poder usar el volver
	document.getElementById('newsletter_orig').innerHTML = document.getElementById('newsletter_fieldset').innerHTML;

	if (email != ''){
	
		if (validar_email(email)){
			getDataV1('suscripcionBoletin','ajax.php?object=suscripcionBoletin&email='+email,'newsletter_fieldset','');
		}
		else{
			document.getElementById('newsletter_fieldset_error').style.display = '';
			document.getElementById('newsletter_fieldset').style.display = 'none';
		}
		
	}
	
}

function newsletterVolver(){

	document.getElementById('newsletter_fieldset_error').style.display = 'none';
	document.getElementById('newsletter_fieldset').innerHTML = document.getElementById('newsletter_orig').innerHTML;
	document.getElementById('newsletter_fieldset').style.display = '';

}


// visualizar un alerta, en caso de no estar logueado, con reload
function addCom(e,id_prod,reload,nom_prod){
	
	if (userLogin()){
		var url_com1 = location.href;
	    var url_com2  = url_com1.split('\#');
		location.href = url_com2[0]+'#add_comentario';
	}
	else{
		
	    var inner_v = '<a href="#" onclick="alertLogin(\'ocultar\',\'\',event);return false;" class="closed">cerrar</a>';
        inner_v += '<p>Para a&ntilde;adir un comentario usted debe ser un usuario registrado</p>';
        inner_v += '<a href="#" onclick="alertLogin(\'ocultar\',\'\',event);location.reload();return false;" class="options">Ingresar</a><a href="registro/cliente/" class="options">Registrarse</a>';
      
		alertLogin('mostrar',inner_v,e,0);
	}
}


function userLogin(){
	if (document.getElementById('btn_login_out') == undefined)	return false;
	else return true;
}


var actual = 1;
// ALERT GALERIA
function alertGaleria(accion,total,mover){

if(total > 0) {

	//Ancho de la imagen de fondo del alert 
	var w_div = 516;
	var h_div = 360;

	//Valor de left para que siempre salga en el centro
	var left_v = (docwidth() - w_div) / 2;
	var top_v = (docVisibleHeight() - h_div) / 2;

	obj_fondo = document.getElementById('div_bcg');

	if(mover == 1 && actual > 1) actual--;
    if(mover == 2 && actual < total) actual++;	
		
	var img_actual = actual - 1;	
	
	var img_act = $("#imagen_"+img_actual).attr("value");

	if (accion == 'mostrar'){

		var inner_v = '';
	
		inner_v += '<div id="popupGaleria">';
		inner_v += '  <img width="497px" height="294px" src="' + img_act + '" alt="Imagen Galeria" />'; 
		inner_v += '  <div id="flechas">';

		if(actual > 1)
		inner_v += '    <a class="atrasGal" href="#" onclick="alertGaleria(\'mostrar\',' + total + ',1); return false;""><span>Anterior</span></a>'; 
		inner_v += '    <p>' + actual + ' de ' + total + '</p>';
		if(actual < total)
		inner_v += '    <a class="siguienteGal" href="#" onclick="alertGaleria(\'mostrar\',' + total + ',2); return false;"><span>Siguiente</span></a>'; 
		
		inner_v += '  </div>';
		inner_v += '  <div id="cerrarGal">'; 
		inner_v += '    <a href="#" onclick="alertGaleria(\'cerrar\',' + total + ',0); return false;"><span>Cerrar</span></a>';
        inner_v += '  </div>';
        inner_v += '  <p class="close">Cerrar</p>';
        inner_v += '</div>';		

		if (obj_fondo == undefined){
			//Fondo blanco
			fondo = document.createElement('div');

			fondo.id = 'div_bcg';
			fondo.style.background = "#ffffff";
			fondo.style.opacity =  0.50;
			fondo.style.filter = 'alpha(opacity=50)';
			fondo.style.width = docwidth()+'px';
			fondo.style.height = docheight()+'px';
			fondo.style.zIndex = 5;
			fondo.style.position = 'absolute';
			fondo.style.top = 0;
			fondo.style.left = 0;
			document.body.appendChild(fondo);
			
		}
		else{
			var alerta = document.getElementById('alert');
			if (alerta != undefined) document.body.removeChild(alerta);

			obj_fondo.style.display = '';
		} 

		var div = document.createElement('div');
		div.id = 'alert';
		div.style.zIndex = 500;
		div.style.left = left_v + 'px';
		div.innerHTML = inner_v;

		div.style.top = top_v + 'px';
		div.style.position = 'fixed';

		document.body.appendChild(div);
		
	}
	else{

		document.body.removeChild(document.getElementById('alert'));
		obj_fondo.style.display = 'none';
		
	}

  } // Fin del if de total
	
} // Fin de la función de alert de galeria


//usa jquery.dimensions
function docwidth(){
	return $(document).width();
}
function docheight(){
	return $(document).height();
}
function docVisibleHeight(){

	if (self.innerWidth)
	{
		HeightW = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		HeightW = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		HeightW = document.body.clientHeight;
	}

	return HeightW;
}

function validar_email(email_text){

	re = /^[\w-]+(?:\.[\w-]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7}$/;

	if(email_text.match(re))	return true
	else				return false;
}

function validarNum(e)
{
	tecla = (document.all) ? e.keyCode : e.which;
	if (tecla == 8) return true;
	patron = /\d/;
	te = String.fromCharCode(tecla);
	return patron.test(te);
}


//Esta en el arreglo
function in_array( what, where ){

  var a=false;

  for(var i=0;i<where.length;i++){

    if(what == where[i]){
      a=true;
      break;
    }

  }

  return a;

}

//Elementos: String que tiene nombre_campo_forma,etiqueta_campo
//campo_email: valor del campo de email a validar, vacio si la forma no tiene este campo
function validar_forma(elementos,campo_email,idioma){
	
	var ElementosForma = elementos.split(",");
	
	if(idioma == 2)
	var Error = "The following fields are required:\n\n";
	else var Error = "Los siguientes campos son requeridos:\n\n";
	
	var Error_i = 0;

	for (i=0;i<ElementosForma.length;i++){
		if (document.getElementById(ElementosForma[i]).type == "text" || document.getElementById(ElementosForma[i]).type == "password" || document.getElementById(ElementosForma[i]).type == "textarea" || document.getElementById(ElementosForma[i]).type == "select-multiple" || document.getElementById(ElementosForma[i]).type == "select-one" || document.getElementById(ElementosForma[i]).type == "file" || document.getElementById(ElementosForma[i]).type == "hidden"){
			if (document.getElementById(ElementosForma[i]).value == "" || document.getElementById(ElementosForma[i]).value == ElementosForma[i+1]){
				Error += "- " + ElementosForma[i+1] + "\n";
				Error_i = 1;
			}
		}
		else if (document.getElementById(ElementosForma[i]).type == "radio" || document.getElementById(ElementosForma[i]).type == "checkbox"){
			if (document.getElementById(ElementosForma[i]).checked == false){
				Error += "- " + ElementosForma[i+1] + "\n";
				Error_i = 1;
			}
		}

		i++;
	}

	if (Error_i == 1){
		alert(Error);
		return false;
	}
	else{
		if (campo_email != ""){
			if(!validar_email(campo_email)){
				alert('Formato de Email incorrecto');
				return false;
			}	 
		}
		else
			return true;
	}
}

function getClickX(e){

	var IE = document.all ? true:false;
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = e.clientX;

		if( document.documentElement && ( document.documentElement.scrollTop || document.documentElement.scrollLeft )){
			tempX += document.documentElement.scrollLeft;
		} 
		else if( document.body && ( document.body.scrollTop || document.body.scrollLeft )){
			tempX += document.body.scrollLeft;
		}
	} 
	else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX
	}

	// catch possible negative values in NS4
	if (tempX < 0){tempX = 0}

	return tempX;
}

function getClickY(e){

	var IE = document.all ? true:false;
	if (IE) { // grab the x-y pos.s if browser is IE
		tempY = e.clientY;

		if( document.documentElement && ( document.documentElement.scrollTop || document.documentElement.scrollLeft )){
			tempY += document.documentElement.scrollTop;
		} 
		else if( document.body && ( document.body.scrollTop || document.body.scrollLeft )){
			tempY += document.body.scrollTop;
		}
	} 
	else {  // grab the x-y pos.s if browser is NS
			tempY = e.pageY
	}

	// catch possible negative values in NS4
	if (tempY < 0){tempY = 0}

	return tempY;
}

function showDivEmail(div_id,accion){
    
	//Eliminar Clase Ocultar
	$("#div_email").removeClass("ocultar");
	
	var div = document.getElementById("div_" + div_id);
	var obj_fondo = document.getElementById('div_bcg');

	var w_div = 370;
	var h_div = 510;
	
	//Valor de left para que siempre salga en el centro
	var left = (docwidth() - w_div) / 2;
	var top = (docVisibleHeight() - h_div) / 2;

	if (accion == 'mostrar'){
	
		if ( obj_fondo == undefined){

			fondo = document.createElement('div');
			fondo.id = 'div_bcg';
			fondo.style.background = "#6B6B6B";
			fondo.style.opacity = 0.50;
			fondo.style.filter = 'alpha(opacity=50)';
			fondo.style.width = docwidth()+'px';
			fondo.style.height = docheight()+'px';
			fondo.style.zIndex = 5;
			fondo.style.position = 'absolute';
			fondo.style.top = 0;
			fondo.style.left = 0;
			document.body.appendChild(fondo);
		}
		else{
			obj_fondo.style.display = '';
		} 
	
		div.style.left = left + 'px';
		div.style.display = '';
		div.style.zIndex = 500;
		div.style.position = 'fixed';
		div.style.top = top + 'px';

	} 
	else if(accion == 'enviar') {
	    emailContenido(); 
	}
	else{
		div.style.display = 'none';
		obj_fondo.style.display = 'none';
	}
	
}


//Envia un contenido por email
function emailContenido(){
	
	var you_n = document.getElementById('you_name').value;
	var you_e = document.getElementById('you_email').value;

	var rec_n = document.getElementById('rec_name').value;
	var rec_e = document.getElementById('rec_email').value;
	
	var t_contenido = document.getElementById('titulo_contenido').innerHTML;
	var url = window.location.href;
	var idioma =  document.getElementById('lang_cita').value;
	
	if(idioma == 1)
	estado = validar_forma('you_name,Nombre del Remitente,you_email,Email del Remitente,rec_name,Nombre del Destinatario,rec_email,Email del Destinatario',rec_e,idioma);
	else
	estado = validar_forma('you_name,Sender Name,you_email,Sender E-mail,rec_name,Recipients Name,rec_email,Recipients E-mail',rec_e,idioma);
    
	if (estado != false){	
	  str = 'you_name='+you_n+'&you_email='+you_e+'&rec_name='+rec_n+'&rec_email='+rec_e+'&t_contenido='+t_contenido+'&url='+url;
	  getDataV1('','ajax.php?object=emailContenido&'+str,'rta_div_email','inner');	
	} 
	
}

//Version Print Contenido
function printContenido(url,id){

  window.open(url+'index2.php?print=1&mod=showContent&id='+id,'','width=600,height=600,top=100,left=100,scrollbars=1');
	
}

//Version Print Producto
function printProducto(url,id){

  window.open(url+'index2.php?print=2&mod=showProduct&id='+id,'','width=900,height=600,top=100,left=100,scrollbars=1');

}

//Version Print Producto
function printProducto(){

	var Url = location.href;
	Url = Url.replace(/.*\?(.*?)/,"$1");
	Variables = Url.split ("&");
	for (i = 0; i < Variables.length; i++) {
		Separ = Variables[i].split("=");
		eval ('var '+Separ[0]+'="'+Separ[1]+'"');
	}

	window.open('index2.php?print=2&mod=showProduct&id_c='+id_c,'','width=900,height=600,top=100,left=100,scrollbars=1');
}

//Version PDF Contenido
function pdfContenido(){

	var Url = location.href;
	Url = Url.replace(/.*\?(.*?)/,"$1");
	Variables = Url.split ("&");
	for (i = 0; i < Variables.length; i++) {
		Separ = Variables[i].split("=");
		eval ('var '+Separ[0]+'="'+Separ[1]+'"');
	}

	location.href='index2.php?pdf=1&mod=showContent&id_c='+id_c,'','width=600,height=600,top=100,left=100,scrollbars=1';
}

//Version PDF Producto
function pdfProducto(){

	var Url = location.href;
	Url = Url.replace(/.*\?(.*?)/,"$1");
	Variables = Url.split ("&");
	for (i = 0; i < Variables.length; i++) {
		Separ = Variables[i].split("=");
		eval ('var '+Separ[0]+'="'+Separ[1]+'"');
	}

	location.href='index2.php?pdf=2&mod=showProducto&id_c='+id_c,'','width=600,height=600,top=100,left=100,scrollbars=1';
}

function showDivEnlarge (div_id,accion){


	var div = document.getElementById("div_" + div_id);
	var obj_fondo = document.getElementById('div_bcg');

	//var w_div = parseInt(div.style.width);
	var w_div = 521;
	var h_div = 400;
	//Valor de left para que siempre salga en el centro
	var left = (docwidth() - w_div) / 2;
	var top = (docVisibleHeight() - h_div) / 2;

	if (accion == 'mostrar'){
		div.style.left = left + 'px';
		div.style.display = '';
		div.className='fixed';
		if (getBrowser() != 'ie'){
			div.style.top = top + 'px';
			div.style.position = 'fixed';
		}

		if ( obj_fondo == undefined){
			//Fondo negro
			fondo = document.createElement('div');

			fondo.id = 'div_bcg';
			fondo.style.background = "#6B6B6B";
			fondo.style.opacity = 0.50;
			fondo.style.filter = 'alpha(opacity=50)';
			fondo.style.width = docwidth()+'px';
			fondo.style.height = docheight()+'px';
			fondo.style.zIndex = 5;
			fondo.style.position = 'absolute';
			fondo.style.top = 0;
			fondo.style.left = 0;
			document.body.appendChild(fondo);
		}
		else{

			obj_fondo.style.display = '';
		} 
	}
	else{
		div.style.display = 'none';
		obj_fondo.style.display = 'none';
	}
}

//Coloca el url a donde debe ir al cambiar la fecha del archivo de noticias, esto se hace para evitar multiples mm_aa en el url
function setUrlComboArchive(valor){

	url = location.href;

	url_tmp = url.split('?');
	args = url_tmp[1];
	url_t = args.split('&');

	args = '';
	for (var i=0;i<url_t.length;i++){

		par = url_t[i].split("=");

		if (par[0] == 'mm_aa')	par[1] = valor;

		if (par[0].indexOf('num_pag') == -1){
			if (args == '')	args = par[0] + '=' + par[1];
			else			args += "&" + par[0] + '=' + par[1];
		} 	
	}

	//Check si esta el parametro mm_aa
	if (url.indexOf('mm_aa') == -1){
		args += '&mm_aa=' + valor;
	}

	return url_tmp[0] + '?' + args;
}

//Retorna el valor de un parametro dado el url y el nombre del parametro
function getUrlParameter(url,parameter){
	url_t = url.split("&");

	for (var i=0;i<url_t.length;i++){

		par = url_t[i].split("=");

		if (par[0] == parameter)	return par[1];	
	}
}

//Login in
function signIn(){

	var u = document.getElementById('usuario').value;
	var p = document.getElementById('pass').value;

	if (u != '' && p != ''){
		getDataV1('login','ajax.php?object=signIn&u='+u+'&p='+p,'','inner');
	}
	
}

//Login out
function signOut(){	
	getDataV1('logout','ajax.php?object=signOut','','inner');	
}

//Recuperar Contraseña
function recuperarContrasena(){	
    
	var email = document.getElementById('recuperar_contrasena').value;
	
	if(!validar_email(email)) {
	  $("#div_email_error").show();
	} else {
	  $("#div_email_error").hide();
	  getDataV1('recuperar','ajax.php?object=recuperarContrasena&email='+email,'','inner');	
	}
	
}

//Reportar Contenido Inapropiado o Incorrecto
function reportarContenido(id_content,url_content){	
	getDataV1('reportar','ajax.php?object=reportarContenido&id_content='+id_content+'&url_content='+url_content,'','inner');	
}

function focusLogin(obj){
	if(obj.value == 'Usuario')	obj.value = '';
}

function blurLogin(obj){
	if(obj.value == '') obj.value = 'Usuario';
}

function focusPassword(obj){

	var spane = document.getElementById("input_pass");
	
	if(obj.value == 'Contrase\xf1a'){
		spane.innerHTML = '<input name="pass" type="password" id="pass" value="" onfocus="focusPassword(this)" onblur="blurPassword(this)" class="input1" />';
		
	}

	setTimeout("document.getElementById('pass').focus()",10);
}

function blurPassword(obj){

	var spane = document.getElementById("input_pass");
	
	if(obj.value == ''){
		spane.innerHTML = '<input name="pass" type="text" id="pass" value="Contrase\xf1a" onfocus="focusPassword(this)" onblur="blurPassword(this)" class="input1" />';
	}
}


//Login volver
function loginVolver(){
	getDataV1('','ajax.php?object=signOut','top_login','inner');
}


function changeInputType(oldObject, oType) {

	var newObject = document.createElement('input');
	newObject.type = oType;
	if(oldObject.size) newObject.size = oldObject.size;
	if(oldObject.value) newObject.value = oldObject.value;
	if(oldObject.name) newObject.name = oldObject.name;
	if(oldObject.id) newObject.id = oldObject.id;
	if(oldObject.className) newObject.className = oldObject.className;
	oldObject.parentNode.replaceChild(newObject,oldObject);

	return newObject;
	
}

function getBrowser() {
	var sBrowser = navigator.userAgent;

	if (sBrowser.toLowerCase().indexOf('msie') > 0)
		return 'ie';
	else
		return;
}

//Lista equivalente de tildes
function latinChars(texto){

	var latin = Array("a","e","i","o","u","n");
	var web = Array("\xe1","\xe9","\xed","\xf3","\xfa","\xf1");


	for(var i=0;i<latin.length;i++){
		texto.replace(/latin[i]/,web[i]);
	}

	return texto;
}

function filtroContenidoHome(){

	var obj = document.getElementById('filtro_home');
	var id = obj.options[obj.selectedIndex].value;
	location.href = '?cf='+id;
	
}

function filtroProducto(url){

    var pagina="http://"+location.host+'/'
	var url_tmp  = url.split('?cf');
	var url_tmp2 = url_tmp[0].split('?pa');
	var obj = document.getElementById('filtro_p');
	var id = obj.options[obj.selectedIndex].value;
	var cont = url_tmp2[0].length;
	var cad_temp = url_tmp2[0].substr(cont-1, 1);
	if(cad_temp == '/')
	location.href = pagina+url_tmp2[0]+ '?cf='+id;
	else
	location.href = pagina+url_tmp2[0]+ '/?cf='+id;
	
	var obj = document.getElementById('filtro_home');
	var id = obj.options[obj.selectedIndex].value;
	location.href = url + '?crt='+crt+'&cf='+id;
	
}

