﻿var localizadorNS = (function() {
    function LocalizadorOBJ(config) {
                            var conf = eval('(' + config + ')');
                            this.clientID = conf.clientID;
                            this.textboxCalle = getElementByIdEx(conf.textboxCalle);
                            this.textboxCalle.value = '';
                            this.listaCalles = getElementByIdEx(conf.listaCalles);                            
                            this.textboxNum = getElementByIdEx(conf.textboxNum);
                            this.textboxNum.value = '';
                            this.textboxLetra = getElementByIdEx(conf.textboxLetra);
                            this.textboxLetra.value = '';
                            this.ajaxloader = conf.ajaxloader;
                            this.textboxCalle.style.background = 'url(' + this.ajaxloader + ') no-repeat 200%';
                            this.calleSelected = false;
                            this.coordenadasListener = null;
                            this.direccionClicada = getElementByIdEx(conf.direccionClicada);
                            this.printlink = getElementByIdEx(conf.printlink);
                            this.printUrl = conf.printUrl;
                            this.associatedMap = null;
                            //this.listaCalles.style.visibility = 'visible';
                            //this.listaCalles.style.display = 'block';
                            //this.listaCalles.parentNode.style.visibility = 'hidden';
                            
                        };
    LocalizadorOBJ.prototype.CallbackError = function(message) {
                            alert("Ha ocurrido un error:\n" + message);
                        };
 
	// Funcion para ahorrar vaciar un ListBox sin problemas con IE			
	LocalizadorOBJ.prototype.deleteListbox = function(lb) {
							if(!lb || lb.selectedIndex < 0) {
								return;
							}
							while(lb.hasChildNodes()) {
								// Quitamos optgroups y options
								if((lb.childNodes[0].nodeType == 1) || (lb.childNodes[0].nodeType == 3)) {
									lb.removeChild(lb.childNodes[0]);
								}
							}
							// Per si de cas, ponemos la longitud a cero
							lb.options.length=0;
						};

 
    LocalizadorOBJ.prototype.ListaCallesHandler = function(result, context) {

                            var me = eval(context);
                            var objCalles = eval('(' + result + ')');                                                           
                            if (objCalles.oficiales.length == 0 && objCalles.historicos.length == 0 ){
                                me.setAjaxLoader(false);
                                this.calleSelected = false;
                                return;
                            }
                            var iter;
                            var grupoOfic;
                            var grupoHist;
                            var elemento;
                            me.calleSelected = true;

                            
                            var hayHist = objCalles.historicos.length > 0;
                            var hayOfi = (objCalles.oficiales.length > 0) && (objCalles.historicos.length > 0);
                            var len = 0;
							if( objCalles.historicos.length + objCalles.oficiales.length > 0 ) {
                            	me.deleteListbox(me.listaCalles);
                            	//me.listaCalles.innerHTML = '';
                            }
                            if (hayOfi){
                                var oficiales = document.createElement('optgroup');
                                me.listaCalles.appendChild(oficiales);
                                oficiales.label = 'Oficials';
                                len = objCalles.oficiales.length;
                                
                                for (iter = 0; iter < len; iter++){
                                    elemento = document.createElement('option');
                                    oficiales.appendChild(elemento); 
                                    elemento.text = objCalles.oficiales[iter].nombre;
                                    elemento.value = objCalles.oficiales[iter].codigo;
                                }

                            }else{
                                    len = objCalles.oficiales.length;
                                    for (iter = 0; iter < len; iter++){
                                        elemento = document.createElement('option');
                                        me.listaCalles.options.add(elemento); 
                                        elemento.text = objCalles.oficiales[iter].nombre;
                                        elemento.value = objCalles.oficiales[iter].codigo;

                                    }
                            }
                           
                            if (hayHist){
                                var historicos = document.createElement('optgroup');
                                me.listaCalles.appendChild(historicos);
                                historicos.label = 'Històrics';
                                len = objCalles.historicos.length;
                                for(iter = 0; iter < len; iter++){
                                    elemento = document.createElement('option');
                                    historicos.appendChild(elemento); 
                                    elemento.text = objCalles.historicos[iter].nombre;
                                    elemento.value = objCalles.historicos[iter].codigo;
                                }

                            }        
                            me.listaCalles.selectedIndex = 0;                    
                            me.setAjaxLoader(false);
                            me.showListaCalles();
                        };
                                              
    LocalizadorOBJ.prototype.showListaCalles = function(){    
                            if(this.listaCalles.length > 0){                               
                                this.listaCalles.parentNode.style.visibility = 'visible';
                                this.listaCalles.style.visibility = 'visible';
                                this.listaCalles.style.display = 'block';
                            }
                        };

    LocalizadorOBJ.prototype.hideListaCalles = function(){   
                            //alert('hideListaCalles 1') ;
                            this.listaCalles.parentNode.style.visibility = 'hidden';
                            this.listaCalles.style.visibility = 'hidden';
                            this.listaCalles.style.display = 'none';
                            //this.listaCalles.parentNode.style.display = 'none';
                            //alert('hideListaCalles 2') ;
                            sleep(500);
                        };
                        
function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
                                              
    LocalizadorOBJ.prototype.getEntidadFromCoord = function(x, y){    
                            if(this.coordenadasListener){
                                this.coordenadasListener(x,y);
                            }
                            //alert(x + " " + y);
                            WebForm_DoCallback(this.clientID,this.clientID + '_entidad:' + x + '||' + y, this.EntidadHandler,this.clientID,this.CallbackError,false);
                        };
    
    LocalizadorOBJ.prototype.EntidadHandler = function(result, context){
                            var me = eval(context);
                            var res = eval('('+result+')');
                            
                            res[1] = parseInt(res[1],10);
                            
                            me.direccionClicada.innerHTML = res[0] + ((res[1]!=0)? ", " + res[1] : "" ) + " " + res[2];
                            me.RefreshMap();
                        };
    
    LocalizadorOBJ.prototype.specialKey = function(event){
                            var e = event || window.event;
                            switch(e.keyCode){
                                case 37:
                                    break;
                                case 38:
                                //case 63232:
                                //Flecha arriba
                                    if (this.listaCalles.selectedIndex > 0){
                                        this.listaCalles.selectedIndex--;
                                    }
                                    break;
                                    
                                case 40:
                                //case 63233:
                                //Flecha abajo
                                    if(this.listaCalles.selectedIndex < this.listaCalles.length - 1){
                                        this.listaCalles.selectedIndex++;
                                    }
                                    break;
                                case 13:
                                //Intro.
                                    if ((!this.calleSelected || this.listaCalles.selectedIndex == -1)&&(this.getCalle().length > 2)){
                                        this.setAjaxLoader(true);
                                        WebForm_DoCallback(this.clientID,this.clientID + '_calle:' + this.getCalle(),this.ListaCallesHandler,this.clientID,this.CallbackError,false)
                                        
                                        break;
                                    }
                                    if (this.associatedMap == '') break;
                                    
                                    var visorMapas = eval(this.associatedMap);
                                    visorMapas.setMapBusy(true);
                                    this.textboxCalle.value = this.listaCalles.options[this.listaCalles.selectedIndex].text;
                                    
                                    WebForm_DoCallback(this.clientID,this.clientID + '_coord:' + this.getCodigoSel() + '||' + this.getNumero() + '||' + this.getLetra() + '||' + visorMapas.getHeight() + '||' + visorMapas.getWidth(),visorMapas.CentraMapaHandler,this.associatedMap,visorMapas.CallbackError,false);
                                    this.hideListaCalles();
                                                                        
                                    //this.listaCalles.innerHTML = '';  
                                    //this.calleSelected = false;
                                    
                                    break;  
                                case 39:
                                case 9:
                                //case 63235:
                                //Flecha Derecha y Tab
                                    if (this.listaCalles.selectedIndex <0) break;
                                    this.textboxCalle.value = this.listaCalles.options[this.listaCalles.selectedIndex].text;
                                    //this.textboxCalle.onblur()
                                    this.hideListaCalles();
                                    break;
                                
                                default:
                                   // this.calleSelected = false;
                                    return false;                            
                            }
                                                        
                            return true;
                        };
                        
    LocalizadorOBJ.prototype.ignoreKey = function(event) { 
                            var e = event || window.event;
                            switch(e.keyCode){
                            case 37:
                            case 38:
                            case 40:
                            case 13:
                            case 39:
                                return true;
                            default:
                                return false;
                            }
                        } ;
                                                                     
    LocalizadorOBJ.prototype.getCalle = function() { 
                            return this.textboxCalle.value;
                           
                        };
                        
    LocalizadorOBJ.prototype.getCodigoSel = function() {
                            return this.listaCalles.value;
                        };
                        
    LocalizadorOBJ.prototype.getNumero = function() {
                            if(this.textboxNum.value != undefined){
                                return this.textboxNum.value;
                            }else{
                                return "";
                            }
                        };
                        
    LocalizadorOBJ.prototype.getLetra = function() {
                            if(this.textboxLetra.value != undefined){
                                return this.textboxLetra.value.toUpperCase();
                            }else{
                                return "";
                            }
                        };                                                  
    
    LocalizadorOBJ.prototype.setAjaxLoader = function(enable){
                            if (enable) {
                                this.textboxCalle.style.backgroundPosition = 'right';
                            } else {
                                this.textboxCalle.style.backgroundPosition = '200%';
                            }
                    };
                    
    LocalizadorOBJ.prototype.addCoordenadasListener = function(listener){
                        this.coordenadasListener = listener;
                    };
                    
    LocalizadorOBJ.prototype.setAssociatedMap = function(map){
                        this.associatedMap = map;
                        this.associatedMap.addRefreshListener(this);
                        this.RefreshMap();
                    };
                    
    LocalizadorOBJ.prototype.RefreshMap = function(){
                        if (this.associatedMap){
                            var url = this.associatedMap.getCurrentMapURL(620,900);
                            url = url.split('?');
                            
                            this.printlink.href = this.printUrl + '?' + url[1] + '&xmlUri=' + location.href.substring(0, location.href.lastIndexOf('\/')) + '/SelectorCapas.xml' + '&nomDireccion=' + this.direccionClicada.innerHTML;                        
                        //this.printlink.href = this.printUrl + '?' + url[1] + '&xmlUri=http://www.l-h.cat/proves/planol/SelectorCapas.xml' + '&nomDireccion=' + this.direccionClicada.innerHTML;                        
                        }
                    };
                    
                    
    return {
        LocalizadorOBJ : LocalizadorOBJ 
    }
})();

