/// SCRIPT CREADO EN ALTIMEA
var loadstatustext="<img src='./images/loading1.gif' />"
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)
}
//###############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="";
}
//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)
	//alert('id=' + cadena_id + '& idproducto=' + idproducto + '& volcar=' + volcar);
 doAjax('dependientes_producto.php','id=' + cadena_id + '& idproducto=' + idproducto + '& volcar=' + volcar + '& idcategoria=' + idcategoria,'dependiente_user','post','1');
}
//############################## ASOCIAR PRODUCTOS CON USUARIOS
function dependiente(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(volcar,idproducto,lista){
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.php','id=' + cadena_id + '& idproducto=' + idproducto + '& volcar=' + volcar,'dependiente','post','1');
}
//########################################### 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;
}

}
//########################################### FIN DEL SCRIPT MESCLANDO VALIDATOR CON  AJAX

///validacion  de formulario de modificacion de usuario
/*function cambiaColor(){
    var i
    for (i=0;i<document.fcolores.colorin.length;i++){
       if (document.fcolores.colorin[i].checked)
          break;
    }
    document.bgColor = document.fcolores.colorin[i].value
}*/
/*	ver el OPTION ACTIVADO 
	 var i
    for (i=0;i<ruta.optActivar.length;i++){
       if (ruta.optActivar[i].checked==true)
	   	optActivar=ruta.optActivar[i].value;
    }*/
function enviardatos_newletter(ruta) {
	valor=validaFormulario(ruta);
	if (valor===false){
		return false;
	}else{
	cadenaFormulario=enviarFormulario(ruta);
	doAjax('./include/'+document.getElementById('page').value+'.php',cadenaFormulario ,'retornadatos_newletter','post','0');
	}
}
function retornadatos_newletter(xml_pueblos){
	alert("Votre inscription à la newsletter Visioscène s'est effectuée avec succès");
 //var numero=xml_pueblos.getElementsByTagName("login").length;;
//alert('holas');
/* if(numero>0){
  retor=xml_pueblos.getElementsByTagName('login').item(0).firstChild.nodeValue;
  alert("Votre inscription &agrave; la newsletter Visiosc&egrave;ne s'est effectu&eacute;e avec succ&egrave;s" + retor);
 }*/
 document.getElementById('preload').innerHTML="";
}

function enviardatos_usuario(ruta) {
	valor=validaFormulario(ruta);
	if (valor===false){
		return false;
	}else{
	cadenaFormulario=enviarFormulario(ruta);
	doAjax('./include/'+document.getElementById('page').value+'.php',cadenaFormulario ,'retornadatos_mensaje','post','0');
	}
}
//volcando alertas
function retornadatos_mensaje(xml_pueblos){
 document.getElementById('preload').innerHTML=xml_pueblos;
 alert("Votre inscription à la newsletter Visioscène s'est effectuée avec succès");
}
function retornadatos_usuarios(xml_pueblos){
var valor = new Array();
 var numero1=xml_pueblos.getElementsByTagName("login").length;;
 var numero2=xml_pueblos.getElementsByTagName("email").length;;
 if(numero1>0){
  document.getElementById('login').innerHTML='&nbsp; &nbsp;' + xml_pueblos.getElementsByTagName('login').item(0).firstChild.nodeValue;
 } if(numero2>0){
 document.getElementById('email').innerHTML=' &nbsp;&nbsp;' +  xml_pueblos.getElementsByTagName('email').item(0).firstChild.nodeValue;
 }
 document.getElementById('preload').innerHTML="";
}
function enviarFormulario(Formulario){
    var longitudFormulario = Formulario.elements.length;
    var cadenaFormulario = ""
    var sepCampos
    sepCampos = ""
    for (var i=0; i <= Formulario.elements.length-1;i++) {
      cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(Formulario.elements[i].value);
      sepCampos="&";
    }
	return cadenaFormulario; 
 }
//  funcion para la paginacion
function verCampos(ruta){
	val=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
				if(controlAct.value!=""){
					val++;
				}
				
			}
		}
	}
	return val;
}
function buscarDato(ruta){
		val=verCampos(ruta);
		if(val>0){
		cadenaFormulario=enviarFormulario(ruta);
		doAjax('./resultado_busqueda.php',cadenaFormulario ,'listado_busqueda','post','0');
		}else{
		alert('Vous devez saisir une région, un code postal, ou choisir une agence pour effectuer votre recherche');
		}
}
function listado_busqueda(xml_pueblos){
 document.getElementById('preload').innerHTML=xml_pueblos;
}
function Pagina(nropagina,dato){
		dato=document.frmbusqueda;
		cadenaFormulario=enviarFormulario(dato);
		doAjax('./'+document.getElementById('page').value+'.php?pag='+nropagina,cadenaFormulario ,'listado_busqueda','post','0');
}

