/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
VarienForm = Class.create();
VarienForm.prototype = {
    initialize: function(formId, firstFieldFocus){
        this.form       = $(formId);
        if (!this.form) {
            return;
        }
        this.cache      = $A();
        this.currLoader = false;
        this.currDataIndex = false;
        this.validator  = new Validation(this.form);
        this.elementFocus   = this.elementOnFocus.bindAsEventListener(this);
        this.elementBlur    = this.elementOnBlur.bindAsEventListener(this);
        this.childLoader    = this.onChangeChildLoad.bindAsEventListener(this);
        this.highlightClass = 'highlight';
        this.extraChildParams = '';
        this.firstFieldFocus= firstFieldFocus || false;
        this.bindElements();
        if(this.firstFieldFocus){
            try{
                Form.Element.focus(Form.findFirstElement(this.form))
            }
            catch(e){}
        }
    },

    submit : function(url){
        if(this.validator && this.validator.validate()){
             this.form.submit();
        }
        return false;
    },

    bindElements:function (){
        var elements = Form.getElements(this.form);
        for (var row in elements) {
            if (elements[row].id) {
                Event.observe(elements[row],'focus',this.elementFocus);
                Event.observe(elements[row],'blur',this.elementBlur);
            }
        }
    },

    elementOnFocus: function(event){
        var element = Event.findElement(event, 'fieldset');
        if(element && element.className){
            Element.addClassName(element, this.highlightClass);
        }
    },

    elementOnBlur: function(event){
        var element = Event.findElement(event, 'fieldset');
        if(element && element.className){
            Element.removeClassName(element, this.highlightClass);
        }
    },

    setElementsRelation: function(parent, child, dataUrl, first){
        if (parent=$(parent)) {
            // TODO: array of relation and caching
            if (!this.cache[parent.id]){
                this.cache[parent.id] = $A();
                this.cache[parent.id]['child']     = child;
                this.cache[parent.id]['dataUrl']   = dataUrl;
                this.cache[parent.id]['data']      = $A();
                this.cache[parent.id]['first']      = first || false;
            }
            Event.observe(parent,'change',this.childLoader);
        }
    },

    onChangeChildLoad: function(event){
        element = Event.element(event);
        this.elementChildLoad(element);
    },

    elementChildLoad: function(element, callback){
        this.callback = callback || false;
        if (element.value) {
            this.currLoader = element.id;
            this.currDataIndex = element.value;
            if (this.cache[element.id]['data'][element.value]) {
                this.setDataToChild(this.cache[element.id]['data'][element.value]);
            }
            else{
                new Ajax.Request(this.cache[this.currLoader]['dataUrl'],{
                        method: 'post',
                        parameters: {"parent":element.value},
                        onComplete: this.reloadChildren.bind(this)
                });
            }
        }
    },

    reloadChildren: function(transport){
        var data = eval('(' + transport.responseText + ')');
        this.cache[this.currLoader]['data'][this.currDataIndex] = data;
        this.setDataToChild(data);
    },

    setDataToChild: function(data){
        if (data.length) {
            var child = $(this.cache[this.currLoader]['child']);
            if (child){
                var html = '<select name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
                if(this.cache[this.currLoader]['first']){
                    html+= '<option value="">'+this.cache[this.currLoader]['first']+'</option>';
                }
                for (var i in data){
                    if(data[i].value) {
                        html+= '<option value="'+data[i].value+'"';
                        if(child.value && (child.value == data[i].value || child.value == data[i].label)){
                            html+= ' selected';
                        }
                        html+='>'+data[i].label+'</option>';
                    }
                }
                html+= '</select>';
                Element.insert(child, {before: html});
                Element.remove(child);
            }
        }
        else{
            var child = $(this.cache[this.currLoader]['child']);
            if (child){
                var html = '<input type="text" name="'+child.name+'" id="'+child.id+'" class="'+child.className+'" title="'+child.title+'" '+this.extraChildParams+'>';
                Element.insert(child, {before: html});
                Element.remove(child);
            }
        }

        this.bindElements();
        if (this.callback) {
            this.callback();
        }
    }
}


PaisUpdater = Class.create();
PaisUpdater.prototype={
	
	initialize:function(barrioEl,RegionEl,CityEl,municipios)
	{
		this.BarrioEl=$(barrioEl);
		this.RegionEl=$(RegionEl);
		this.CityEl=$(CityEl);
		this.municipios=municipios;
		
		if (this.CityEl.options.length<=1) {
            this.update();
        }
        
		Event.observe(this.RegionEl, 'change', this.update.bind(this));
	},
	
	update:function()
	{	
		def = this.CityEl.getAttribute('defaultValue');
        
		if(this.CityEl!=null)
			this.CityEl.options.length = 1; // para reiniciar el select de ciudades
		
 		if(this.BarrioEl!=null)
			this.BarrioEl.options.length = 1; // para reiniciar el select de barrios
		//alert(this.municipios[2]["region_id"]);
		for(k=0;k<this.municipios.length;k++)
		{
		    if(this.municipios[k]["region_id"]==this.RegionEl.value)
		    {
				option = document.createElement('OPTION');
		       // option.value = this.municipios[k]["municipio"]+" ("+this.municipios[k]["id_dane"]+")";
		        option.value = this.municipios[k]["id_dane"];
		        option.text = this.municipios[k]["municipio"];
		        if(def==option.value)
		        	option.selected=true;
		        
		        if (this.CityEl.options.add) {
		            this.CityEl.options.add(option);
		        } else {
		            this.CityEl.appendChild(option);
		        }
    		}
  		}
  		if(!def)
  			this.CityEl.selectedValue=def;
	//	var url = 'myscript.php';
//		var pars = 'func=updateCities&regionId='+this.RegionEl.value;
//		var target = 'output-div';	
//		var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars});	
	}
	
	
}



BarrioUpdater = Class.create();
BarrioUpdater.prototype={
	
	initialize:function(postcodeEl,CityEl,BarrioEl,barrios)
	{
		this.postcodeEl=$(postcodeEl);
		this.CityEl=$(CityEl);
		this.BarrioEl=$(BarrioEl);
		this.barrios=barrios;
		
		if (this.BarrioEl.options.length<=1) {
            this.update();
        }
        
		Event.observe(this.CityEl, 'change', this.update.bind(this));
	},
	
	update:function()
	{	
		def = this.BarrioEl.getAttribute('defaultValue');
        
		if(this.postcodeEl!=null)  // para que postcode tenga el valor de la ciudad, para la validación de fletes
			this.postcodeEl.value=this.CityEl.value;
		
		
		if(this.BarrioEl!=null){
		this.BarrioEl.options.length = 1; // para reiniciar el select de ciudades
		}
		for(k=0;k<this.barrios.length;k++)
		{
		    if(this.barrios[k]["municipio_id"]==this.CityEl.value)
		    {
				option = document.createElement('OPTION');
		       // option.value = this.municipios[k]["municipio"]+" ("+this.municipios[k]["id_dane"]+")";
		        option.value = this.barrios[k]["barrio_id"];
		        option.text = this.barrios[k]["descripcion"];
		        if(def==option.value)
		        	option.selected=true;
		        
		        if (this.BarrioEl.options.add) {
		            this.BarrioEl.options.add(option);
		        } else {
		            this.BarrioEl.appendChild(option);
		        }
    		}
  		}
  		if(!def)
  			this.BarrioEl.selectedValue=def;
	//	var url = 'myscript.php';
//		var pars = 'func=updateCities&regionId='+this.RegionEl.value;
//		var target = 'output-div';	
//		var myAjax = new Ajax.Updater(target, url, {method: 'get', parameters: pars});	
	}
	
	
}







RegionUpdater = Class.create();
RegionUpdater.prototype = {
    initialize: function (CityEl,BarrioEl,countryEl, regionTextEl, regionSelectEl, regions, disableAction)
    {
    	this.CityEl=$(CityEl);
		this.BarrioEl=$(BarrioEl);
        this.countryEl = $(countryEl);
        this.regionTextEl = $(regionTextEl);
        this.regionSelectEl = $(regionSelectEl);
        this.regions = regions;

        this.disableAction = (typeof disableAction=='undefined') ? 'hide' : disableAction;

        
        
        this.countryEl.remove(0); // para que no aparezca la opción vacia en el combobox de PAIS!!!
        
        
        
        if (this.regionSelectEl.options.length<=1) {
            this.update();
        }

        Event.observe(this.countryEl, 'change', this.update.bind(this));
    },

    update: function()
    {//alert("ole");
//    	if($("city"))
//    		$("city").options.length = 1; // para reiniciar el select de ciudades
    	if(this.CityEl!=null && this.BarrioEl!=null){
		this.CityEl.options.length = 1; // para reiniciar el select de ciudades
		this.BarrioEl.options.length = 1; // para reiniciar el select de barrios
    	}
    	
        if (this.regions[this.countryEl.value]) {
            var i, option, region, def;

            if (this.regionTextEl) {
                def = this.regionTextEl.value.toLowerCase();
                this.regionTextEl.value = '';
            }
            if (!def) {
                def = this.regionSelectEl.getAttribute('defaultValue');
            }

            this.regionSelectEl.options.length = 1;
            for (regionId in this.regions[this.countryEl.value]) {
                region = this.regions[this.countryEl.value][regionId];

                option = document.createElement('OPTION');
                option.value = regionId;
                option.text = region.name;

                if (this.regionSelectEl.options.add) {
                    this.regionSelectEl.options.add(option);
                } else {
                    this.regionSelectEl.appendChild(option);
                }

                if (regionId==def || region.name.toLowerCase()==def || region.code.toLowerCase()==def) {
                    this.regionSelectEl.value = regionId;
                }
            }

            if (this.disableAction=='hide') {
                if (this.regionTextEl) {
                    this.regionTextEl.style.display = 'none';
                }

                this.regionSelectEl.style.display = '';
            } else if (this.disableAction=='disable') {
                if (this.regionTextEl) {
                    this.regionTextEl.disabled = true;
                }
                this.regionSelectEl.disabled = false;
            }
            this.setMarkDisplay(this.regionSelectEl, true);
        } else {
            if (this.disableAction=='hide') {
                if (this.regionTextEl) {
                    this.regionTextEl.style.display = '';
                }
                this.regionSelectEl.style.display = 'none';
                Validation.reset(this.regionSelectEl);
            } else if (this.disableAction=='disable') {
                if (this.regionTextEl) {
                    this.regionTextEl.disabled = false;
                }
                this.regionSelectEl.disabled = true;
            } else if (this.disableAction=='nullify') {
                this.regionSelectEl.options.length = 1;
                this.regionSelectEl.value = '';
                this.regionSelectEl.selectedIndex = 0;
                this.lastCountryId = '';
            }
            this.setMarkDisplay(this.regionSelectEl, false);
        }
    },

    setMarkDisplay: function(elem, display){
        if(elem.parentNode){
            var marks = Element.select(elem.parentNode, '.required');
            if(marks[0]){
                display ? marks[0].show() : marks[0].hide();
            }
        }
    }
}


//custom functions
// para realizar ciertas validaciones
function checkDigitoValidacion(comboTipoId)
{
	if($("digito_validacion"))
		obj=$("digito_validacion");
	else if($("billing:digito_validacion"))
		obj=$("billing:digito_validacion");
	else if($("shipping:digito_validacion"))
		obj=$("billing:digito_validacion");
	switch(comboTipoId.value)
	{
		case "N":	$("id_digito_validacion").style.display="";
					//$("digito_validacion").value="";
					break;
		case "C":	$("id_digito_validacion").style.display="none";
					obj.value="C";
					break;
		case "U":	$("id_digito_validacion").style.display="none";
					obj.value="C";
					break;					
		case "E":	$("id_digito_validacion").style.display="none";
					obj.value="O";
					break;
		default:	$("id_digito_validacion").style.display="none";
					obj.value="";
					break;										
	}
	return true;
}
function esInteger(e)
{
	var tecla
	var navegador=navigator.appName;

	if(navegador == 'Netscape')
		tecla = e.which;
	else
		tecla = e.keyCode;

	if (tecla > 31 && (tecla < 48 || tecla > 57))
		return false;
	else
		return true;
}
function reuniteFirstNameLastName(prefijo)
{
	if(prefijo)
	{
		var arreglo1=explode(":",prefijo.id);
		tamano=arreglo1.length;
	}
	else
		tamano=0;
	
	if(tamano=="2")
	{
		cc = arreglo1[0]+":"; 
		//alert(cc);
	}
	else
	{
			cc="";
		//	alert('jhon');
	}
	try
	{
		if (cc=="")
		{
			$("firstname").value=$("primer_nombre").value+" "+$("segundo_nombre").value;
			$("lastname").value=$("primer_apellido").value+" "+$("segundo_apellido").value;
		}
		
		if (cc=="billing:")
		{
			$("billing:firstname").value=$("billing:primer_nombre").value+" "+$("billing:segundo_nombre").value;
			$("billing:lastname").value=$("billing:primer_apellido").value+" "+$("billing:segundo_apellido").value;
		}
		if (cc=="shipping:")
		{
			$("shipping:firstname").value=$("shipping:primer_nombre").value+" "+$("shipping:segundo_nombre").value;
			$("shipping:lastname").value=$("shipping:primer_apellido").value+" "+$("shipping:segundo_apellido").value;
		}	
	}
	catch(e){}
	
}

function reuniteFirstNameLastNameOnePage(prefijo)
{
	
	var arreglo1=explode(":",prefijo.id);
	var tamano=arreglo1.length;
	if(tamano=="2")
	{
		cc = arreglo1[0]+":"; 
		
	}
	else
			cc="";
	try
	{
		if (cc=="billing:")
		{
			$("billing:firstname").value=$("billing:primer_nombre").value+" "+$("billing:segundo_nombre").value;
			$("billing:lastname").value=$("billing:primer_apellido").value+" "+$("billing:segundo_apellido").value;
		}
		if (cc=="shipping:")
		{
			$("shipping:firstname").value=$("shipping:primer_nombre").value+" "+$("shipping:segundo_nombre").value;
			$("shipping:lastname").value=$("shipping:primer_apellido").value+" "+$("shipping:segundo_apellido").value;
		}	
	}
	catch(e){}
	
}

/*
FUNCIONES PARA LA VALIDACIÓN DEL NIT... EXTRAÍDA DE UN FORO EN LANEROS.
http://www.laneros.com/archive/index.php/t-71402.html
*/

function zero_fill(i_valor, num_ceros) 
{
	relleno = "";
	i = 1;
	salir = 0;
	while ( ! salir ) 
	{
		total_caracteres = i_valor.length + i;	
		if ( i > num_ceros || total_caracteres > num_ceros )
			salir = 1;
		else
			relleno = relleno + "0";
		i++;
	
	}
	i_valor = relleno + i_valor;
	return i_valor;
}
/*
funcion para el calculo del digito de validación modificada por Jhon Quintero - Gattaca S.A. 2009
NIT: el nombre del campo de texto que contiene el NIT
digitoValidacion: el objeto (campo de texto), en el cual se digita el digito de validación.
*/
function calcularDV(NIT,digitoValidacion) 
{
	var i_rut=$(NIT).value;
	
	if(digitoValidacion.value=="" ||i_rut=="")
	{
		alert("Por favor digite el NIT y el n\u00famero de validaci\u00f3n");
		$(NIT).focus();
		return false;
	}
	var pesos = new Array(71,67,59,53,47,43,41,37,29,23,19,17,13,7,3); 
	rut_fmt = zero_fill(i_rut, 15);
	suma = 0;
	for ( i=0; i<=14; i++ ) 
		suma += rut_fmt.substring(i, i+1) * pesos[i];
	resto = suma % 11;
	if ( resto == 0 || resto == 1 )
		digitov = resto;
	else
		digitov = 11 - resto;
//alert(digitov);		
	if(digitov!=digitoValidacion.value)
	{
		alert("Error, El digito de validaci\u00f3n no corresponde con el NIT ingresado");
		digitoValidacion.value="";
		$(NIT).focus();
	}
	return digitov;
}
function traerClienteWS(identificacionCliente,tipoIdentificacion)
{

	if(trimString(identificacionCliente.value)=="" || trimString(tipoIdentificacion.value)=="")
	{
		return false;
	}
	else // SKU it's defined, let's do the ajax validation
	{
		var cc = identificacionCliente.id;
		
		var arreglo1=explode(":",cc);
		var tamano=arreglo1.length;
		if(tamano=="2")
		{
			cc = arreglo1[0]+":"; 
		//	alert (cc);
		}
		else
			cc="";


            if($('disablingDiv_'))
				$('disablingDiv_').style.display='block';
					
			if(cc=="") {
		    //	$("identificacion").style.background="#3333FF";
		    	$("primer_nombre").disabled=true;
	        	$("segundo_nombre").disabled=true;
	        	$("primer_apellido").disabled=true;
	        	$("segundo_apellido").disabled=true;
	        	$("digito_validacion").disabled=true;
      		}
      		else
      		{
      			ele = document.createElement("identificacion"); 
        		ele.id=cc+"identificacion";
				$(ele.id).disabled=true;

       			eledv = document.createElement("digito_validacion"); 
        		eledv.id=cc+"digito_validacion";
        		$(eledv.id).disabled=true;
        		
				elepn = document.createElement("primer_nombre"); 
        		elepn.id=cc+"primer_nombre";
				$(elepn.id).disabled=true;       	       			
				
				elesn = document.createElement("segundo_nombre"); 
        		elesn.id=cc+"segundo_nombre";
        		$(elesn.id).disabled=true;
        		
	        	elepa = document.createElement("primer_apellido"); 
        		elepa.id=cc+"primer_apellido";
        		$(elepa.id).disabled=true;
        		
	        	elesa = document.createElement("segundo_apellido"); 
        		elesa.id=cc+"segundo_apellido";
        		$(elesa.id).disabled=true;
        		
	        	eledv = document.createElement("digito_validacion"); 
        		eledv.id=cc+"digito_validacion";
        		$(eledv.id).disabled=true;
        		
	        	/*$("id_digito_validacion").disabled=true;
	        	$("primer_nombre").disabled=true;
	        	$("segundo_nombre").disabled=true;
	        	$("primer_apellido").disabled=true;
	        	$("segundo_apellido").disabled=true;*/
	        	
      		}
			
		new Ajax.Request( "?customAjax=true", {
		    method: "get",
		    parameters: {
		        idCliente : identificacionCliente.value,
		        func: "traerClienteWS"
		    },
		    //onLoading:function(){
//			
//			
//		    },

		    onFailure:function(){

				if($('disablingDiv_'))
		    		$('disablingDiv_').style.display='none';
		    		
		    	if(cc=="") {
		    	  	$("identificacion").style.background="#FFFFFF";
			        $("primer_nombre").disabled=false;
		        	$("segundo_nombre").disabled=false;
		        	$("primer_apellido").disabled=false;
		        	$("segundo_apellido").disabled=false;
		        	$("digito_validacion").disabled=false;
		        	$("primer_nombre").focus();
	        	}
	        	else
				{
					$(ele.id).style.background="#FFFFFF";
	        		$(ele.id).disabled=false;
					$(elepn.id).disabled=false;
	        		$(elesn.id).disabled=false;
	        		$(elepa.id).disabled=false;
		        	$(elesa.id).disabled=false;
		        	$(eledv.id).disabled=false;
		        	//$("id_digito_validacion").disabled=false;
	        		//$("primer_nombre").focus();
    			}
		    },
		    onSuccess: function( transport ) {
		    	
				if($('disablingDiv_'))
					$('disablingDiv_').style.display='none';
		    	
		        if(transport.responseText!="")
		        {
		        if(cc=="") {
		        //	$("identificacion").style.background="#FFFFFF";
			        $("primer_nombre").disabled=false;
		        	$("segundo_nombre").disabled=false;
		        	$("primer_apellido").disabled=false;
		        	$("segundo_apellido").disabled=false;
		        	$("digito_validacion").disabled=false;
	        	
	        	}
	        	else
				{
					$(ele.id).style.background="#FFFFFF";
					$(ele.id).disabled=false;
	        		$(elepn.id).disabled=false;
	        		$(elesn.id).disabled=false;
	        		$(elepa.id).disabled=false;
		        	$(elesa.id).disabled=false;
		        	$(eledv.id).disabled=false;
		        	//$("id_digito_validacion").disabled=false;
		        /*	$("primer_nombre").disabled=false;
		        	$("segundo_nombre").disabled=false;
		        	$("primer_apellido").disabled=false;
		        	$("segundo_apellido").disabled=false;
		        	$(eledv.id).disable=false;*/
  				}
		        	
		          	if(transport.responseText!="0")
		        	{
		        	   	var arregloNuevo=explode(",",transport.responseText);
		        	   	if(cc=="") {
				        	$("primer_nombre").value=arregloNuevo[0];
				        	$("segundo_nombre").value=arregloNuevo[1];
				        	$("primer_apellido").value=arregloNuevo[2];
				        	$("segundo_apellido").value=arregloNuevo[3];
				        	$("digito_validacion").value=arregloNuevo[4];
				        	$("primer_nombre").focus();
			        	}
			        	else
						{
		  					
        					$(elepn.id).value=arregloNuevo[0];
							$(elesn.id).value=arregloNuevo[1];
        					$(elepa.id).value=arregloNuevo[2];
        					$(elesa.id).value=arregloNuevo[3];
        					$(eledv.id).value=arregloNuevo[4];  
        				/*	$("primer_nombre").value=arregloNuevo[0];
				        	$("segundo_nombre").value=arregloNuevo[1];
				        	$("primer_apellido").value=arregloNuevo[2];
				        	$("segundo_apellido").value=arregloNuevo[3];
        					$(eledv.id).arregloNuevo[4];*/
        					//$("digito_validacion").value=arregloNuevo[4];
						}
			        
		        	}
		        	else
		        		$("primer_nombre").focus();
		        	
		        }
			//	new Insertion.Bottom( $$("body")[0], transport.responseText );
		    }
		}); 	
	}
}

function traerTipoGeo(codigoCiudad,identificador)
{
	if(identificador!="")
		id=identificador+":georef";
	else
		id="georef";
	if(trimString(codigoCiudad)=="")
	{
		$(id).value="0";
		return true;
	}
	
	new Ajax.Request( "?customAjax=true", {
		    method: "get",
		    parameters: {
				codigoDaneCiudad: codigoCiudad,
		        func: "traerTipoGeo"
		    },	
		onLoading:function(){},
		onFailure:function(){},
		onSuccess:function(transport)
		{
			$(id).value=trimString(transport.responseText);
			//new Insertion.Bottom( $$("body")[0], trimString(transport.responseText));	
			return true;
		}
	});
		
}

function traerDireccionWS(telefono ,codigoCiudad, direccion, georef)
{

	if(codigoCiudad.value =="" || codigoCiudad.value=="" || georef=="")
	{
		return false;
	}
	else // SKU it's defined, let's do the ajax validation
	{
		var identificador = direccion.id;
		
		var arreglo1=explode(":",identificador);
		var tamano=arreglo1.length;
		//alert(arreglo1.length);
		if(tamano=="2")
		{
				identificador = arreglo1[0]+":";
				//alert (identificador);
		}
		else
			identificador="";


	   if($('disablingDiv_')){
			$('disablingDiv_').style.display='block';
		}
		if($('disablingDiv_2')){
			$('disablingDiv_2').style.display='block';
		}
		
		if(identificador=="") {
	    	$("street_1").disabled=true;
	    	$("direccion").disabled=true;
           	$("barrio").disabled=true;
        	$("coordenadax").disabled=true;
        	$("coordenaday").disabled=true;
    		$("direccion_alterna").disabled=true;
    		
    		$("country").disabled=true;
			$("direccion_alterna").disabled=true;
    		$("region_id").disabled=true;
    		$("city").disabled=true;
    		$("telephone").disabled=true;
    		
		}
		else
		{//alert("v");
			ele= document.createElement("street1"); 
			ele.id=identificador+"street1";
			$(ele.id).disabled=true;
//      				alert(ele.id);
			
			eledir = document.createElement("direccion"); 
			eledir.id=identificador+"direccion";
			$(eledir.id).disabled=true;
			
			elebarr = document.createElement("barrio"); 
			elebarr.id=identificador+"barrio";
			$(elebarr.id).disabled=true;
			   					
			elebarr1 = document.createElement("barrio1"); 
			elebarr1.id=identificador+"barrio1";
			$(elebarr1.id).disabled=true;
			
			elecorx = document.createElement("coordenadax"); 
			elecorx.id=identificador+"coordenadax";
			
			
			elecory = document.createElement("coordenaday"); 
			elecory.id=identificador+"coordenaday";
			
			eledirA = document.createElement("direccion_alterna"); 
			eledirA.id=identificador+"direccion_alterna";
		
	  		$(identificador+"country_id").disabled=true;
			$(identificador+"direccion_alterna").disabled=true;
    		$(identificador+"region_id").disabled=true;
    		$(identificador+"city").disabled=true;	  
    		$(identificador+"telephone").disabled=true;
	  }


		
		new Ajax.Request( "?customAjax=true", {
		    method: "get",
		    parameters: {
		        telephone : telefono.value,
				postcode  : codigoCiudad.value,
		        direccion : direccion.value,
		        georef    : georef,
		        func: "traerDireccionWS"
		    },
//		    onLoading:function(){
//		    	
//			
//	        
//       			
//		    },
		    onFailure:function(){
		    	
		    	if($('disablingDiv_'))
					$('disablingDiv_').style.display='none';
				
				if($('disablingDiv_2')){
					$('disablingDiv_2').style.display='none';
				}
					
		    	if(identificador=="") {
	    	  		$("street_1").style.background="#FFFFFF";
			        $("street_1").disabled=false;
					$("direccion").disabled=false;
		        	$("barrio").disabled=false;
		        	$("coordenadax").disabled=false;
		        	$("coordenaday").disabled=false;
	        		$("direccion_alterna").disabled=false;
	        		
	        		$("country").disabled=false;
	        		$("direccion_alterna").disabled=false;
	        		$("region_id").disabled=false;
	        		$("city").disabled=false;	
					$("telephone").disabled=false;  
   				}
   				else
   				{
   					$(ele.id).style.background="#FFFFFF";
   					$(ele.id).disabled=false;
   					$(eledir.id).disabled=false;
   					$(elebarr.id).disabled=false;
   					$(elebarr1.id).disabled=false;
   					$(elecorx.id).disabled=false;
   					$(elecory.id).disabled=false;
   					$(eledirA.id).disabled=false;
   					
   					$(identificador+"country_id").disabled=false;
   					$(identificador+"direccion_alterna").disabled=false;
	        		$(identificador+"region_id").disabled=false;
	        		$(identificador+"city").disabled=false;	  
	        		$(identificador+"telephone").disabled=false;
   					
   				}
		    },
		    onSuccess: function( transport ) {
		    	
		    	if($('disablingDiv_'))
					$('disablingDiv_').style.display='none';
					
				if($('disablingDiv_2')){
					$('disablingDiv_2').style.display='none';
				}
		    	
		        if(transport.responseText!="")
      	        {	      	        	
			    	if(identificador=="") {
						$("street_1").disabled=false;
						$("direccion").disabled=false;
						$("barrio").disabled=false;
						$("coordenadax").disabled=false;
			        	$("coordenaday").disabled=false;
			        	$("direccion_alterna").disabled=false;
			        	
			        	$("country").disabled=false;
						$("direccion_alterna").disabled=false;
		        		$("region_id").disabled=false;
		        		$("city").disabled=false;	
						$("telephone").disabled=false;		        	
		        	}
		        	else
		        	{
		        		$(ele.id).disabled=false;
	   					$(eledir.id).disabled=false;
	   					$(elebarr.id).disabled=false;
	   					$(elebarr1.id).disabled=false;
	   					$(elecorx.id).disabled=false;
	   					$(elecory.id).disabled=false;
	   					$(eledirA.id).disabled=false;
	   					
	   					
	   					$(identificador+"country_id").disabled=false;
	   					$(identificador+"direccion_alterna").disabled=false;
		        		$(identificador+"region_id").disabled=false;
		        		$(identificador+"city").disabled=false;
		        		$(identificador+"telephone").disabled=false;
		        	}
 	        	
			 	  if(transport.responseText!="0")
			       {
        				var arreglo=explode(",",transport.responseText);
        				
        				if(identificador=="") {
							$("street_1").style.background="#FFFFFF";
							//$("street_1").style.background="#3333FF";
	      	        		$("street_1").value=arreglo[0];
	      	        		$("direccion").value=arreglo[0];
				       		$("barrio").value=arreglo[1];
				       	//	$('barrio').setAttribute('value', arreglo[1]);// "5000601");
				       		$("coordenadax").value=arreglo[2];
				        	$("coordenaday").value=arreglo[3];
				        	$("direccion_alterna").value=arreglo[4];
      					}
						  else
						  {
						  	if(arreglo[0]!="")
						  	{
							    $(ele.id).style.background="#FFFFFF";
	        					$(ele.id).value=arreglo[0];
								$(eledir.id).value=arreglo[0];
	        					$(elebarr.id).value=arreglo[1];
	        					//$(elebarr1.id).value=arreglo[1];
	        					$(elecorx.id).value=arreglo[2];
	        					$(elecory.id).value=arreglo[3];
	        					$(eledirA.id).value=arreglo[4];
   							}
   							else
   							{
   								$(elecorx.id).value="0";
	        					$(elecory.id).value="0";
   							}
						  }	
						  			         		
		       		}
		        	else 
					{
		        		if(identificador=="") {
		        			$("street_1").style.background="#FFFFFF";
			        		//$("direccion").value="";
			        		//$("barrio").value="";
			        		$("coordenadax").value="";
			        		$("coordenaday").value="";
			        		$("direccion_alterna").value="";
	        			}
		        		else
		        		{
        					$(ele.id).style.background="#FFFFFF";
        				/*	$(eledir.id).value="";
        					$(elebarr.id).value="";
        					$(elecorx.id).value="";
        					$(elecory.id).value="";
        					$(eledirA.id).value="";*/
	        			}
		        		
	        		}
		        }
				//new Insertion.Bottom( $$("body")[0], transport.responseText );
		    }
		}); 	
	}
}


function trimString(str)
{
 	return str.replace(/^\s*|\s*$/g,"");
}
function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    // 
    // version: 905.412
    // discuss at: http://phpjs.org/functions/explode
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
 
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}