//****************************************************	
	//AJAX para actualizar carrito y obtener el numero de items	
	var xmlHttp = null;
	var bshowcart=0;
	var bupdatecart=0;
	
	function showCart(){ 
		document.getElementById("sidecart").style.display="block";
	}	
	
	function hideCart(){ 
		document.getElementById("sidecart").style.display="none";
	}


	function getResponseDebug(){
		if(xmlHttp.readyState == 4){ 
			straux=xmlHttp.responseText;
			//alert(straux);
			location.reload(true);
		}
	}
	
	function getResponseOptions(){
		if(xmlHttp.readyState == 4){
			//straux=xmlHttp.responseText;
			//alert(straux);
			//location.reload(true);
      //Pasa al siguiente paso
      location.href="index.php?content=shopping&refid=1&step=4";//pasa al siguiente paso       
		}
	}
	
	function getResponseNewUser(){
		if(xmlHttp.readyState == 4){ 
			var rta=parseInt(xmlHttp.responseText);	
			//alert(xmlHttp.responseText);
			obj=document.getElementById("txtproceso2");
			if (rta==2){
				//El usuario ya existe				
				alert("Ya existe un usuario registrado con esa cuenta de correo!");
			}else if(rta==1){
				//document.getElementById("discountmsg").innerText="";
				//location.reload(true);
				location.href="index.php?content=shopping&refid=1&step=3";//pasa al siguiente paso
			}else if(rta==10){
			  location.href="index.php?content=loginok";//pasa al siguiente paso
			}else{
				alert("No fue posible procesar el registro!\n" + xmlHttp.responseText );
			}
			document.getElementById("txtproceso2").style.display="none";
		}		
	}		

	function getResponseAddress(){
	  if(xmlHttp.readyState == 4){ 
      //alert(xmlHttp.responseText);
      location.reload(true);
    }
	}		
	
	function getResponseRefresh(){
	  if(xmlHttp.readyState == 4){ 
      //alert(xmlHttp.responseText);
      location.reload(true);
    }
	}	
	
	function getResponseValidateUser(){
		if(xmlHttp.readyState == 4){ 
			var userok=parseInt(xmlHttp.responseText);
			//alert(xmlHttp.responseText);
      if (userok==200){
				//Usuario Registrado Shopping Cart 
				location.href="index.php?content=shopping&refid=1&step=3";//pasa al siguiente paso
      }else if (userok==201){
				//Usuario Registrado Login
				location.href="index.php?content=loginok";				
			}else{
				alert("Los datos de registro No son validos. Por Favor intente de nuevo!\n" + xmlHttp.responseText);
			}
			document.getElementById("txtproceso1").style.display="none";			
		}		
	}	
	
	function getResponseDiscount(){
		if(xmlHttp.readyState == 4){ 
			var discount=parseInt(xmlHttp.responseText);
			//alert(xmlHttp.responseText);
      if (discount==0){
				//No hay descuento
				if(document.all){
             document.getElementById("discountmsg").innerText = "Código No Valido!";
        } else{
            document.getElementById("discountmsg").textContent = "Código No Valido!";
        }
			}else{
				document.getElementById("discountmsg").innerText="";
				location.reload(true);
			}			
		}
	}		
	

	function getResponseUpdate(){
		if(xmlHttp.readyState == 4){ 
			//straux=xmlHttp.responseText;
			//alert(straux);
			//Actualiza Numero de Items y muestra carrito
			inisidecart(1, 1, 1);
		}
	}

 	function getResponseUpdatePromo(){
		if(xmlHttp.readyState == 4){ 
			//straux=xmlHttp.responseText;
			//alert(straux);
			//Actualiza Numero de Items y muestra carrito
      location.reload(true);			
		}
	}

	function getResponseItemsList(){
		if(xmlHttp.readyState == 4){ 
			straux=xmlHttp.responseText;
			//alert(straux);
			var obj1=document.getElementById("sidecart"); //SideCart
			if (obj1) obj1.innerHTML=straux;
			if (bshowcart==1){
				//obj1.style.display="block";
				showCart();
				setTimeout("hideCart()",10000);
			}
			if (bshowcart==0) obj1.style.display="none"; 
		}
	}
	
	function getResponseNumItems(){
		if(xmlHttp.readyState == 4){ 
			//Actualiza el numero de items en el sidecart
			var qty=parseInt(xmlHttp.responseText);
			//alert(xmlHttp.responseText);
			var color="";
			objaux=document.getElementById("noitems");
			//alert(qty);
			if (qty>0){							
				if (objaux) objaux.innerHTML="Tienes <b>"+qty+"</b> Items en tu carrito de compras.";						
			}else{
				if (objaux) objaux.innerHTML="No tienes Items en tu Carrito de Compras";			 
				color="#959595";
			}
			objaux=document.getElementById("linkcart1");						
			if (objaux) objaux.style.color=color;
			objaux=document.getElementById("linkcart2");
			if (objaux) objaux.style.color=color;					
			
			if (bupdatecart==1){
				ajaxGETCommand("updateitemslist", "includes/cart_sidecartitems.php"); //Muestra Pantalla
			}
		} 		
	}

	
	function ajaxGETCommand(action,url){
		try{
			xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
		}catch (e){
			try{
				xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
			}catch (e){
				try{
					xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
				}catch (e){
					alert("Your browser does not support AJAX.");
					return false;
				}
			}
		}
		var nocacheurl = url; //+"?t="+timestamp;
		/*
		if (action=="validatenewuser"){
			xmlHttp.open("POST",nocacheurl,true);
			xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length",0);
			xmlHttp.setRequestHeader("Connection", "close");			
			alert("POST");
		}else{									
			xmlHttp.open("GET",nocacheurl,true);
		}*/	
		xmlHttp.open("GET",nocacheurl,true);
		xmlHttp.send(null);
		switch(action){
			case "deleteitemmain":
			case "updateqtymain":
				//Do Nothing								   
				xmlHttp.onreadystatechange = getResponseDebug;
				break;
			case "additem":
			case "deleteitem":
			case "updateqty":
      case "addbonoregalo":      			
				xmlHttp.onreadystatechange = getResponseUpdate;
				break;
			case "additempromo":
				xmlHttp.onreadystatechange = getResponseUpdatePromo;
				break;
			case "getitemsnumber":
				xmlHttp.onreadystatechange = getResponseNumItems;
				break;
			case "updateitemslist":	
				xmlHttp.onreadystatechange = getResponseItemsList;
				break;
			case "applydiscount":
				xmlHttp.onreadystatechange = getResponseDiscount;
				break;
			case "validateuser":
				xmlHttp.onreadystatechange = getResponseValidateUser;
				break; 
			case "validatenewuser":
				xmlHttp.onreadystatechange = getResponseNewUser;
				break;
			case "updateoptions":
				xmlHttp.onreadystatechange = getResponseOptions;
				break;										
			case "addressnew":
			case "addressdelete":
			case "addressselect":
				xmlHttp.onreadystatechange = getResponseAddress;
				break;
      case "showusd":
				xmlHttp.onreadystatechange = getResponseRefresh;
				break;        										
		}
	}
	
	function showusd(val){
    //alert(val); 
		ajaxGETCommand("showusd", "includes/cart_showusd.php?action=" + val); 
	}	
	
  function inisidecart(inicase, updatecart, showcart){//Actualiza el carrito de compras sidecart pero no lo muestra
		bupdatecart=updatecart;
		bshowcart=showcart;		
		switch (inicase){
			case 1: //Actualiza el numero de items en el sidecart								   
				ajaxGETCommand("getitemsnumber", "includes/cart_getitemscount.php"); //Adiciona Item 
				break;
			case 2: //Refresh a la lista de items en el sidecart
				ajaxGETCommand("updateitemslist", "includes/cart_sidecartitems.php"); //Adiciona Item
				break;
		}
	} 
	
	function fadditem(itemid, itemwoid, type){
    var baux=0;
		var addcase=0;
		
		sobj1=document.getElementById("OPT1_"+itemid);
		sobj2=document.getElementById("OPT2_"+itemid);
		
		if (sobj1 && sobj2){ //Doble Opcion
		  var op1=sobj1.options[sobj2.selectedIndex].value;
      var op2=sobj2.options[sobj2.selectedIndex].value;			 	  
      itemwoid=sobj2.options[sobj2.selectedIndex].getAttribute("iid2");
      addcase=1; 
    }else if(sobj1){ //Una Opcion
		  var op1=sobj1.options[sobj1.selectedIndex].value;
		  itemwoid=sobj1.options[sobj1.selectedIndex].getAttribute("iid1"); //Sin Opciones o Una Opcion
		  addcase=2;
    }else{
    }
				
    if (op1==0 && op2==0 & addcase==1){//Opcion 1 y Opcion 2 Obligatorias					
			alert ("Por Favor Seleccione las Opciones");
			baux=1;
		}else if(op1==0 & addcase==2){//Opcion 1 Obligatoria
			alert ("Por Favor Seleccione una Opción");
			baux=1;
		}else if(addcase==0){
			op1=0;
			op2=0;
		} 
		//alert(type);
    if (baux==0){
			if (type==1){
        ajaxGETCommand("additem", "includes/cart_updatecart.php?action=add&itemwoid=" + itemwoid);
      }else{
        ajaxGETCommand("additempromo", "includes/cart_updatecart.php?action=add&itemwoid=" + itemwoid);
      }       
		}	
	} 
	
	function additem(itemid, itemwoid){
	 fadditem(itemid, itemwoid, 1, 0);	 
	}
	
  function additempromo(itemid, itemwoid){
	 fadditem(itemid, itemwoid, 2, 0);
	}
	 
	function deleteitem(itemwoid){
    //alert(itemwoid); 
		ajaxGETCommand("deleteitem", "includes/cart_updatecart.php?action=delete&itemwoid=" + itemwoid); 
	}

	function deleteitemmain(itemwoid){ 
		ajaxGETCommand("deleteitemmain", "includes/cart_updatecart.php?action=delete&itemwoid=" + itemwoid); 
	}

	function updateqty(itemwoid, qty){ 
		ajaxGETCommand("updateqty", "includes/cart_updatecart.php?action=update&itemwoid=" + itemwoid + "&qty=" + qty); 
	}

	function updateqtymain(itemwoid, qty){
		//alert(qty);
    ajaxGETCommand("updateqtymain", "includes/cart_updatecart.php?action=update&itemwoid=" + itemwoid + "&qty=" + qty); 
	}	
	
	function addbonoregalo(){
    var $nombre=document.getElementById("crto").value;
	  var $email=document.getElementById("crmailto").value;
	  var $msg=document.getElementById("crmsg").value;
	  var $valor=document.getElementById("crvalue").value;
    if ($nombre=='' || $email=='' || $valor==''){
      alert('Los campos con * son obligatorios');      
    }else{
      if ($valor<30000){
        alert('El campo de Valor debe ser de Mínimo $30000');
        exit;
      }

      var $itemwoid=1;      
      ajaxGETCommand("addbonoregalo", "includes/cart_updatecart.php?action=add&itemwoid=" + $itemwoid + "&nombre=" + $nombre + "&email=" + $email + "&msg=" + $msg + "&valor=" + $valor);      
    } 
  }
	
	//AJAX para Registro de Usuario	
	function validateuser(valcase, t){ 		
		if (valcase==1){//Usuario Registrado
			document.getElementById("txtproceso1").style.display="block";
			email1=document.getElementById("email1").value;
			pass1=document.getElementById("pass1").value; 
			ajaxGETCommand("validateuser", "includes/user_validate.php?p=" + pass1 + "&e=" + email1 + "&type=" + t); 
		}else{//Nuevo Usuario 			
			document.getElementById("txtproceso2").style.display="block";
			//var url="includes/user_newuser.php";
			//ajaxGETCommand("validatenewuser", "includes/user_validatenewuser.php?nombres=" + document.getElementById("nombres").value);
			//ajaxGETCommand("validatenewuser", url);			
      if (ValidateForm(valcase)==true){
					if (t==4){
            //alert (valcase);
            var url="includes/user_newuser.php"; 					
  					url += "?case=" + valcase;
  					url += "&type=" + t;
  					url += "&nombres=" + document.getElementById("nombres").value; 
  					url += "&apellidos=" + document.getElementById("nombres").value;
  					url += "&genero=0";
  					url += "&dd=00";
  					url += "&mm=00";
  					url += "&yy=00";
  					add=document.getElementById("direccion").value;
  					add=add.replace("#"," ")
            url += "&direccion=" + add; 
  					url += "&pais=" + document.getElementById("pais").value;
  					url += "&ciudad=" + document.getElementById("ciudad").value;
  					url += "&otraciudad=" + document.getElementById("otraciudad").value;
  					url += "&telefono=" + document.getElementById("telefono").value; 
  					url += "&movil=" + document.getElementById("movil").value;
  					url += "&email=" + document.getElementById("email").value;
  					if (valcase!=3){
  						url += "&pass=" + document.getElementById("pass").value;					
  						url += "&acepto=" + document.getElementById("acepto").checked;					
  					}
          }else{
            var url="includes/user_newuser.php"; 					
  					url += "?case=" + valcase;
  					url += "&type=" + t;
  					url += "&nombres=" + document.getElementById("nombres").value; 
  					url += "&apellidos=" + document.getElementById("apellidos").value;
  					url += "&genero=" + document.getElementById("genero").options[document.getElementById("genero").selectedIndex].text;
  					url += "&dd=" + document.getElementById("dd").value;
  					url += "&mm=" + document.getElementById("mm").value;
  					url += "&yy=" + document.getElementById("yy").value;
  					add=document.getElementById("direccion").value;
  					add=add.replace("#"," ")
            url += "&direccion=" + add; 
  					url += "&pais=" + document.getElementById("pais").value;
  					url += "&ciudad=" + document.getElementById("ciudad").value;
  					url += "&otraciudad=" + document.getElementById("otraciudad").value;
  					url += "&telefono=" + document.getElementById("telefono").value; 
  					url += "&movil=" + document.getElementById("movil").value;
  					url += "&email=" + document.getElementById("email").value;
  					if (valcase!=3){
  						url += "&pass=" + document.getElementById("pass").value;					
  						url += "&acepto=" + document.getElementById("acepto").checked;					
  					}
          }  
					//alert(url);
					ajaxGETCommand("validatenewuser", url);
			}
		}			
	}	
	
	function newaddress($email){
    if (ValidateForm(4)==true){
			var url="user_addressnew.php"; 					
			url += "?email=" + $email;
			url += "&nombres=" + document.getElementById("nombres").value; 
			url += "&apellidos=" + document.getElementById("apellidos").value;
			add=document.getElementById("direccion").value;
			add=add.replace("#"," ")
      url += "&direccion=" + add; 
			url += "&pais=" + document.getElementById("pais").value;
			url += "&ciudad=" + document.getElementById("ciudad").value;
			url += "&otraciudad=" + document.getElementById("otraciudad").value;
			url += "&telefono=" + document.getElementById("telefono").value; 
			url += "&movil=" + document.getElementById("movil").value;
			//alert (url);
			ajaxGETCommand("addressnew", url);
		}
  }
  
  function deleteaddress($aid){
    var url="user_addressdelete.php";
    url += "?aid=" + $aid;
		ajaxGETCommand("addressdelete", url);    
  }
  
  function selectaddress($aid, $email){
    var url="user_addressselect.php";
    url += "?email=" + $email;
    url += "&aid=" + $aid;
		//alert(url);
    ajaxGETCommand("addressselect", url);    
  }
	
	function updateuserdata(){
		document.getElementById("tableuserdata").style.display="block";	
	}
	
	function updateoptions(valcase,option){		  
		url="includes/cart_updateoptions.php?option=" + option + "&case=" + valcase;
		ajaxGETCommand("updateoptions", url);
	}
	
	/*
  function salemoneychange($val1){
     	 alert('ja');
       $val2 = document.getElementById("totalcell").value;
     	alert($val2);
  } */
					 						  
//****************************************************
	//Obtiene Código Descuentos
	function applydiscount(){ 
		sobj=document.getElementById("dcode");
		discode=sobj.value;
		ajaxGETCommand("applydiscount", "includes/cart_checkdiscount.php?discode=" + discode); 
	}	
	
	function addCommas(nStr)
	{
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	}
	
	function removePriceFormat(sprice){
		sprice=sprice.replace(/$/,"");
		sprice=sprice.replace(/./,"");
		sprice=sprice.replace(/,/,"");					
		sprice=parseInt(sprice);
		return sprice;	
	}

//****************************************************	
//Validacion de Formulario
function alpha(e) {
     var k;     
     document.all ? k = e.keyCode : k = e.which;
     return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32) || k==0;
}

function numbersonly(e){
	var unicode=e.charCode? e.charCode : e.keyCode
  if (unicode!=8 && unicode!=9){ //if the key isn't the backspace key (which we should allow)
		if (unicode<48||unicode>57 || unicode==0) //if not a number
		return false //disable key press
	}
}

function validarFecha(pDia, pMes, pAno){
	var rta = 0;
	var monthLength = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var day = parseInt(pDia);
	var month = parseInt(pMes);
	var year = parseInt(pAno);
		
	if (year/4 == parseInt(year/4))
		monthLength[1] = 29;

	if (day > monthLength[month-1])
		rta = -1;
	else{
		var now = new Date();
		now = now.getTime(); //NN3

		var dateToCheck = new Date();
		dateToCheck.setYear(year);
		dateToCheck.setMonth(month-1);
		dateToCheck.setDate(day);
		var checkDate = dateToCheck.getTime();

		if(now < checkDate)
			rta = 1;
	}
	return rta;
}

function validar(obj, len){//Objeto, numero de caracteres minimo, div validador
	val=true;
	if(document.getElementById(obj).value.length<len) val=false;	
	return val;
};
	
function ValidateForm(valcase){
//valcase=1(Nuevo desde SignUp), 2(Nuevo desde ShoppingCart), 3(Update), 4(New Address), 5 Wholesale
    //alert (valcase);
    
    val=validar('nombres',3);
		if(!val){
			alert('Por favor ingrese su nombre');
			document.getElementById('nombres').focus();
			//return (val);
			return false;
		}
		if (valcase!=5){
  		val=validar('apellidos',3);
  		if(!val){
  			alert('Por favor ingrese su apellido');
  			document.getElementById('apellidos').focus();
  			//return (val);
  			return false;
  		}		
    }
		
		/*
		val=validar('genero',0);
		if(!val){
			alert('Por favor seleccione una opción de género');
			document.getElementById('apellidos').focus();
			//return (val);
			return false;
		}	*/ 

		if (valcase!=4 && valcase!=5){
      //Fecha de Nacimiento		
  		var strDia = document.getElementById('dd').value;
  		var strMes = document.getElementById('mm').value;
  		var strAno = document.getElementById('yy').value;				
  		if(strDia == ''){
  			alert("Por favor seleccione una fecha de nacimiento valida.");
  			document.getElementById('dd').focus();
  			return false;
  		}		
  		if(strMes == ''){
  			alert("Por favor seleccione una fecha de nacimiento valida.");
  			document.getElementById('mm').focus();
  			return false;
  		}
  		if(strAno.length == 0){					
  			alert("Por favor seleccione una fecha de nacimiento valida.");
  			document.getElementById('yy').focus();
  			return false;
  		}
  		if(isNaN(strAno) == true){
  			alert("Por favor ingrese unicamente valores numericos en el campo año.");
  			document.getElementById('yy').value = '';
  			document.getElementById('yy').focus();
  			return false;
  		}
  		var iRta = validarFecha(strDia, strMes, strAno); 			
  		if(iRta > 0){
  			alert("La fecha de nacimiento debe ser menor que la fecha actual.");
  			document.getElementById('yy').focus();
  			return false;
  		}
  		if(iRta == -1){
  			alert("Por favor seleccione una fecha de nacimiento valida.");
  			return false;
  		}
    }
    //Direccion    
		val=validar('direccion',4);
		if(!val){
			alert('Por favor ingrese una direccion');
			document.getElementById('direccion').focus();
			//return (val);
			return false;
		} 
		
		//Ciudad - Pais
		if (document.getElementById('ciudad').value=='-OTRA CIUDAD-'){
			val=validar('otraciudad',3);	
			if(!val){
				alert('Usted selecciona -OTRA CIUDAD-, por favor indique el nombre de la ciudad.');
				document.getElementById('ciudad').focus();
				//return (val);
				return false;
			}							
		}else{
		 	document.getElementById('otraciudad').value=document.getElementById('ciudad').value;
		}
		
		val=validar('telefono',7);
		if(!val){
			alert('Por favor ingrese un telefono');
			document.getElementById('telefono').focus();
			//return (val);
			return false;
		}
					
		if (valcase==1 || valcase==2){ 			
      val=validar('email',5);
			if(!val){
				alert('Por favor ingrese una cuenta de correo electronico valida ');
				document.getElementById('email').focus();
				//return (val);
				return false;
			}
			if (document.getElementById('email').value!=document.getElementById('email2').value){
				alert('Los datos de Email No son iguales. Por favor verifique');
				document.getElementById('email').focus();
				//return (val);
				return false;
      
      }
			if (valEmail(document.getElementById('email').value)==false)
			{
				document.getElementById('email').focus();
				return false;
			}
			//Solo para Nuevo Usuario
			val=validar('pass',4);
			if(!val){
				alert('Por favor ingrese una contraseña valida (minimo 6 caracteres)');
				document.getElementById('pass').focus();
				//return (val);
				return false;
			}	
			if (document.getElementById('pass').value!=document.getElementById('pass2').value)
			{
				alert('Las contraseñas No son iguales, por favor verifique');
				document.getElementById('pass').focus();
				//return (val);
				return false;
			}
		} 
    return true;
 }
 
 function valEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   alert("Por favor ingrese un email valido")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   alert("Por favor ingrese un email valido")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
	    alert("Por favor ingrese un email valido")
	    return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
	    alert("Por favor ingrese un email valido")
	    return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
	    alert("Por favor ingrese un email valido")
	    return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
	    alert("Por favor ingrese un email valido")
	    return false
	 }
	
	 if (str.indexOf(" ")!=-1){
	    alert("Por favor ingrese un email valido")
	    return false
	 }
	 return true;
}

