﻿//Al Cargar La Pagina...
$(document).ready(function () {
  $(".bottominfo, .bottominfo2").hover(function(){$(this).addClass("bclegal")},function(){$(this).removeClass("bclegal")});
  $(".lnkdrop").hover(function(){$(this).addClass("lnkdrop2")},function(){$(this).removeClass("lnkdrop2")});
  $("input.cl1").click(function(){$(this).css({'background-color':'#FFFFFF'})});
  
  $("#busca1").keypress(function (e) {
      if (e.which == 13)
      {
      	buscAdv();
      } 
    });
  
  $(".celdaAC002").hover(function(){$(this).css({'background-color':'#EEEEEE'})}, function(){$(this).css({'background-color':'#FFFFFF'})});
  $(".dropbase").hover(function(){$(this).css({'background-image':'url(images/botondropsele.gif)'})}, function(){$(this).css({'background-image':'url(images/botondrop.gif)'})});
  /*$("#busca1").autocomplete("buscador.php",{cacheLength:1, matchSubset:false, matchContains:false, onFindValue:buscAdv});*/
  
  $("#drp1").keypress(
					function(e){
						if(e.which == 13)
						{
							selectOpt('drop1', 'drp1');
						}
						});
  $("#drp2").keypress(
					function(e){
						if(e.which == 13)
						{
							selectOpt('drop2', 'drp2');
						}
						});
  $("#dselect").keypress(
					function(e){
						if(e.which == 13)
						{
							swPPday($(this).val(), $("#ddret").val());
						}
						});
  $("#ordby").keypress(
					function(e){
						if(e.which == 13)
						{
							ordBy();
						}
						});
});
//Fin
//Funciones Viejas!
function cambiaTexto(newTexto, elemento) 
{ 
var objetoSPAN = document.getElementById(elemento); 
objetoSPAN.innerHTML = newTexto; 
return true; 
} 

function abreDetalle(ventana)
{
var randomNumber = Math.random();
var number = Math.round(randomNumber);
//window.open(ventana,"Digitalife", "height=800,width=900,status=yes,toolbar=no,menubar=yes,location=no,scrollbars=1");
window.open(ventana,number, "height=800,width=900,status=yes,toolbar=no,menubar=yes,location=no,scrollbars=1");
}

function emailCheck(emailStr)
{
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
		alert("La dirección de correo electrónico contiene un error (checar @ y .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
		alert("El nombre de usuario del e-mail, contiene caracteres inválidos.");
		return false;
   		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("El nombre de dominio del e-mail contiene caracteres inválidos.");
			return false;
   		}
	}

	if (user.match(userPat)==null) {
		alert("El nombre de usuario del e-mail parece no ser válido");
		return false;
	}

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("La direcci&oacute;n IP del e-mail es inválida");
				return false;
   			}
		}
		return true;
	}

	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("El nombre de dominio parece ser inválido");
			return false;
   		}
	}

	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
			alert("El nombre de dominio debe terminar en dos letras de región o dominio conocido ");
			return false;
	}

	if (len<2) {
		alert("La dirección es desconocida");
		return false;
	}

	return true;
}
//FIN
//Utilidades
function isset(variable_name) 
{
    try {
         if (typeof(eval(variable_name)) != 'undefined')
         if (eval(variable_name) != null)
         return true;
     } catch(e) { }
    return false;
}
//Fin Utilidades
//Cosa de las Noticias
function sbnoticias(seccion, tsecciones, barra)
{
	var divnoticia=$("#"+seccion).css("display");
	if(divnoticia == "none")
	{
		var conta=1;
		var hasta=tsecciones+1;
		while(conta != hasta)
		{
			var otrosdiv=$("#"+barra+"-"+conta).css("display");
			if(otrosdiv == "block")
			{
				$("#"+barra+"-"+conta).slideUp("normal");
				$("#"+barra+"-"+conta+"t").removeClass("lnkbarras2");
				$("#"+barra+"-"+conta).removeClass("barrfondo");
			}
			conta++;
		}
		$("#"+seccion).slideDown("normal");
		/*$("#"+seccion+"t").addClass("lnkbarras2");*/
		$("#"+seccion).addClass("barrfondo");
	}
	return true;
}
//Fin

/*function disableselect(e){
return false
}
function reEnable(){
return true
}

// Evita seleccion de texto
document.onmousedown = new Function("return false");
document.onselectstart = new Function ("return false");
if (window.sidebar) {
   document.onmousedown = new Function("return false");
   document.onclick = new Function("return true");
}*/

function disableselect(e){
return false
}
function reEnable(){
return true
}

//si es internet explorer 4 o superior
document.onselectstart=new Function ("return false")
//si es netscape 6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
document.oncontextmenu = function(){return false}

function limpiar(campo)
{
	if(campo.value=='Escriba lo que quiere buscar')
	{
		campo.value='';
	}
	return true;
}

function localizar(valor)
{
	var valll=jQuery.trim(valor);
	var abuscar="busca1="+valll;
	var regresa=$.ajax({
	   type: "POST",
	   url: "buscador.php",
	   data: abuscar,
	   async: false,
	   cache: false,
	   success: function(html){
   			if($("#buscador").css("display") == 'none')
			{
				$(".ldrop1").slideUp("fast");
				$("#buscador").slideDown("fast")
			}
  		}

	 }).responseText;
	if(regresa == '')
	{
		$("#buscador").slideUp("fast");
	}
	else
	{
		document.getElementById('resultados').innerHTML=regresa;
		$('#resultados div').keynav('linkrapido_2', 'linkrapido');
	}
	return true;
}

function hideDivs()
{
	$('.drpsopts').slideUp("fast");
	$('#drop1, #drop2').css({'background-image':'url(images/botondrop.gif)'});
	$('#buscador').slideUp("fast");
	return true;
}

function showDropBox(drop, drvis)
{
	hideDivs();
	if($("#"+drop).css("display") == 'none')
	{
		$('#'+drvis).css({'background-image':'url(images/botondropsele.gif)'});
		$("#"+drop).slideDown("fast");
	}
	return true;
}

function sDrOpt(dv, donde, texto, valor)
{
	var dvs=document.getElementById(dv);
	var adonde=document.getElementById(donde);
	hideDivs();
	dvs.innerHTML=texto;
	adonde.value=valor;
	return true;
}

function prForm()
{
	var forma=document.getElementById('formaprods');
	if ($("#drp1").val() == 0 && $("#drp2").val() == 0)
	{
		alert("Debe seleccionar por lo menos una Opcion");
		return false;
	}
	else
	{
		if($("#drp2").val() == 0)
		{
			$("#actclick").val("2");
		}
		else if($("#drp1").val() == 0)
		{
			$("#actclick").val("3");
		}
		else
		{
			$("#actclick").val("9");
		}
		forma.submit();
		return true;
	}
}

function suscBoletin()
{
	var forma=document.getElementById('multiforma');
	var correo=$("#bolsusc").val();
	var corrlimpio=jQuery.trim(correo);
	if(corrlimpio == '')
	{
		alert('Por Favor, escribe una Dirección de Correo');
		return false;
	}
	else if(emailCheck(corrlimpio))
	{
		document.getElementById('accion').value='1';
		forma.submit();
	}
	else
	{
		return false;
	}
}

function buscAdv()
{
	var forma=document.getElementById('multiforma');
	var busqueda=$("#busca1").val();
	var blimpio=jQuery.trim(busqueda);
	if(blimpio == '' || blimpio == 'Escriba lo que quiere buscar')
	{
		alert('Por Favor escribe algo en Busqueda');
		return false;
	}
	else
	{
		document.getElementById('accion').value='2';
		forma.submit();
		return true;
	}
}

function abrebarras()
{
	var conta=0;
	while(conta != 4)
	{
		var valor=$("#rb"+conta).val();
		$("#"+conta+"enc").animate({width: ""+valor+"%"}, 1500 );
		conta++;
	}
}

function encuesta(tenc)
{
	var encuesta=$('#idencuesta').val();
	var conta=0;
	var elemento;
	var opcion=0;
	while(conta < tenc)
	{
		//alert(conta);
		elemento=document.getElementById('radio'+conta);
		if(elemento.checked == true)
		{
			opcion=$('#radio'+conta).val();
			conta=tenc;
		}
		conta++;
	}
	
	if(opcion == 0)
	{
		alert("Debe Seleccionar una Opción para poder Votar");
	}
	else
	{
		var respuesta=$.ajax({
  		type: "POST",
		url: "vota.php",
		data: "respuesta="+opcion+"&nvote=1&encuesta="+$('#idencuesta').val(),
		async: false
		});
		$("#encmisc").fadeOut("fast");
		document.getElementById('encmisc').innerHTML=respuesta.responseText;
		$("#encmisc").fadeIn("fast");
		abrebarras();
	}
}

function changeimg(ident, idactivado)
{
	var imgact=$("#imgactual").val();
	//alert(imgact);
	//alert(imgact);
	//alert(ident+' '+idactivado);
	$("#img"+imgact).hide('slide',{},"normal", function(){$("#img"+idactivado).show('slide',{},"normal");});
	//$("#casilla"+ident).val(imgact);
	$("#imgactual").val(idactivado);
	
	$("#b"+ident+"-"+idactivado).fadeOut("fast", function(){$("#b"+ident+"-"+imgact).fadeIn("fast")});
	//alert(imgact);
	/*if(ident == 1)
	{
		document.getElementById('brgal'+ident).innerHTML='<img src="img/galeriabarras/barra'+imgact+'_'+ident+'.gif" width="24" height="320" id="b'+ident+'" onmouseover="this.src=imgover'+imgact+'['+ident+'].src" onmouseout="this.src=imgnrm'+imgact+'['+ident+'].src"/>';
	}
	else if(ident == 2)
	{
		document.getElementById('brgal'+ident).innerHTML='<img src="img/galeriabarras/barra'+imgact+'_'+ident+'.gif" width="24" height="336" id="b'+ident+'" onmouseover="this.src=imgover'+imgact+'['+ident+'].src" onmouseout="this.src=imgnrm'+imgact+'['+ident+'].src"/>';
	}
	else if(ident == 3)
	{
		document.getElementById('brgal'+ident).innerHTML='<img src="img/galeriabarras/barra'+imgact+'_'+ident+'.gif" width="24" height="352" id="b'+ident+'" onmouseover="this.src=imgover'+imgact+'['+ident+'].src" onmouseout="this.src=imgnrm'+imgact+'['+ident+'].src"/>';
	}*/
}

function pagosChange(meses, producto)
{
	var cambio=$("#pd"+producto+"-"+meses).val();
	$("#cabprice"+producto).text(meses+" Pagos de:");
	$("#prpagos"+producto).text("$ "+cambio);
}

function showPagos(producto, accion)
{
	if(accion == 1)
	{
		$(".pagosOverlayMod1").fadeOut("medium");
		$(".pagosOverlayMod1").animate({opacity:0},0);
		$("#pg"+producto).show();
		$("#pg"+producto).animate({opacity:0.8},1000);
		
	}
	else
	{
		$(".pagosOverlayMod1").fadeOut("medium");
	}
}

function showPagos2(producto, accion)
{
	if(accion == 1)
	{
		$(".pagosOverlayMod2").fadeOut("medium");
		$(".pagosOverlayMod2").animate({opacity:0},0);
		$("#pg"+producto).show();
		$("#pg"+producto).animate({opacity:0.8},1000);
		
	}
	else
	{
		$(".pagosOverlayMod2").fadeOut("medium");
	}
}

function changeIVA()
{
	var titems=$("#titems").val();
	var conta=0;
	var chk=document.getElementById('ivaact');
	
	if(chk.checked == true)
	{
		while(conta != titems)
		{
			$("#price"+conta).text($("#precioIVA"+conta).val());
			$("#ivatext"+conta).text("IVA Incluído");
			conta++;
		}
	}
	else
	{
		while(conta != titems)
		{
			$("#price"+conta).text($("#precioNormal"+conta).val());
			$("#ivatext"+conta).text("+ IVA");
			conta++;
		}
	}
}

var secs;
var timerID = null;
var timerRunning = false;
var delay = 1000;

function InitializeTimer()
{
    // Set the length of the timer, in seconds
    secs = 1;
    StopTheClock();
    StartTheTimer();
}

function StopTheClock()
{
    if(timerRunning)
        clearTimeout(timerID);
    timerRunning = false;
}

function StartTheTimer()
{
    if (secs==0)
    {
        StopTheClock();
        // Here's where you put something useful that's
        // supposed to happen after the allotted time.
        // For example, you could display a message:
        //alert("You have just wasted 10 seconds of your life.")
		localizar($("#busca1").val());
    }
    else
    {
        self.status = secs;
        secs = secs - 1;
        timerRunning = true;
        timerID = self.setTimeout("StartTheTimer()", delay);
    }
}

/*Timer Galeria*/
var segundos;
var tiempo= null;
var corriendo = false;
var retrazo = 250;

function IniciarGaleria(ident, idactivado)
{
    // Set the length of the timer, in seconds
    segundos = 2;
    Detener();
    Iniciar(ident, idactivado);
}

function Detener()
{
    if(corriendo)
        clearTimeout(tiempo);
    corriendo = false;
}

function Iniciar(ident, idactivado)
{
    //alert('hola '+segundos);
	if (segundos==0)
    {
        Detener();
        changeimg(ident, idactivado)
    }
    else
    {
        self.status = segundos;
        segundos = segundos - 1;
        corriendo = true;
        tiempo = self.setTimeout("Iniciar("+ident+", "+idactivado+")", retrazo);
    }
}

/*Fin Timer Galería*/

function teclaRapida()
{
	var e = document.getElementById('busca1');
	
	e.onkeydown = function (evt) {
		/**
		 * after this, evt will be a keyboard event
		 */
	    evt = (evt) ? evt : ((window.event) ? window.event : "");
		
	    if (evt) {
			/*alert(String.fromCharCode(evt.keyCode));
			alert("Has pulsado la tecla con c&oacute;digo " + evt.keyCode);*/
	    }
	}
}

function swNoticia(idNot)
{
	var actual=$("#activa").val();
	if($("#extnot"+idNot).css("display")=="none")
	{
		if(actual != 0)
		{
			$("#extnot"+actual).slideUp();
			document.getElementById('view'+actual).src='images/showcontent.gif';
		}
		$("#extnot"+idNot).slideDown();
		document.getElementById('view'+idNot).src='images/hidecontent.gif';
		$("#activa").val(idNot);
	}
	else
	{
		$("#extnot"+idNot).slideUp();
		document.getElementById('view'+idNot).src='images/showcontent.gif';
		$("#activa").val('0');
	}
}

function swPPday(idChange, dia)
{
	var valor=document.getElementById('dselect').selectedIndex;
	var texto=document.getElementById('dselect').options[valor].text;
	$("#drdia").html(texto);
	$("#dselect").slideUp("fast");
	
	var actual=parseInt($("#actual").val());
	var cambio=parseInt($("#dselect").val());
	idChange=cambio;
	var ct1="";
	
	//alert(actual);
	switch(actual)
	{
		case 0:
		break;
		case 1:
			ct1="#dvLun";
		break;
		case 2:
			ct1="#dvMar";
		break;
		case 3:
			ct1="#dvMierc";
		break;
		case 4:
			ct1="#dvJuev";
		break;
		case 5:
			ct1="#dvVier";
		break;
		case 6:
			ct1="#dvFnSEM";
		break;
		case 7:
			ct1=".dvrdias";
		break;
		default:
			alert('WTF?');
		break;
	}
	
	//alert(dia);
	if(idChange == dia)
	{
		$("#prdaytit").html('PROMOCIONES POR DIA, VALIDO SOLO HOY');
	}
	else if(idChange == 7)
	{
		var semana=$("#sema").val();
		$("#prdaytit").html('PROMOCIONES POR DIA, '+semana);
	}
	else
	{
		$("#prdaytit").html('PROMOCIONES POR DIA');
	}
	
	switch(cambio)
	{
		case 0:
		break;
		case 1:
			$(ct1).fadeOut("fast",function(){$("#dvLun").fadeIn("fast")});
			$("#actual").val(1);
		break;
		case 2:
			$(ct1).fadeOut("fast",function(){$("#dvMar").fadeIn("fast")});
			$("#actual").val(2);
		break;
		case 3:
			$(ct1).fadeOut("fast",function(){$("#dvMierc").fadeIn("fast")});
			$("#actual").val(3);
		break;
		case 4:
			$(ct1).fadeOut("fast",function(){$("#dvJuev").fadeIn("fast")});
			$("#actual").val(4);
		break;
		case 5:
			$(ct1).fadeOut("fast",function(){$("#dvVier").fadeIn("fast")});
			$("#actual").val(5);
		break;
		case 6:
			$(ct1).fadeOut("fast",function(){$("#dvFnSEM").fadeIn("fast")});
			$("#actual").val(6);
		break;
		case 7:
			$(".dvrdias").fadeIn("fast");
			$("#actual").val(7);
		break;
		default:
			alert('WTF2?');
		break;
	}
}

function dropMaster(drop)
{
	hideDivs();
	if($("#"+drop).css('display') == "none")
	{
		$("#"+drop).slideDown("fast", function(){document.getElementById(drop).focus();});
	}
	else
	{
	  $("#"+drop).slideUp("fast");
	}
}

function selectOpt(base, drop)
{
	//alert('sdas');
	var valor=document.getElementById(drop).selectedIndex;
	var texto=document.getElementById(drop).options[valor].text;
	$("#"+base).html(texto);
	$("#"+drop).slideUp("fast");
}

function ordBy()
{
	var valor=document.getElementById('ordby').selectedIndex;
	var texto=document.getElementById('ordby').options[valor].text;
	$("#drorganiza").html(texto);
	$("#ordby").slideUp("fast");
	document.getElementById('srchorder').submit();
}

function valida_fecha(idDay, idMonth, idYear)
{
    var dia, mes, anyo, bisiesto, valida;
    valida=true;
    dia=$("#"+idDay).val();
    mes=$("#"+idMonth).val();
    anyo=$("#"+idYear).val();
   
   //alert(dia+' '+mes+' '+anyo);
    if ((anyo % 4 == 0) && ((anyo % 100 != 0) || (anyo % 400 == 0)))
    {
        bisiesto=true;
    }
    else
    {
        bisiesto=false;
    }
   
    if (bisiesto == false && mes == 2 && dia >28)
    {
        valida=false;
    }
    else if (bisiesto == true && mes == 2 && dia >29)
    {
        valida=false
    }
   
    if ((mes==2 || mes==4 || mes==6 || mes==9 || mes==11) && dia > 30)
    {
        valida=false;
    }
   
    return valida;
}

function valDataConf()
{
	var contra=jQuery.trim($('#contra').val()), email=jQuery.trim($('#email').val());
	
	//alert(valida_fecha('dia', 'mes', 'anyo'));
	if(valida_fecha('dia', 'mes', 'anyo') == false)
	{
		alert('La Fecha seleccionada no es Valida.');
	}
	else
	{
		if(contra == '')
		{
			alert('No debe dejar la Contraseña en Blanco.');
		}
		else
		{
			if(email == '')
			{
				alert('No debe dejar el Campo E-mail Vacio.');
			}
			else
			{
				document.getElementById('cnfrmdata').submit();
			}
		}
	}
}

function fncopiar()	
{
	document.reg.street_address.value = document.reg.street_addressFact.value;
	document.reg.col.value = document.reg.colFact.value;
	document.reg.cp.value = document.reg.cpFact.value; 
	document.reg.city.value = document.reg.cdFact.value; 
	document.reg.state.value = document.reg.edoFact.value; 
	document.reg.pais.value = document.reg.paisFact.value;
	document.reg.lada.value = document.reg.ladaF.value;  
	document.reg.telephone.value = document.reg.telFact.value; 
	document.reg.fax.value = document.reg.faxFact.value;
}

function openFact()
{
	if($(".factura").css('display')=="none")
	{
		$(".factura").slideDown("fast");
		$("#letfact").text("¿No Desea Factura?");
		$("#fctac").val('1');
		$("#dvfct").show();
	}
	else
	{
		$(".factura").slideUp("fast");
		$("#letfact").text("¿Desea Factura?");
		$("#fctac").val('0');
		$("#dvfct").hide();
	}
}

function valRegUsr()
{
	//Datos
	var valido=true, errtxt="Error: Olvido Completar los Campos: ";
	var firstname=jQuery.trim($("#firstname").val()), lastname=jQuery.trim($("#lastname").val()), correo=jQuery.trim($("#m_add").val()), contra1=jQuery.trim($("#clav").val()), contra2=jQuery.trim($("#confirmation").val()), msc=document.getElementById('msc').checked, fmn=document.getElementById('fmn').checked;
	
	$("input").css({'background-color':'#FFFFFF', 'border':'#A5ACB2 1px solid'});
	if(fmn==false && msc==false)
	{
		valido=false;
		errtxt=errtxt+"Sexo, ";
	}
	
	if(firstname == '')
	{
		valido=false;
		errtxt=errtxt+"Nombre, ";
		$("#firstname").css({'background-color':'#FF0000'});
	}
	
	if(lastname == '')
	{
		valido=false;
		errtxt=errtxt+"Apellido, ";
		$("#lastname").css({'background-color':'#FF0000'});
	}
	
	if(correo == '')
	{
		valido=false;
		errtxt=errtxt+"Correo, ";
		$("#m_add").css({'background-color':'#FF0000'});
	}
	
	if(contra1 == '')
	{
		valido=false;
		errtxt=errtxt+"Contraseña, ";
		$("#clav").css({'background-color':'#FF0000'});
	}
	
	if(contra2 == '')
	{
		valido=false;
		errtxt=errtxt+"Confirmación de Contraseña, ";
		$("#confirmation").css({'background-color':'#FF0000'});
	}
	
	if(contra1 != contra2)
	{
		valido=false;
		alert('Las Contraseñas no son Iguales, Verifique por Favor');
		$("#clav").css({'background-color':'#FF0000'});
		$("#confirmation").css({'background-color':'#FF0000'});
	}
	
	//Factura, Envio
	var company=jQuery.trim($("#company").val()), dFact=jQuery.trim($("#street_addressFact").val()), colFact=jQuery.trim($("#colFact").val()), cpFact=jQuery.trim($("#cpFact").val()), municFact=jQuery.trim($("#munDelFact").val()), cdFact=jQuery.trim($("#cdFact").val()), edoFact=jQuery.trim($("#edoFact").val()), ladaF=jQuery.trim($("#ladaF").val()), telFact=jQuery.trim($("#telFact").val()), rfc=jQuery.trim($("#rfc").val()), direc=jQuery.trim($("#street_address").val()), entre1=jQuery.trim($("#entre1").val()), entre2=jQuery.trim($("#entre2").val()), col=jQuery.trim($("#col").val()), cp=jQuery.trim($("#cp").val()), munic=jQuery.trim($("#munDel").val()), city=jQuery.trim($("#city").val()), state=jQuery.trim($("#state").val()), lada=jQuery.trim($("#lada").val()), telephone=jQuery.trim($("#telephone").val()), fctac=$("#fctac").val();
	if(fctac == 1)
	{
		if(company == '')
		{
			valido=false;
			errtxt=errtxt+"Nombre a Facturar, ";
			$("#company").css({'background-color':'#FF0000'});
		}
		
		if(dFact == '')
		{
			valido=false;
			errtxt=errtxt+'Direccion de Facturación, ';
			$("#street_addressFact").css({'background-color':'#FF0000'});
		}
		
		if(colFact == '')
		{
			valido=false;
			errtxt=errtxt+'Colonia de Facturación, ';
			$("#colFact").css({'background-color':'#FF0000'});
		}
		
		if(cpFact == '')
		{
			valido=false;
			errtxt=errtxt+'C.P. de Facturación, ';
			$("#cpFact").css({'background-color':'#FF0000'});
		}
		
		if(municFact == '')
		{
			valido=false;
			errtxt=errtxt+'Municipio/Delegación de Facturación, ';
			$("#munDelFact").css({'background-color':'#FF0000'});
		}
		
		if(cdFact == '')
		{
			valido=false;
			errtxt=errtxt+'Ciudad de Facturación, ';
			$("#cdFact").css({'background-color':'#FF0000'});
		}
		
		if(edoFact == '')
		{
			valido=false;
			errtxt=errtxt+'Estado de Facturación, ';
			$("#edoFact").css({'background-color':'#FF0000'});
		}
		
		if(ladaF == '')
		{
			valido=false;
			errtxt=errtxt+'Lada de Facturación, ';
			$("#ladaF").css({'background-color':'#FF0000'});
		}
		
		if(telFact == '')
		{
			valido=false;
			errtxt=errtxt+'Telefono de Facturación, ';
			$("#telFact").css({'background-color':'#FF0000'});
		}
		
		if(rfc == '')
		{
			valido=false;
			errtxt=errtxt+'R.F.C., ';
			$("#rfc").css({'background-color':'#FF0000'});
		}
	}
	
	if(direc == '')
	{
		valido=false;
		errtxt=errtxt+'Dirección, ';
		$("#street_address").css({'background-color':'#FF0000'});
	}
	
	if(entre1 == '')
	{
		valido=false;
		errtxt=errtxt+'Entre la calle, ';
		$("#entre1").css({'background-color':'#FF0000'});
	}
	
	if(entre2 == '')
	{
		valido=false;
		errtxt=errtxt+'y la calle, ';
		$("#entre2").css({'background-color':'#FF0000'});
	}
	
	if(col == '')
	{
		valido=false;
		errtxt=errtxt+'Colonia, ';
		$("#col").css({'background-color':'#FF0000'});
	}
	
	if(cp == '')
	{
		valido=false;
		errtxt=errtxt+'C.P., ';
		$("#cp").css({'background-color':'#FF0000'});
	}
	
	if(munic == '')
	{
		valido=false;
		errtxt=errtxt+'Municipio/Delegación, ';
		$("#munDel").css({'background-color':'#FF0000'});
	}
	
	if(city == '')
	{
		valido=false;
		errtxt=errtxt+'Ciudad, ';
		$("#city").css({'background-color':'#FF0000'});
	}
	
	if(state == '')
	{
		valido=false;
		errtxt=errtxt+'Estado, ';
		$("#state").css({'background-color':'#FF0000'});
	}
	
	if(lada == '')
	{
		valido=false;
		errtxt=errtxt+'Lada, ';
		$("#lada").css({'background-color':'#FF0000'});
	}
	
	if(telephone == '')
	{
		valido=false;
		errtxt=errtxt+'Telefono, ';
		$("#telephone").css({'background-color':'#FF0000'});
	}
	
	if(valida_fecha('dia', 'mes', 'anyo') == false)
	{
		valido=false;
		alert('La Fecha seleccionada no es valida.');
	}
	
	if(emailCheck($("#m_add").val()) == false)
	{
		valido=false;
	}
	
	var tCarac=errtxt.length;
	var hasta=tCarac-2;
	var ec=errtxt.substring(0,hasta);
	ec=ec+".";
	if(valido == false)
	{
		alert('Existen Errores, por Favor Rectifique e intente de nuevo.');
		$(".msjerror").html(ec);
	}
	else
	{
		document.getElementById('reg').submit();
	}
}

function recovPassFrm(mode)
{
	if(mode == 0)
	{
		var email=jQuery.trim($("#email_address").val());
		if(email == '')
		{
			alert('Olvido Escribir el Correo Electronico');
		}
		else
		{
			if(valida_fecha('dia', 'mes', 'anyo') == false)
			{
				alert('La Fecha no es Válida.');
			}
			else
			{
				if(emailCheck(email) != false)
				{
					document.getElementById('passrecov').submit();
				}
			}
		}
	}
	else if(mode == 1)
	{
		var email=jQuery.trim($("#email_address").val()), codesec=jQuery.trim($("#ccode").val()), newpass1=jQuery.trim($("#nvpassword").val()), newpass2=jQuery.trim($("#passconfirm").val());
		if(email == '')
		{
			alert('Debe escribir el Correo Electronico.');
		}
		else
		{
			if(codesec == '')
			{
				alert('Debe escribir el Codigo de Validación enviado a su correo.');
			}
			else
			{
				if(newpass1 == '' || newpass2 == '')
				{
					alert('Los Passwords no pueden estar en Blanco.');
				}
				else
				{
					if(newpass1 != newpass2)
					{
						alert('Los Password no Corresponden, por Favor verifique de Nuevo.');
					}
					else
					{
						if(emailCheck(email) != false)
						{
							document.getElementById('passrecov').submit();
						}
					}
				}
			}
		}
	}
}
//Funciones Manejo de cookies
function getCookieVal(offset) 
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
		endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie(name) 
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) 
	{
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

function SetCookie(name, value) 
{
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
    ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
    ((path == null) ? "" : ("; path=" + path)) +
    ((domain == null) ? "" : ("; domain=" + domain)) +
    ((secure == true) ? "; secure" : "");
}

function DeleteCookie(nombre) 
{
	/*var exp = new Date();
	exp.setTime (exp.getTime() - 1000000000);  // This cookie is history (changed -1 to make it previous time)*/
	var cval = GetCookie(nombre);
	document.cookie = nombre + "=" + cval + "; expires= Thu, 01-Jan-70 00:00:01 GMT";
}
//Funciones del Carrito de Compras
/*idProdct=idProducto, cantidad=Cantidad de Elementos, modo: 1=Cambiar Cantidad, 2=Agregar Elementos (modo solo se aplicara en caso que exista el elemento)*/
function addToCart(idProdct, cantidad, modo)
{
	//Obtenemos la cookie
	var cookie=jQuery.trim(GetCookie('CRTPRDS'));
	var prdct="";
	/*
		FORMATO PARA LA COOKIE: idProducto1->cantidad1|idProducto2->cantidad2|...|idProducto20->cantidad20
		Maximo 20 Productos en el Carrito, Maximo 9999 Elementos de Cada Producto
	*/
	//alert(cookie);
	if(cookie == null || cookie == '')//No Hay nada en el Carrito, se Crea un nuevo Carrito
	{
		if(parseInt(cantidad) <= 9999)
		{
			prdct=idProdct+'->'+cantidad;
			SetCookie('CRTPRDS', prdct);
		}
		else
		{
			alert('Esta Cantidad Excede el total de Productos iguales Permitidos.');
			return false;
		}
	}
	else
	{
		
		var cprds=new Array();
		cprds=cookie.split('|');
		var tprods=cprds.length;
		//alert('cPrds: '+cprds);
		if(tprods == 20 && modo == 2)//Carrito Lleno, No hará Nada
		{
			alert('El Carrito esta Lleno, Por Favor Finalice su Pedido.');
			return 'full-1';
		}
		else//El Carrito no está Lleno o se va a modificar la Cantidad
		{
			var conta=0, extpr, productos=new Array(), lcvr=new Array(), cookie2="";
			//alert('a');
			while(conta != tprods)//Extraemos los Valores
			{
				extpr=cprds[conta];
				lcvr=extpr.split('->');
				productos[lcvr[0]]=lcvr[1];
				conta++;
			}
			
			if(productos[idProdct] != null)//¿El Producto ya esta en el Carrito?
			{//Sí
				//alert('lalala');
				var cadena;
				if(modo == 1)
				{
					if(cantidad <= 9999)
					{
						productos[idProdct]=cantidad;
					}
					else
					{
						alert('Esta Cantidad Excede el total de Productos iguales Permitidos.');
						return false;
					}
				}
				else if(modo == 2)
				{
					if(tprods >= 20)
					{
						alert('El Carrito esta Lleno, Por Favor Finalice su Pedido.');
						return 'full-2';
					}
					var ctsuma=parseInt(productos[idProdct])+parseInt(cantidad);
					if(productos[idProdct] < 9999 && ctsuma <= 9999)
					{
						productos[idProdct]=ctsuma;
					}
					else
					{
						alert('No puede Agregar otro Producto igual, ya que excede el total permitido de Productos iguales.');
						return false;
					}
				}
				
				conta=0;
				for(var i in productos)
				{
					//alert(i+'-'+productos[i]);
					if(productos[i] != 0)
					{
						if(conta == 0)
						{
							cookie2+=i+'->'+productos[i];
						}
						else
						{
							cookie2+='|'+i+'->'+productos[i];
						}
						conta++;
					}
				}
			}
			else//No
			{
				//alert('WTF?');
				if(cantidad <= 9999)
				
				{
					cookie2=cookie+'|'+idProdct+'->'+cantidad;//Agregamos el Elemento al Final de la Lista
				}
				else
				{
					alert('Esta Cantidad Excede el total de Productos iguales Permitidos.');
					return false;
				}
			}
			SetCookie('CRTPRDS', cookie2);
			return true;
		}
	}
}

function edCant(idProducto, idCt, mode)
{
	if(mode == 1)//Eliminar
	{
		var cantidad=0;
	}
	else if(mode == 2)
	{
		var cantidad=$('#'+idCt).val();
	}
	//alert(cantidad);
	var ct=parseInt(cantidad);
	addToCart(idProducto, ct, 1);
	location.reload(0);
}

function setPack(idPaq, tpaq)
{
	if(tpaq == 1)//Tienda
	{
		var intro='t->'+idPaq;
	}
	else if(tpaq == 2)//Paqueteria
	{
		var intro=idPaq;
	}
	SetCookie('paqueteria', intro);
	location.reload(0);
}

function openSrc(kind)
{
	if(kind == 1)
	{
		$('#sucursal').slideUp('fast');
		$('#paqueteria').slideDown('fast');
	}
	else if(kind == 2)
	{
		$('#paqueteria').slideUp('fast');
		$('#sucursal').slideDown('fast');
	}
}

function valCart()
{
	var cookiePaq=jQuery.trim(GetCookie('paqueteria'));
	var cart=jQuery.trim(GetCookie('CRTPRDS'));
	if(cookiePaq == '')
	{
		alert('Debe Seleccionar una Paqueteria/Sucursal para continuar.');
		return false;
	}
	else
	{
		if(cart == '')
		{
			alert('Lo invitamos a Seleccionar Productos de nuestro Catalogo.');
			return false;
		}
		else
		{
			window.location='https://www.digitalife.com.mx/nvpagedemo/crtFinal.php';//Antes de otra cosa quitar el nvpagedemo
		}
	}
}

function cartFinApprove()
{
	if(confirm('¿Está Seguro que los Datos son Correctos?'))
	{
		window.location='https://www.digitalife.com.mx/nvpagedemo/saveBuy.php';
	}
}

function dEnvVal()
{
	var calle=jQuery.trim($("#street_address").val()), entre1=jQuery.trim($("#entre1").val()), entre2=jQuery.trim($("#entre2").val()), col=jQuery.trim($("#col").val()), cp=jQuery.trim($("#cp").val()), numDel=jQuery.trim($("#munDel").val()), city=jQuery.trim($("#city").val()), state=jQuery.trim($("#state").val()), lada=jQuery.trim($("#lada").val()), telephone=jQuery.trim($("#telephone").val());
	
	if(calle == '' || entre1 == '' || entre2 == '' || col == '' || cp == '' || munDel == '' || city == '' || state == '' || lada == '' || telephone == '')
	{
		alert('Olvido Escribir una Información Importante. \nRecuerde que los campos marcados con * son Requeridos.');
	}
	else
	{
		if(confirm('¿Esta Seguro que la Información es Correcta?'))
		{
			document.getElementById('reg').submit();
		}
	}
}

function dFactVal()
{
	var company=jQuery.trim($("#company").val()), street=jQuery.trim($("#street_addressFact").val()), colFact=jQuery.trim($("#colFact").val()), cpFact=jQuery.trim($("#cpFact").val()), munDelFact=jQuery.trim($("#munDelFact").val()), cdFact=jQuery.trim($("#cdFact").val()), lada=jQuery.trim($("#lada").val()), telFact=jQuery.trim($("#telFact").val()), faxFact=jQuery.trim($("#faxFact").val()), rfc=jQuery.trim($("#rfc").val()), factura=$('input[name=factura]:checked').val();
	
	if(factura == 1)
	{
		if(company == '')
		{
			alert('Debe poner un Nombre a Facturar \nSi esta Seleccionada la Casilla ¿Desea Factura?, por favor seleccione No en Caso que no desee Factura.');
		}
		else
		{
			if(street == '' || colFact == '' || cpFact == '' || cdFact == '' || lada == '' || telFact == '' || edoFact == '' || munDelFact == '')
			{
				alert('Olvido Escribir una Información Importante. \nRecuerde que los campos marcados con * son Requeridos');
			}
			else
			{
				if(confirm('¿Está seguro que la Información es Correcta?'))
				{
					document.getElementById('reg').submit();
				}
			}
		}
	}
	else
	{
		if(confirm('¿Está seguro que NO desea Factura?'))
		{
			document.getElementById('reg').submit();
		}
	}
}