﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />



Type.registerNamespace("UI.Controls");

//
UI.Controls.MapLocationBehavior = function(element) {
    /// <summary>
    /// Administra el panel para localización en el mapa
    /// </summmary>
    /// <param name="element" type="Sys.UI.DomElement">The element to attach to</param>
    UI.Controls.MapLocationBehavior.initializeBase(this, [element]);
    // Referencia a Controles y objetos
    this._parentControl = null; // Referencia al control de mapas
    this._container = null;     // contenedor
    // Fields
    this._locId = -1;                // Localidad seleccionada
    this._barId = -1;                // Identificador del barrio
    this._lstLocalidades = null;     // Lista de localidades
    this._txtBarrio = null;          // Lista de barrios
    this._txtCalle = null;           // Calle
    this._txtCalleEsquina = null;    // Calle intersección.
    this._calleDirty = false;        // Cuando se modifica el valor de una calle se marca
    this._barrioDirty = false;       // Cuando se modifica el barrio, este valor cambia a true
    this._cfgLocalidades = null;     // Lista de localidades, se cargan la primera vez que se necesitan
    this._cfgBarrios = null;         // Lista de Barrios
    this._loadLocalidadesTimer = 0;  // Temporizador utilizado para retrasar unos segundos la carga de localidades
    this._loadBarriosTimer = 0;      // Temporizador utilizado para retrasar unos segundos la carga de barrios
    this._lnkLimpiar = null;         // Botón link para limpiar el formulario
    this._autosearch = true;         // Bandera utilizada para habilitar/suspender temporalmente el auto search
    // Propiedades
    this._MapLocationPanelId = null;    // Id del Panel para desarrollar controles
    this._ServicePath = null;           // Ruta del servicio web con el método para insertar un delito

    // Eventos
    this._lstLocalidades$delegates = {
        change: Function.createDelegate(this, this._lstLocalidades_onChange)
    };
    this._txtBarrios$delegates = {
        change: Function.createDelegate(this, this._txtBarrios_onChange),
        keydown: Function.createDelegate(this, this._txtBarrios_onKeyDown)
    };
    this._txtCalle$delegates = {
        keydown: Function.createDelegate(this, this._txtCalle_onKeyDown),
        change: Function.createDelegate(this, this._txtCalle_onChange)
    };
    this._txtCalleEsquina$delegates = {
        keydown: Function.createDelegate(this, this._txtCalleEsquina_onKeyDown),
        change: Function.createDelegate(this, this._txtCalleEsquina_onChange)
    };
    this._lnkLimpiar$delegates = {
        mousedown: Function.createDelegate(this, this._lnkLimpiar_onMouseDown),
        click: Function.createDelegate(this, this._lnkLimpiar_onClick)
    };

}

UI.Controls.MapLocationBehavior.prototype = {
    initialize: function() {
        UI.Controls.MapLocationBehavior.callBaseMethod(this, 'initialize');
        //
        this._parentControl = this.get_element().control;
        this._container = $get(this._MapLocationPanelId);
        // Attach events
        // Construye elementos
        this.buildControls();
    },
    dispose: function() {
        // Detach Handlers
        UI.Controls.MapLocationBehavior.callBaseMethod(this, 'dispose');
    },
    get_PlugInId: function() {
        /// <value type="string" mayBeNull="false">
        /// Gets de plugIn unique id
        /// </value>
        return 'ui.controls.MapLocation';
    },
    load: function(container) {
        /// <summary>
        // loads the current plugin into the main map container, creates menu, toolbar, atach events, etc
        /// </summary>
        /// <param name="container" type="SGis.MapToolkit.MapControl">
        /// The map control container
        /// </param>
        // Load Plugin
    },
    unload: function() {
        // Unloads Plugin
    },
    buildControls: function() {
        /// <summary>
        /// Construye los controles contenidos 
        /// </summary>
        /// <returns />
        var tabla = $common.createElementFromTemplate(
        {
            nodeName: "table",
            cssClasses: ["ui_maplocation_datos"]
        }, this._container);
        var tbody1 = $common.createElementFromTemplate({ nodeName: "tbody" }, tabla);
        this.buildLstLocalidades(tbody1);
        this.buildTxtBarrios(tbody1);
        this.buildTxtCalle(tbody1);
        this.buildTxtCalleEsquina(tbody1);
        this.buildLnkLimpiar();
        //
    },
    // Construye la fila para la selección de localidades
    buildLstLocalidades: function(tablebody) {
        var tr = $common.createElementFromTemplate({ nodeName: "tr" }, tablebody);
        var td1 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            properties: {
                innerHTML: "<span>Localidad</span>"
            },
            cssClasses: ["ui_maplocation_datos_label"]
        }, tr);
        var td2 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            cssClasses: ["ui_maplocation_datos_field"]
        }, tr);
        this._lstLocalidades = $common.createElementFromTemplate(
        {
            nodeName: "select",
            properties: {
                style: {
                    width: "150px",
                    fontSize: "10px"
                },
                disabled: true
            }, events: this._lstLocalidades$delegates
        }, td2);
        this.programLoadLocalidades(4000); // programa con retraso la carga de lista de localidades, 5segundos
    },
    // Construye la fila para la selección de barrios
    buildTxtBarrios: function(tablebody) {
        var tr = $common.createElementFromTemplate({ nodeName: "tr" }, tablebody);
        var td1 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            properties: {
                innerHTML: "<span>Barrio</span>"
            },
            cssClasses: ["ui_maplocation_datos_label"]
        }, tr);
        var td2 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            cssClasses: ["ui_maplocation_datos_field"]
        }, tr);
        this._txtBarrio = $common.createElementFromTemplate(
        {
            nodeName: "input",
            properties: {
                style: {
                    width: "144px",
                    fontSize: "10px"
                }
            }, events: this._txtBarrios$delegates
        }, td2);
        // Agrega extensor para mostrar lista de ayuda de calles
        $create(
            AjaxControlToolkit.AutoCompleteBehavior,
            {
                "completionSetCount": 20,
                "delimiterCharacters": ";, :",
                "id": "AutoCompleteBarrioEx",
                "completionInterval": 300,
                "minimumPrefixLength": 2,
                "serviceMethod": "GetBarrioCompletionList",
                "servicePath": this._ServicePath,
                "showOnlyCurrentWordInCompletionListItem": true
            }, null, null, this._txtBarrio);
    },
    // Construye la fila para la carga de calle
    buildTxtCalle: function(tablebody) {
        var tr = $common.createElementFromTemplate({ nodeName: "tr" }, tablebody);
        var td1 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            properties: {
                innerHTML: "<span>Calle</span>"
            },
            cssClasses: ["ui_maplocation_datos_label"]
        }, tr);
        var td2 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            cssClasses: ["ui_maplocation_datos_field"]
        }, tr);
        this._txtCalle = $common.createElementFromTemplate(
        {
            nodeName: "input",
            properties: {
                style: {
                    width: "144px",
                    fontSize: "10px"
                }
            }, events: this._txtCalle$delegates
        }, td2);
        // Agrega extensor para mostrar lista de ayuda de calles
        $create(
            AjaxControlToolkit.AutoCompleteBehavior,
            {
                "completionSetCount": 20,
                "delimiterCharacters": ";, :",
                "id": "AutoCompleteCalleEx",
                "completionInterval": 300,
                "minimumPrefixLength": 2,
                "serviceMethod": "GetCallesCompletionList",
                "servicePath": this._ServicePath,
                "showOnlyCurrentWordInCompletionListItem": true
            }, null, null, this._txtCalle);
    },
    // Construye la fila para la carga de calle esquina
    buildTxtCalleEsquina: function(tablebody) {
        var tr = $common.createElementFromTemplate({ nodeName: "tr" }, tablebody);
        var td1 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            properties: {
                innerHTML: "<span>Esquina</span>"
            },
            cssClasses: ["ui_maplocation_datos_label"]
        }, tr);
        var td2 = $common.createElementFromTemplate(
        {
            nodeName: "td",
            cssClasses: ["ui_maplocation_datos_field"]
        }, tr);
        this._txtCalleEsquina = $common.createElementFromTemplate(
        {
            nodeName: "input",
            properties: {
                style: {
                    width: "144px",
                    fontSize: "10px"
                }
            }, events: this._txtCalleEsquina$delegates
        }, td2);
        // Agrega extensor para mostrar lista de ayuda de calles
        $create(
            AjaxControlToolkit.AutoCompleteBehavior,
            {
                "completionSetCount": 20,
                "delimiterCharacters": ";, :",
                "id": "AutoCompleteCalleEsquinaEx",
                "completionInterval": 300,
                "minimumPrefixLength": 2,
                "serviceMethod": "GetCallesCompletionList",
                "servicePath": this._ServicePath,
                "showOnlyCurrentWordInCompletionListItem": true
            }, null, null, this._txtCalleEsquina);

    },
    buildLnkLimpiar: function() {
        // Boton para limpiar el formulario
        this._lnkLimpiar = $common.createElementFromTemplate(
        {
            nodeName: "a",
            cssClasses: ["ui_maplocation_btn_limpiar"],
            properties: {
                href: "#",
                innerHTML: "Limpiar Formulario",
                title: "Limpiar Formulario"
            },
            events: this._lnkLimpiar$delegates
        }, this._container);
    },

    // Carga las localidades en la lista de selección
    resetLstLocalidades: function() {
        if (!this._cfgLocalidades) {
            this.invokeGetLocalidadesWebService();
        } else {
            var lst = this._lstLocalidades;
            var cfg = this._cfgLocalidades;
            lst.disabled = false;
            lst.innerHTML = "";
            lst.options[lst.options.length] = new Option("", "-1");
            lst.options[lst.options.length - 1].selected = true;
            for (var i in cfg) {
                var l = cfg[i];
                var o = new Option(l.LocNombre, l.LocId.toString());
                o.CfgLocalidad = l;
                lst.options[lst.options.length] = o;
            }
        }
    },
    // Invoca procedimiento para determinar si se puede localizar la calle
    buscarCalles: function() {
        if (!this._calleDirty) return;
        this._calleDirty = false;
        this.invokeGetCallesExtentWebService();
    },
    // Invoca al servicio web para obtener lista de localidades en forma asincrónica
    invokeGetCallesExtentWebService: function() {

        Sys.Net.WebServiceProxy.invoke(this._ServicePath, "GetCallesExtent", false,
        { calle: this._txtCalle.value, esquina: this._txtCalleEsquina.value, locId: this._locId }
        ,
        Function.createDelegate(this, this.onGetCallesExtentMethodComplete),
        Function.createDelegate(this, this.onGetCallesExtentMethodError), null, 50000);
    },
    // Se completo invocación al web service -
    onGetCallesExtentMethodComplete: function(result, userContext, methodName) {
        if (result.Found) {
            this.drawLineCalles(result.Calle1, result.Calle2);
            this._parentControl.changeExtentToBox(result.MinX, result.MaxX, result.MinY, result.MaxY);
        } else {
            this.hideLineCalles();
        }
    },
    // Error al invocar web service
    onGetCallesExtentMethodError: function(webServiceError, userContext, methodName) {
        // Error al localizar calles
        this.hideLineCalles();
    },
    // Programa la carga de localidades desde el servidor
    programLoadLocalidades: function(ms) {
        window.clearTimeout(this._loadLocalidadesTimer);
        this._loadLocalidadesTimer = window.setTimeout(Function.createDelegate(this, this.resetLstLocalidades), ms);
    },
    // Invoca al servicio web para obtener lista de localidades en forma asincrónica
    invokeGetLocalidadesWebService: function() {
        Sys.Net.WebServiceProxy.invoke(this._ServicePath, "GetLocalidades", false, null,
        Function.createDelegate(this, this.onGetLocalidadesMethodComplete),
        Function.createDelegate(this, this.onGetLocalidadesMethodError), null, 50000);
    },
    // Se completo invocación al web service - GetLocalidades
    onGetLocalidadesMethodComplete: function(result, userContext, methodName) {
        if (!this._cfgLocalidades) {
            this._cfgLocalidades = result;
            this.resetLstLocalidades();
        }
    },
    // Error al invocar web service
    onGetLocalidadesMethodError: function(webServiceError, userContext, methodName) {
        // Reintenta
        this.programLoadLocalidades(3000);
    },
    // Invoca procedimiento para determinar si se puede localizar la calle
    buscarBarrio: function() {
        if (!this._barrioDirty) return;
        this._barrioDirty = false;
        this.invokeGetBarrioExtentWebService();
    },
    // Invoca al servicio web para obtener lista de localidades en forma asincrónica
    invokeGetBarrioExtentWebService: function() {
        Sys.Net.WebServiceProxy.invoke(this._ServicePath, "GetBarrioExtent", false,
        { barrio: this._txtBarrio.value, locId: this._locId }
        ,
        Function.createDelegate(this, this.onGetBarrioExtentMethodComplete),
        Function.createDelegate(this, this.onGetBarrioExtentMethodError), null, 50000);
    },
    // Se completo invocación al web service -
    onGetBarrioExtentMethodComplete: function(result, userContext, methodName) {
        if (result.Found) {
            if (result.BarId && result.BarId > 0) {
                this.drawPolygonBarrio(result.BarId, result.BarGeomWKT);
            } else {
                this.hidePolygonBarrio();
            }
            this._parentControl.changeExtentToBox(result.MinX, result.MaxX, result.MinY, result.MaxY);
        } else {
            this.hidePolygonBarrio();
        }
    },
    // Error al invocar web service
    onGetBarrioExtentMethodError: function(webServiceError, userContext, methodName) {
        // Error al localizar barrio
        this.hidePolygonBarrio();
    },
    // Habilita la capa de barrios para dibujarlo
    drawPolygonBarrio: function(barId, barGeomWKT) {
        var lyr = $find('LayerMapBarrio');
        if (lyr) {
            var par = new Object();
            par.BarId = barId;
            par.BarGeomWKT = barGeomWKT;
            lyr._isDirty = true;
            lyr.set_Params(Sys.Serialization.JavaScriptSerializer.serialize(par));
            lyr.set_LayerEnabled(true);

        }
    },
    // Oculta el barrio
    hidePolygonBarrio: function() {
        var lyr = $find('LayerMapBarrio');
        if (lyr) {
            lyr.set_Params(Sys.Serialization.JavaScriptSerializer.serialize(""));
            lyr.set_LayerEnabled(false);
        }
    },
    // Habilita la capa de calles para dibujarlo
    drawLineCalles: function(calle1, calle2) {
        var lyr = $find('LayerMapCalles');
        if (lyr) {

            var par = new Object();
            par.Calle1 = calle1;
            par.Calle2 = calle2;
            lyr._isDirty = true;
            lyr.set_Params(Sys.Serialization.JavaScriptSerializer.serialize(par));
            lyr.set_LayerEnabled(true);

        }
    },
    // Oculta calles
    hideLineCalles: function() {
        var lyr = $find('LayerMapCalles');
        if (lyr) {
            lyr.set_Params(Sys.Serialization.JavaScriptSerializer.serialize(""));
            lyr.set_LayerEnabled(false);
        }
    },
    clearForm: function() {
        this._autoseach = false;
        this._lstLocalidades.options[0].selected = true;
        this._txtBarrio.value = "";
        this._txtCalle.value = "";
        this._txtCalleEsquina.value = "";
        this.hideLineCalles();
        this.hidePolygonBarrio();
        this._autoseach = true;
    },
    // Hack para ie 6, oculta los select porque siempre se muestran en primer plano
    hackIe6HideSelects: function() {
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7) {
            Sys.UI.DomElement.setVisible(this._lstLocalidades, false);
        }
    },
    // Hack para ie 6, muestra los select ocultados
    hackIe6ShowSelects: function() {
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7) {
            Sys.UI.DomElement.setVisible(this._lstLocalidades, true);
        }
    },

    //--------------------------------------------------------------------------
    // Acceso a Propiedades
    //--------------------------------------------------------------------------
    get_MapLocationPanelId: function() {
        return this._MapLocationPanelId;
    },
    set_MapLocationPanelId: function(value) {
        if (this._MapLocationPanelId != value) {
            this._MapLocationPanelId = value;
            this.raisePropertyChanged('MapLocationPanelId');
        }
    },
    get_ServicePath: function() {
        return this._ServicePath;
    },
    set_ServicePath: function(value) {
        if (this._ServicePath != value) {
            this._ServicePath = value;
            this.raisePropertyChanged('ServicePath');
        }
    },
    //--------------------------------------------------------------------------
    // Manejadores de Eventos
    //--------------------------------------------------------------------------
    // Al cambiar valor seleccionado de departamento
    _lstLocalidades_onChange: function(sender, args) {
        var c = this._lstLocalidades;
        var i = c.selectedIndex;
        var locNombre = "";
        this._locId = -1;
        if (i && i >= 0) {
            var o = c.options[i];
            if (o.CfgLocalidad) {
                var l = o.CfgLocalidad;
                this._locId = l.LocId;
                locNombre = l.LocNombre;
                if (this._autosearch) {
                    this._parentControl.changeExtentToBox(l.MinX, l.MaxX, l.MinY, l.MaxY);
                }
            }
        }
        // Deshabilita o habilita campos de calle y barrio cuando se selecciono Localidad
        // Temporal
        var dis = true;
        if (this._locId == -1 || locNombre == "San Luis") {
            dis = false;

        }
        this._txtBarrio.disabled = dis;
        this._txtCalle.disabled = dis;
        this._txtCalleEsquina.disabled = dis;
    },
    _txtBarrios_onChange: function(sender, args) {
        if (this._autosearch) {
            this._barrioDirty = true;
            this.buscarBarrio();
        }
    },
    _txtBarrios_onKeyDown: function(sender, args) {
        var k = sender.keyCode ? sender.keyCode : sender.rawEvent.keyCode;
        if (k === Sys.UI.Key.enter && this._autosearch) {
            this._barrioDirty = true;
            this.buscarBarrio();
        }
    },
    _txtCalle_onChange: function(sender, args) {
        if (this._autosearch) {
            this._calleDirty = true;
            this.buscarCalles();
        }
    },
    _txtCalle_onKeyDown: function(sender, args) {
        var k = sender.keyCode ? sender.keyCode : sender.rawEvent.keyCode;
        if (k === Sys.UI.Key.enter && this._autosearch) {
            this._calleDirty = true;
            this.buscarCalles();
        }
    },
    _txtCalleEsquina_onChange: function(sender, args) {
        if (this._autosearch) {
            this._calleDirty = true;
            this.buscarCalles();
        }
    },
    _txtCalleEsquina_onKeyDown: function(sender, args) {

        var k = sender.keyCode ? sender.keyCode : sender.rawEvent.keyCode;
        if (k === Sys.UI.Key.enter && this._autosearch) {
            this._calleDirty = true;
            this.buscarCalles();
        }
    },
    _lnkLimpiar_onMouseDown: function(sender, args) {
        this.clearForm();
    },
    _lnkLimpiar_onClick: function(sender, args) {
        sender.preventDefault();
        sender.stopPropagation();
    }



}
UI.Controls.MapLocationBehavior.registerClass('UI.Controls.MapLocationBehavior', AjaxControlToolkit.BehaviorBase, SGis.MapToolkit.IPlugIn);



if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();