/// SCRIPT CREADO EN ALTIMEA
var loadstatustext="En train de charger"
onload=function() 
{

	divTransparente=document.getElementById("transparencia");
	divMensaje=document.getElementById("transparenciaMensaje");
	preCarga("./images/ok.gif", "./images/loading.gif", "./images/error.gif");
}

function preCarga()
{
	imagenes=new Array();
	for(i=0; i<arguments.length; i++)
	{
		imagenes[i]=document.createElement("img");
		imagenes[i].src=arguments[i];
	}
}
/// MENSAJE DE TRANSPARENCIA

function ocultaMensaje()
{
	divTransparente.style.display="none";
}

function muestraMensaje(mensaje,img)
{
	//img=loading,error,ok,help
	switch(img) {
	  case 'error' :{ image='<img src="'+TEMPLATE_DIR+'/images/error.gif" alt=""><br>'; break; }
	  case 'ok' : { image='<img src="'+TEMPLATE_DIR+'/images/ok.gif" alt=""><br>'; break; }
	  case 'help' :{ image='<img src="'+TEMPLATE_DIR+'/images/help.gif" alt=""><br>'; break; }
	  case 'loading' : { image='<img src="'+TEMPLATE_DIR+'/images/loading.gif" alt=""><br>'; break; }
	  default: { image='<img src="'+TEMPLATE_DIR+'/images/loading.gif" alt=""><br>'; }
	}
	divTransparente=document.getElementById("transparencia");
	divMensaje=document.getElementById("transparenciaMensaje");
	
	divMensaje.innerHTML=image+mensaje;
	
	divTransparente.style.display="block";
}


function createREQ() {
try {
     req = new XMLHttpRequest(); /* p.e. Firefox */
     } catch(err1) {
       try {
       req = new ActiveXObject('Msxml2.XMLHTTP'); /* algunas versiones IE */
       } catch (err2) {
         try {
         req = new ActiveXObject("Microsoft.XMLHTTP"); /* algunas versiones IE */
         } catch (err3) {
          req = false;
         }
       }
     }
     return req;
}
function requestGET(url, query, req) {
myRand=parseInt(Math.random()*99999999);
req.open("GET",url+'?'+'query'+'&rand='+myRand,true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url,true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//alert(query);
req.send(query);
}
function doCallback(callback,item) {
eval(callback + '(item)');
}

function doAjax(url,query,callback,reqtype,getxml) {
// crea la instancia del objeto XMLHTTPRequest

//document.getElementById('preload').innerHTML=loadstatustext
var myreq = createREQ();
myreq.onreadystatechange = function() {
if(myreq.readyState == 4) {
   if(myreq.status == 200) {
      var item = myreq.responseText;
      if(getxml==1) {
         item = myreq.responseXML;
      }
      doCallback(callback, item);
    }
  }
}
if(reqtype=='post') {
requestPOST(url,query,myreq);
} else {
requestGET(url,query,myreq);
}
}
//############################### he aqui comienza el tabs */
var peticion = false; 
function ObtenerDatos(datos,divID,query) { 
var peticion = createREQ();
if(peticion) {
     var obj = document.getElementById(divID); 
	 obj.innerHTML =loadstatustext;    
     peticion.onreadystatechange = function()  { 
          if (peticion.readyState == 4) { 
               obj.innerHTML = peticion.responseText; 
          } 
     }
	 //llamando la funcion para hacer la petion del GET
	 requestPOST(datos,query,peticion);
}
}

function CambiarEstilo(id) {
	var elementosMenu = getElementsByClassName(document, "li", "activo");
	for (k = 0; k< elementosMenu.length; k++) {
	elementosMenu[k].className = "inactivo";
	}
	var identity=document.getElementById(id);
	identity.className="activo";
}


function getElementsByClassName(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];      
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }   
    }
    return (arrReturnElements)
}

//########################################### MESCLANDO VALIDATOR CON  AJAX
function validaFormulario(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 == "") {
			return 0;
		}
		else {
			if (fieldValue.indexOf('.') == -1) 
				fieldValue += ".";
			dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
	
			if (dectext.length > decallowed){
				return 0;
	      	}else {
			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;
}

}



function listado_busqueda(xml_pueblos){
 ocultaMensaje();
 document.getElementById('paginacion').innerHTML=xml_pueblos;
}
function Pagina(nropagina){
	//alert(nropagina);
		/*dato=document.frmbusqueda;
		cadenaFormulario=enviarFormulario(dato);*/
		muestraMensaje(texto,'loading');
		doAjax('index.php'+nropagina,nropagina ,'listado_busqueda','post','0');
}
function listado_Paginaimages(xml_pueblos){
 document.getElementById('paginacion').innerHTML=xml_pueblos;
}
function Paginaimages(nropagina){
		doAjax('index.php'+nropagina,nropagina ,'listado_Paginaimages','post','0');
}
function Paginanext(id){
	nropagina=document.getElementById('pagina').value;
	Paginaimages('?content=detail&id='+ id +'&next='+ nropagina +'');
	
}
///validar 
function validar_tipos(val){
	ruta=document.frm_contact;
	id=val.value
	for(var i=0; i<ruta.elements.length; i++){
		controlAct=ruta.elements[i];
		if(ruta.elements[i].title.indexOf("tipos")!=-1){//si existe * entonces valida datos del control actual
		
			controlAct.disabled=1;
			
		}
	}
	document.getElementById(id).disabled =0;
}
//volcando asociados
function dependiente_user(xml_pueblos)
{
  selec=document.getElementById('asociado');
  while (selec.hasChildNodes()) {
         selec.removeChild(selec.firstChild);
      }
 var numero=xml_pueblos.getElementsByTagName("pueblo").length;;
 for(i=0;i<numero;i++) {
 	var nombre_pueblo = xml_pueblos.getElementsByTagName("pueblo")[i].childNodes[1].firstChild.nodeValue;
	 var id_pueblo = xml_pueblos.getElementsByTagName("pueblo")[i].childNodes[0].firstChild.nodeValue;
	var nodo_texto = document .createTextNode(nombre_pueblo);
    var nuevo_option = document.createElement('option');
	nuevo_option.appendChild(nodo_texto);
    selec.appendChild(nuevo_option);
	nuevo_option.setAttribute("value",id_pueblo);
 }
  // Eliminamos todos los options del select de los pueblos que pudieran ver.
  selec2=document.getElementById('disponible');
  while (selec2.hasChildNodes()){ selec2.removeChild(selec2.firstChild);}
 var numero2=xml_pueblos.getElementsByTagName("pueblo2").length;;
 for(ii=0;ii<numero2;ii++) {
 	var nombre_pueblo2 = xml_pueblos.getElementsByTagName("pueblo2")[ii].childNodes[1].firstChild.nodeValue;
	 var id_pueblo2 = xml_pueblos.getElementsByTagName("pueblo2")[ii].childNodes[0].firstChild.nodeValue;
	var nodo_texto2 = document .createTextNode(nombre_pueblo2);
    var nuevo_option2 = document.createElement('option');
	nuevo_option2.appendChild(nodo_texto2);
    selec2.appendChild(nuevo_option2);
	nuevo_option2.setAttribute("value",id_pueblo2);
 }
 document.getElementById('preload').innerHTML="";
}
function llamada_user(volcar,idproducto,lista){
idcategoria=document.formu.cblista.value;
total=document.getElementById(lista).length;
j=0;cadena_id="";
for(i=0;i<document.getElementById(lista).length;i++){
		if(document.getElementById(lista).options[i].selected==true){
			sep=(j==0?"":"*");
			cadena_id+=sep+document.getElementById(lista).options[i].value;
			j++;
		}
}
	if(j!=0)
	 doAjax('dependientes_producto.php','id=' + cadena_id + '& idproducto=' + idproducto + '& volcar=' + volcar + '& idcategoria=' + idcategoria,'dependiente_user','post','1');
}
/////  mostrar colores 
function responde_ajax_tallas(xml_pueblos)
{	
 limpiar_lista('taille_slt');
 var numero=xml_pueblos.getElementsByTagName("pueblo").length;;
 for(i=0;i<numero;i++) {
 var nombre_pueblo = xml_pueblos.getElementsByTagName("pueblo")[i].childNodes[1].firstChild.nodeValue;
 var id_pueblo = xml_pueblos.getElementsByTagName("pueblo")[i].childNodes[0].firstChild.nodeValue;
 var nodo_texto = document .createTextNode(nombre_pueblo);
 var nuevo_option = document.createElement('option');
	nuevo_option.appendChild(nodo_texto);
    selec.appendChild(nuevo_option);
	nuevo_option.setAttribute("value",id_pueblo);
 }
 ocultaMensaje();
}
function ajax_tallas(color,idproducto,idioma,nulltxt){
	limpiar_lista('txt_cantidad');
	if(color){
	 muestraMensaje(texto,'loading');
	 doAjax('./include/ajax_xml_tallas.php','color=' + color + '& idproducto=' + idproducto + '&idioma=' + idioma +'&nulltxt='+nulltxt,'responde_ajax_tallas','post','1');
	}
}
function limpiar_lista(id_campo){
  selec=document.getElementById(id_campo);
  while (selec.hasChildNodes()) {
         selec.removeChild(selec.firstChild);
   }
}
//// FUNCION CONTROLA LA CANTIDAD DE LOS PRODUSTOS 
function responde_ajax_cantidad(xml_pueblos)
{	
  valor=0;
 limpiar_lista('txt_cantidad');
 var numero=xml_pueblos.getElementsByTagName("pueblo").length;;
 for(i=0;i<numero;i++) {
 var valor = xml_pueblos.getElementsByTagName("pueblo")[i].childNodes[0].firstChild.nodeValue;
 }
 listar_cantidad(valor);
 ocultaMensaje();
}
function ajax_cantidad(idproducto,showstock,idioma,carid){
	muestraMensaje(texto,'loading');
	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;
		cadena='idproducto=' + idproducto + '& idTalla=' + idTalla + '&idColor=' + idColor +'&showstock=' + showstock +'&idioma=' + idioma +'&carid=' + carid;
		
		if(idproducto)
		 doAjax('./include/ajax_xml_cantidad.php',cadena,'responde_ajax_cantidad','post','1');
	}else{
		
		listar_cantidad(10); 
		ocultaMensaje();
	}
}
function listar_cantidad(cadena){
 selec=document.getElementById('txt_cantidad');
  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
 }
}
function validar_carro(null_txt){
	form=document.frm_carro;
	if ($('color_slt').value>0 && $('taille_slt').value>0  && $('txt_cantidad').value>0 ){
		form.action='./include/all_process.php'
		form.submit();
	}else{
		 message(null_txt,'error',2000,1);
	}
}
function create_txt_pago(carid){
	get='process_content=create_txt_pago&carid=' + carid ;
	if(carid){
	  doAjax('./include/all_process.php',get,'responde_create_txt_pago','post','1');	
	}else{
	 return false;
	}
}
function responde_create_txt_pago(responde)
{	
	form=document.frm_inscripcion;	
	var option=radio_button_checker(form);
	if(option==1) {
		document.frm_inscripcion.action="./pago/sample/call_request.php";
	}else{
		document.frm_inscripcion.action="./pago/pago.php";
	}
	document.frm_inscripcion.submit();
}
function end_cart(carid){
///crear txt
create_txt_pago(carid);
///	
}

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;
}
//###############trabajando con las listas  categorias
function llamada_categorias(idproducto){
	idcategoria=document.formu.cblista.value;	
	doAjax('combo_categorias.php','idcategoria=' + idcategoria + '& idproducto=' + idproducto,'dependiente_categorias','post','1');
}
 //aqui se  recupera la informacion  del xml 
 function dependiente_categorias(xml_pueblos)
{
  selec=document.getElementById('disponible');
  while (selec.hasChildNodes()) {
         selec.removeChild(selec.firstChild);
      }
 var numero=xml_pueblos.getElementsByTagName("categoria").length;;
 for(i=0;i<numero;i++) {
 	var nombre_pueblo = xml_pueblos.getElementsByTagName("categoria")[i].childNodes[1].firstChild.nodeValue;
	 var id_pueblo = xml_pueblos.getElementsByTagName("categoria")[i].childNodes[0].firstChild.nodeValue;
	var nodo_texto = document .createTextNode(nombre_pueblo);
    var nuevo_option = document.createElement('option');
	nuevo_option.appendChild(nodo_texto);
    selec.appendChild(nuevo_option);
	nuevo_option.setAttribute("value",id_pueblo);
 }
 document.getElementById('preload').innerHTML="";
}
function message(msg,img,time,get){
	if(get==0){
		ocultaMensaje();
	}else{
		muestraMensaje(msg,img);
		setTimeout("message('','','',0)",time);
	}
}
function recalculer_commandes(userid,carid){
	form=document.frm_inscripcion;
	 if(form.elimDesc.checked==false){
		document.frm_inscripcion.action="index.php?content=recapitulatif&elimDesc="+carid;
	  	document.frm_inscripcion.submit();
		
	}
	partner =  form.txt_codepartner.value;
	get='userid=' + userid + '& carid=' + carid + '& partner=' + partner;
	if(partner!="")
	doAjax('./include/ajax_xml_partner.php',get,'responde_recalculer_commandes','post','1');	
}
function responde_recalculer_commandes(xml)
{	

  var valor = xml.getElementsByTagName("valor")[0].firstChild.nodeValue;
  if(valor==0){
   message(COMM_ALERT_CODE_DESCUENTO,'error',2000,1);
  }else{
	document.frm_inscripcion.action="index.php?content=recapitulatif";
   document.frm_inscripcion.submit();
  }
}
function funtion_descuento(carid){
	form=document.frm_inscripcion;
	if(form.elimDesc.checked==true){
		document.getElementById('txt_codepartner').disabled=false;
	}else{
		document.getElementById('txt_codepartner').disabled=true;
		document.getElementById('txt_codepartner').value="";

	}
}
/////////////////////////////////////////////////////////funciones para CBL

function listado_tarifs(xml_pueblos){
ocultaMensaje();
 document.getElementById('paginacion').innerHTML=xml_pueblos;
}
function tarifs_cbl(){
		muestraMensaje(texto,'loading');
		get='content=tarifs&id='+ document.getElementById('listat').value + '&ajax=1';
		doAjax('index.php?'+get,get ,'listado_tarifs','post','0');
}
///validar 
function check_all(form){	
	for (i=0;i<document.getElementById(form).elements.length;i++)
		if(document.getElementById(form).elements[i].type == "checkbox")	
			document.getElementById(form).elements[i].checked=1;
}
function uncheck_all(form){	
	for (i=0;i<document.getElementById(form).elements.length;i++)
		if(document.getElementById(form).elements[i].type == "checkbox")	
			document.getElementById(form).elements[i].checked=0;
}