/// #################################################


function verCampos(ruta){
	val=0;
	envio=0;
	for(var i=0; i<ruta.elements.length; i++){
		controlAct=ruta.elements[i];
		if(ruta.elements[i].title.indexOf("@")!=-1){//si existe * entonces valida datos del control actual
			propControl = ruta.elements[i].title.split("@");
			if(propControl[1].indexOf("r")!= -1){//si es diferente de -1 entonces es un control requerido
			//longitud = cadena1.length;
				
				if(controlAct.value.length>0 && controlAct.value!=""){
					///verificar si el mail es correcto
					if(emailCheck(controlAct.value)==0){
						val++;
						alert(INSC_ALERT_EMAIL);
						controlAct.focus();
						return val;
						break;
						
					}else{
						envio++;
					}

				}
	
			}
		}
		
	}
	//alert(retor);
	if(envio==0){val=1;}
	return val;

}
//###fin VALIDACION DEL  recomienda	
//###VALIDACION DEL  Newsletter	


//#FIN DE LA VALIDADION DEL Newsletter
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
{
	validar_login(1);
}
else
	return true;
}

function submitenter_rechercher(myfield,e)
{
	
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
{
	document.frm_busqueda.submit();
	//alert(alert_buscador);
}
else
	return true;
}
function submitenter_newsleter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
{
	validar_newsletter();
}
else
	return true;
}

///inicio fun2
function replaceSubstring (inputString, badString,
                          goodString, caseSensitive) {
  fixedReplace = "";
  UI = inputString;
  UB = badString;
  if ((caseSensitive != 1) && (caseSensitive != true)) {
  UI = inputString.toUpperCase();
     UB = badString.toUpperCase();
     }
  badEnd = -1;
  badLoc = UI.indexOf(UB);
  if (badLoc != -1) {
     for (x=1; (badLoc != -1); x++) {
        fixedReplace = fixedReplace + 
                       inputString.substring((badEnd +
                       1), badLoc) + goodString
        badEnd = badLoc + UB.length - 1;
        badLoc = UI.indexOf(UB, (badLoc + 1)); }
     fixedReplace = fixedReplace + 
                    inputString.substring((badEnd + 1),
                    inputString.length); }
     else { fixedReplace = inputString;    }
return fixedReplace;
}


function eliminar(ruta) {
conf=confirm(document.frm_inscripcion.alert_delete.value);
if(conf)
location.href=ruta;	
}
function FitPic() {
	var arrTemp=self.location.href.split("?"); 
	var picUrl = (arrTemp.length>0)?arrTemp[1]:""; 
	var NS = (navigator.appName=="Netscape")?true:false; 	 
	iWidth = (NS)?window.innerWidth:document.body.clientWidth; 
	iHeight = (NS)?window.innerHeight:document.body.clientHeight; 
	iWidth = (document.images[0].width + 100) - iWidth; 
	iHeight = (document.images[0].height +100)- iHeight; 
	window.resizeBy(iWidth, iHeight); 
	self.focus(); 
}; 

function popImage(imageURL,imageTitle)
{
// Set the horizontal and vertical position for the popup
PositionX = 100;
PositionY = 100;
// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)
defaultWidth  = 500;
defaultHeight = 500;
// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows
img=imageURL.split("|");

if(img[1]=='1'){
	var AutoClose = true;		
}else{
	var AutoClose = false;	
}

// Do not edit below this line...
// ================================
if (parseInt(navigator.appVersion.charAt(0))>=4){
var isNN=(navigator.appName=="Netscape")?1:0;
var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}
var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY;	
if (isNN){imgWin=window.open('about:blank','',optNN);}
if (isIE){imgWin=window.open('about:blank','',optIE);}
with (imgWin.document){
writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>');
writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);');
writeln('width=120-(document.body.clientWidth-document.images[0].width);');
writeln('height=100-(document.body.clientHeight-document.images[0].height);');
writeln('window.resizeTo(width,height);}');writeln('if (isNN){');       
writeln('window.innerWidth=document.images["George"].width;');writeln('window.innerHeight=document.images["George"].height;}}');
writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>');
if (!AutoClose) writeln('</head><body scroll="no" onload="reSizeToImage();doTitle();self.focus()">')
else writeln('</head><body scroll="no" onload="reSizeToImage();doTitle(); self.focus()" onblur="self.close()">');
//writeln('<div style="width:100%; background-color:#CCCCCC; z-index:1;position:absolute;right:0; bottom:0;filter:alpha(opacity=70);-moz-opacity:0.7;-khtml-opacity:0.7;opacity:0.7;font-family:Geneva, Arial, Helvetica, sans-serif; font-size:11px;font-weight:bold;color:#333333">&nbsp;'+imageTitle+'</div>');
writeln('<img name="George" src="'+img[0]+'" style="display:block"></body></html>');
close();		
}}


function OpenNewWindow(url,name,w,h) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var v = window.open(url,name,'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width='+w+',height='+h+',top='+wint+',left='+winl);
}

function limpia_txt_obj_detail(){
	document.frm_carro.txt_cantidad.value="";
	document.frm_carro.txt_stotal.value="0.00";
	
	//document.getElementById('txt_cantidad').focus();
}

function calcular(precio,cantidad,prodid,showstock)
{
 var valor = precio * cantidad;
 if(showstock=='1'){
	indice=document.frm_carro.taille_slt.selectedIndex;	
	idTalla=document.frm_carro.taille_slt.options[indice].value;
	
	indicecolor=document.frm_carro.color_slt.selectedIndex;
	idColor=document.frm_carro.color_slt.options[indicecolor].value;
	
	//idColor='1';
	
	cadena=idColor+","+idTalla+","+prodid+","+cantidad;
	//alert(cadena);
	jsrsExecute("./include/verifica_cantidad_add_carrito.php",fin_verifica_Q_carrito,"confirmar",cadena);
 }else{
	document.getElementById("btn_validar_off").style.display='none';
	document.getElementById("btn_validar_on").style.display=''; 
 }
 
 x=cantidad.split('.');
 if(x.length > 1)
 {
  if(x[1].length > 2)
   document.frm_carro.txt_cantidad.value=redondear(cantidad);
 }
 
 document.frm_carro.txt_stotal.value=redondear(valor); 	
}

function fin_verifica_Q_carrito(cadena){

	datos=cadena.split("|");
	
	//alert(cadena);
	
	if(datos[0]=="1"){			
		alert("Vous ne pouvez pas commander plus de "+datos[1]+" Articles ");
		document.getElementById("btn_validar_on").style.display='none';
		document.getElementById("btn_validar_off").style.display='';
	}
	if(datos[0]=="0"){		
		document.getElementById("btn_validar_on").style.display='';
		document.getElementById("btn_validar_off").style.display='none';
	}
	if(datos[0]=="2"){
		alert("Stock insuffisant");
		document.getElementById("btn_validar_on").style.display='none';
		document.getElementById("btn_validar_off").style.display='';		
	}
	
	
	
}

function calcular_group(precio,cantidad,indice)
{
 var valor = precio * cantidad;
 
 x=cantidad.split('.');
 if(x.length > 1)
 {
  if(x[1].length > 2)
   document.getElementById('cant'+indice).value = redondear(cantidad);
 }
 document.getElementById('stotal'+indice).value=redondear(valor); 	
}

function teclear(e,valor) 
{
tecla=(document.all) ? e.keyCode : e.which;
if(tecla==46)
 if(valor.indexOf('.') != "-1")
  return false;
	 
if(tecla<46 || tecla>57 || tecla==47)
return false;

}

function teclear_punto(e) 
{
tecla=(document.all) ? e.keyCode : e.which;
	 
if(tecla<=46 || tecla>57 || tecla==47)
return false;

}

function cargar_region(pais)
{
  cadena=pais;
  jsrsExecute("./include/cargar_region.php",enviar_region,"confirmar",cadena);
}

function radio_button_checker(form){
	var radio_choice = -1;
	if(form.pagos!=null){//si existe
		if(form.pagos.length==undefined){
			radio_choice = form.pagos.value;
		}else{
			for(counter = 0; counter < form.pagos.length; counter++){
				if(form.pagos[counter].checked){
					radio_choice = form.pagos[counter].value; 
				}
			}
		}
	}
	return radio_choice;
}

/*
function radio_button_checker1(form)
{
	var radio_choice = -1;
	total=form.totalfpagos.value

	for(i=0;i<total;i++){
		if(document.getElementById("pagos"+i).checked==true){
			radio_choice = document.getElementById("pagos"+i).value;
		}
	}
return radio_choice;
}*/

function radio_button_checker_old(form)
{
var radio_choice = -1;

for (counter = 0; counter < form.pagos.length; counter++) {
 if (form.pagos[counter].checked) 
  radio_choice = form.pagos[counter].value; 
}

return radio_choice;
}

function radio_button_checker1(form)
{
	var radio_choice = -1;
	
	for (counter = 0; counter < form.envios.length; counter++) 
	{
	  if (form.envios[counter].checked) 
	   radio_choice = form.envios[counter].value; 
	}

return radio_choice;
}


function get_taille(color,prodid)
{
	

  var cadena=color+","+prodid;
  document.getElementById("stock_dispo").style.display='none';
  /*if(color=="--"){
	  document.getElementById("contenedor").style.display='none';  
	  document.getElementById("showtaille").style.display='none';
	  document.getElementById("btn_validar_off").style.display='';
	  document.getElementById("btn_validar_on").style.display='none';
  }else{
	  document.getElementById("showtaille").style.display='';
  }*/
  //alert(cadena);
  jsrsExecute("./include/get_taille.php",fin_taille,"confirmar",cadena);
  
}

function fin_taille(cadena)
{
	alert("holas");
  var form = document.frm_carro;
  datos=cadena.split("|");
  
  id=datos[0].split(",");
  nb=datos[1].split(",");
   
  cid=id.length;
   
  form.taille_slt.options.length=1;
  if(cid==1)
  {
   otraopcion=new Option("------","");
   form.taille_slt.options[0]=otraopcion;
  }

 for(x=0; x < cid-1; x++)
 {   	
	otraopcion=new Option(nb[x],id[x]);
	form.taille_slt.options[x]=otraopcion;
 }
 
 // se agrego estas lineas de codigo para el popup de colores
 for(var y=0; form.color_slt.options.length; y++) {
	if(form.color_slt.options[y].value==datos[3])  {
		form.color_slt.options[y].selected=true;
		break;
	}
 }
 //-----------------------------------------------------------
 
 limpia_txt_obj_detail();
 form.taille_slt.focus();
 
}

function verifica_stock(prodid,showstock){
	document.getElementById("stock_dispo").style.display='none';
	indice=document.frm_carro.taille_slt.selectedIndex;	
	idTalla=document.frm_carro.taille_slt.options[indice].value;
	
	indicecolor=document.frm_carro.color_slt.selectedIndex;	
	idColor=document.frm_carro.color_slt.options[indicecolor].value;
	
	/*idColor='1';*/
	
	/*document.getElementById("contenedor").style.display='';*/
	
	if(showstock=="1"){
		cadena=idColor+","+prodid+","+idTalla;
		//alert(cadena);
		jsrsExecute("./include/control_stock.php",fin_control_stock,"confirmar",cadena);
	}else{
		///para ver si no hay stock 
		cadena=idColor+","+prodid+","+idTalla;
		jsrsExecute("./include/control_stock_dispo.php",fin_control_no_stock,"confirmar",cadena);
	}
	//alert(cadena);
	/*limpia_txt_obj_detail();
	document.getElementById("btn_validar_on").style.display='none';
	document.getElementById("btn_validar_off").style.display='';*/
}
function fin_control_no_stock(cadena){
	//alert(cadena);
	if(cadena==0)
	document.getElementById("stock_dispo").style.display='';
	fin_control_stock(10);
}


function fin_control_stock(cadena){
	//alert(cadena);
	selec=document.getElementById('txt_cantidad');
  while (selec.hasChildNodes()) {
         selec.removeChild(selec.firstChild);
  }
  if(cadena>10){
	 cadena=10; 
	}
 for(i=0;i<=cadena;i++) {
	var nodo_texto = document .createTextNode(i);// nombre
    var nuevo_option = document.createElement('option');
	nuevo_option.appendChild(nodo_texto);
    selec.appendChild(nuevo_option);
	nuevo_option.setAttribute("value",i);//valor
 }
 
 
	//Si cadena = 1 significa stock insuficiente
	if(cadena=="1"){
		//muestra el mensaje y esconde el campo de cantidad
/*		val=document.getElementById("msj_stock_hidden").value;
		document.getElementById("msj_stock").style.display='';
		document.getElementById("msj_stock").innerHTML=val;
		document.getElementById("campos_Q_prix").style.display='none';	
		document.getElementById("btn_validar_off").style.display='';
	    document.getElementById("btn_validar_on").style.display='none';*/
	}else{
		//si el producto tiene stock se muestra el campo para ingresar la cantidad
		/*document.getElementById("msj_stock").style.display='none';
		document.getElementById("campos_Q_prix").style.display='';	*/	
	}
}

function metodos_envio(pago,region,lang,pais,cpostal)
{
  cadena=pago+","+region+","+lang+","+pais+","+cpostal;
  document.frm_inscripcion.pagosx.value=pago;
  jsrsExecute("./include/metodos_envio.php",fin_metodo_envio,"confirmar",cadena);
}

function fin_metodo_envio(cadena)
{
 cadena = cadena.split('-');
 document.frm_inscripcion.envios.value = cadena[0];
 document.frm_inscripcion.cantenvios.value = cadena[1];
}

function metodos_envio2(pago,region,lang,pais,cpostal)
{
	cadena=pago+","+region+","+lang+","+pais+","+cpostal;
	document.frm_inscripcion.pagosx.value=pago;
	jsrsExecute("./include/metodos_envio.php",fin_metodo_envio2,"confirmar",cadena);
}

function fin_metodo_envio2(cadena)
{
 cadena = cadena.split('-');
 
 document.frm_inscripcion.envios.value = cadena[0];
 document.frm_inscripcion.cantenvios.value = cadena[1];
 verificar_promocion();
}

function verificar_partner(){
	cadena=document.frm_inscripcion.txt_codepartner.value;
  	if(cadena){
		jsrsExecute("./include/verificar_partner.php",fin_verificar,"confirmar",cadena);
	}else{
		fin_verificar("y");
	}
}

function fin_verificar(cadena){
	if(cadena=="y"){
		form=document.frm_inscripcion;
		email = form.txt_email.value;
		bmail = form.txt_bmail.value;
		cadena=email+","+bmail;
		jsrsExecute("./include/verificar_mail.php",fin_mail,"confirmar",cadena);
	}else{
		alert(document.frm_inscripcion.alert_codepartner.value);	 
	}
}
function fin_mail(cadena){
	if(cadena=="y"){
		form=document.frm_inscripcion;
		if(validar_inscripcion()){
			form.submit();
		}
	}else{
		alert(document.frm_inscripcion.alert_exemail.value);	 
	}
}
function verificar_inscripcion(){
	
	form=document.frm_inscripcion;
	partner =  form.txt_codepartner.value;
	login = form.txt_login.value;
	mail = form.txt_email.value;
	cpostal = form.txt_codigopostal.value;
	pais = form.slt_pais.value;
	cadena=partner+","+login+","+mail+","+cpostal+","+pais;
	//alert(cadena);
	jsrsExecute("./include/verificar_inscripcion.php",fin_verificar_inscripcion,"confirmar",cadena);
}
function fin_verificar_inscripcion(param){
	form=document.frm_inscripcion;
	//alert(param);
	if(param==4){//todo ok
		if(validar_inscripcion()) {
			form.submit();
		}
	}else{
		
		if(param==1){//partner inexistente
			alert(INSC_ALERT_CODE_PARTENEIRE);
		}else if(param==2){//login existente
			alert(INSC_ALERT_LOGIN_EXISTE);
		}else if(param==3){//3.-email existente
			alert(INSC_ALERT_MAIL_EXISTE);
		}else{
			alert("Code postal incorrect!");
			form.txt_codigopostal.select();
		}
	}
}

/////////////////////////////////////////////////
function validaForm(ruta){
//if(ruta=="contacto")ruta=document.frm_amigo;
//alert(ruta);
var propControl = new Array();
debecontar=0;
contar=0;
validar=0;
vacios=0;
	for(var i=0; i<ruta.elements.length; i++){
		controlAct=ruta.elements[i];
		if(ruta.elements[i].title.indexOf("*")!=-1){//si existe * entonces valida datos del control actual
			propControl = ruta.elements[i].title.split("*");
			//alert(propControl[1]);
			if(propControl[1].indexOf("r")!= -1){//si es diferente de -1 entonces es un control requerido
				if(controlAct.value=="" || controlAct.value=="0"){
					alert("Le champ \""+propControl[0]+"\" est obligatoire");
					controlAct.focus();
					return false;
					break;
				}
			}
			if(propControl[1].indexOf("m")!= -1){//si es diferente de -1 entonces se debe validar el email
				if(emailCheck(controlAct.value)==0){
					alert("Votre email n'est pas valide");
					controlAct.focus();
					return false;
					break;
				}
			}if(propControl[1].indexOf("c")!= -1){
				debecontar=1;
				contar=contar+1;
				if(controlAct.value==""){
					vacios=vacios+1;
					if(contar==1){
						kontrol=controlAct;
						nombreKontrol=propControl[0];
					}
				}				
			}			
			if(propControl[1].indexOf("f")!= -1){
				if(checkDecimals(controlAct)==0){
					alert("Le champ "+propControl[0]+" ne doit pas contenir de caractères alphanumériques");
					controlAct.focus();
					controlAct.select();
					return false;
					break;
				}else{
					num=roundOff(controlAct.value, 2);
					//alert(num);
				}				
			}
			if(propControl[1].indexOf("p1")!= -1){//hay un "campo password"
				password1=controlAct.value;
			}
			if(propControl[1].indexOf("p2")!= -1){//hay un campo "repetir password"
				password2=controlAct.value;
				validar=1;
				ctrlRep=controlAct;
			}
		}
	}
	if(validar==1){
		if(password1!=password2){
			alert('Vous n\’avez pas retapé correctement votre mot de passe');
			ctrlRep.focus();
			ctrlRep.select();
			return false;
		}
	}
	if(debecontar==1){
		if(contar==vacios){
			alert('Les champs "'+nombreKontrol+'" ne peuvent être vides ');
			kontrol.focus();
			return false;
		}
	}
}

function roundOff(value, precision){
value = "" + value //convert value to string
precision = parseInt(precision);
var whole = "" + Math.round(value * Math.pow(10, precision));
var decPoint = whole.length - precision;

	if(decPoint != 0){
		result = whole.substring(0, decPoint);
		result += ".";
		result += whole.substring(decPoint, whole.length);
	}else{
		result = whole;
	}
	return result;
}


function checkDecimals(fieldName) {
decallowed = 2;  // cuantos decimales se desea
fieldValue=fieldName.value;
	if(fieldValue.length>=1){
		if (isNaN(fieldValue) || fieldValue == "") {
			/*alert("OJO! No has introducido un numero. Vuelve a intentarlo");
			fieldName.select();
			fieldName.focus();*/
			return 0;
		}
		else {
			if (fieldValue.indexOf('.') == -1) 
				fieldValue += ".";
			dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
	
			if (dectext.length > decallowed){
				/*alert ("OJO!! Introduce un numero con " + decallowed + " decimales.  Intentalo de nuevo.");
				fieldName.select();
				fieldName.focus();*/
				return 0;
	      	}else {
			//alert ("OK!! Numero correcto.");
			return 1;
	      	}
		}
	}else{
		return 1;
	}
}


function emailCheck (emailStr) {
if(emailStr.length>=1){
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) {
	return 0;
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
	return 0;
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
		return 0;
	    }
    }
	return 1;
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	return 0;
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   return 0;
}

if (len<2) {
   return 0;
}

}else{
	return 1;
}

}

//**************************************formateo de textos**********************


function validar(e) { // 1
    tecla = (document.all) ? e.keyCode : e.which; // 2
    if (tecla==8) return true; // 3
    patron = /\d/; // 4
    te = String.fromCharCode(tecla); // 5
    return patron.test(te); // 6
} 

