﻿/// <reference name="MicrosoftAjax.debug.js" />
/// <reference name="MicrosoftAjaxTimer.debug.js" />
/// <reference name="MicrosoftAjaxWebForms.debug.js" />


Type.registerNamespace("UI.Controls");
//
UI.Controls.EventInfoTipBehavior = function(element) {

    UI.Controls.EventInfoTipBehavior.initializeBase(this, [element]);
    // Referencia a Controles y objetos
    this._parentControl = null; // Referencia al control de mapas
    this._controller = null;    // Controlador de acciones
    this._container = null; // Contenedor del formulario de edición
    this._form = null; // contenedor del formulario
    this._shadowB = null; // Shadow con flecha hacia arriba
    this._shadowT = null; // Shadow con flecha hacia abajo
    this._btnCancelar = null;
    this._dataPanel = null;   // Panel donde se reflejan los datos
    this._titlePanel = null;  // Panel de títulos
    this._recordsPanel = null;   // Panel para mostrar registro actual y botones de desplazamiento
    this._btnNextRecord = null;  // Botón para ver el registro proximo
    this._btnPreviousRecord = null; // Botón para ver el registro anterior
    this._lblCurrentRecord = null;  // Etiqueta con el registro actualmente seleccionado
    // Fields
    this._offsetX = null; // Desplazamiento x del tooltip respecto del punto en pantalla
    this._offsetY = null; // Desplazamiento y del tooltip respecto del punto en pantalla
    this._eventX = null;  // Coordenadas de mundo X
    this._eventY = null;  // Coordenadas de mundo Y
    this._cache = []; // Lista asociativa de objetos usada como cache
    this._idList = [];   // Arreglo de identificadores (pasado como parametros)
    this._currentIndex = null;  // índice actual
    // Propiedades
    this._ServicePath = null;                // Ruta del servicio web con el método para insertar un delito
    // Eventos
    this._btnCancel$delegates = {
        mousedown: Function.createDelegate(this, this._btnCancel_onMouseDownHandler),
        click: Function.createDelegate(this, this._btnCancel_onClickHandler)
    };
    this._mapControl$onMapExtentChanged$delegate = Function.createDelegate(this, this._mapControl_onMapExtentChanged);
    this._mapControl$onPanningMove$delegate = Function.createDelegate(this, this._mapControl_onPanningMove);
    this._btnPreviousRecord$delegates = {
        mousedown: Function.createDelegate(this, this._btnPreviousRecord_onMouseDownHandler),
        click: Function.createDelegate(this, this._btnPreviousRecord_onClickHandler)
    };
    this._btnNextRecord$delegates = {
        mousedown: Function.createDelegate(this, this._btnNextRecord_onMouseDownHandler),
        click: Function.createDelegate(this, this._btnNextRecord_onClickHandler)
    };
}

UI.Controls.EventInfoTipBehavior.prototype = {
    initialize: function() {
        UI.Controls.EventInfoTipBehavior.callBaseMethod(this, 'initialize');
        //
        this._parentControl = this.get_element().control;
        this._parentControl.add_mapExtentChanged(this._mapControl$onMapExtentChanged$delegate);
        this._parentControl.add_panningMove(this._mapControl$onPanningMove$delegate);
        // Construye elementos
        this.buildControls();
    },
    dispose: function() {
        //Add custom dispose actions here
        this._parentControl.remove_mapExtentChanged(this._mapControl$onMapExtentChanged$delegate);
        this._parentControl.remove_panningMove(this._mapControl$onPanningMove$delegate);
        UI.Controls.EventInfoTipBehavior.callBaseMethod(this, 'dispose');
    },
    get_PlugInId: function() {
        /// <value type="string" mayBeNull="false">
        /// Gets de plugIn unique id
        /// </value>

        return 'ui.controls.EventInfoTip';
    },
    /// <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: function(container) {

    },
    unload: function() {
        // Unloads Plugin
    },
    buildControls: function() {
        //
        this._container = $common.createElementFromTemplate(
        {
            nodeName: "div",
            properties: {
                id: "infotipContainer",
                style: {
                    zIndex: 400
                }
            },
            cssClasses: ["ui_eventinfo_container"]

        }, $get('aspnetForm'));
        // Contenedor para sombra, se crean 2 para intercambiarlos en caso que el punto este arriba o abajo del centro
        this._shadowB = $common.createElementFromTemplate({
            nodeName: "div",
            properties: {
                style: { width: "100%", height: "100%", visibility: "hidden" },
                cssClasses: ["ui_eventinfo_shadow"]
            }
        }, this._container);
        $create(SGis.AjaxToolTip.ToolTipControl, { "ArrowOffset": 125, "Border": "FFFF33", "Color": "#FFFF66", "Opacity": .8, "ArrowPosition": 3 }, null, null, this._shadowB);
        //
        this._shadowT = $common.createElementFromTemplate({
            nodeName: "div",
            cssClasses: ["ui_eventinfo_shadow"]
        }, this._container);
        $create(SGis.AjaxToolTip.ToolTipControl,
            { "ArrowOffset": 125, "Border": "#FFFF33", "Color": "#FFFF66", "Opacity": .8, "ArrowPosition": 2 }, null, null, this._shadowT);
        // Formulario
        this._form = $common.createElementFromTemplate({
            nodeName: "div",
            cssClasses: ["ui_eventinfo_form"]
        }, this._container);
        // Panel de titulos
        this._titlePanel = $common.createElementFromTemplate({
            nodeName: "div",
            cssClasses: ["ui_eventinfo_titlepanel"],
            properties: {
                innerHTML: "<span>Titulo</span>"
            }
        }, this._form);
        // Panel de datos
        this._dataPanel = $common.createElementFromTemplate({
            nodeName: "div",
            cssClasses: ["ui_eventinfo_datapanel"]
        }, this._form);
        // Botón Cancelar/Cerrar
        this._btnCancel = $common.createElementFromTemplate(
        {
            nodeName: "a",
            cssClasses: ["ui_eventinfo_btncancelar"],
            properties: {
                href: "#",
                innerHTML: "Cerrar Ventana de Informaci&oacute;n",
                title: "Cerrar Ventana de Informaci&oacute;n"
            },
            events: this._btnCancel$delegates
        }, this._form);
        // Panel de controles de registro
        this._recordsPanel = $common.createElementFromTemplate(
        {
            nodeName: "div",
            cssClasses: ["ui_eventinfo_recordspanel"]
        }, this._form);
        this._btnPreviousRecord = $common.createElementFromTemplate(
        {
            nodeName: "a",
            cssClasses: ["ui_eventinfo_btnprevious"],
            events: this._btnPreviousRecord$delegates
        }, this._recordsPanel);

        this._lblCurrentRecord = $common.createElementFromTemplate(
        {
            nodeName: "span",
            cssClasses: ["ui_eventinfo_record"]
        }, this._recordsPanel);
        this._btnNextRecord = $common.createElementFromTemplate(
        {
            nodeName: "a",
            cssClasses: ["ui_eventinfo_btnnext"],
            events: this._btnNextRecord$delegates
        }, this._recordsPanel);

    },
    // Muestra el foormulario en las coordenadas de pantalla especificadas
    showForm: function(coords, params) {
        //
        this._controller = $find('EventController');
        // Procesa parámetros
        this._cache = []; // vacia cache
        this._idList = params;
        // Lleva coordenadas de mapa a coordenadas de pantalla
        this._eventX = coords.x;
        this._eventY = coords.y;
        var formPos = this._parentControl.worldToMap({ x: this._eventX, y: this._eventY });
        var mapaPos = Sys.UI.DomElement.getLocation(this._parentControl._mapContainer);
        // Determina formato de layout
        this._offsetX = mapaPos.x + formPos.x - 124;
        if (coords.y > this._parentControl._CenterY) {
            this._offsetY = mapaPos.y + formPos.y + 10;
            this.setLayoutTop();
        } else {
            this._offsetY = mapaPos.y + formPos.y - 175;
            this.setLayoutBottom();
        }
        this._container.style.left = (Math.round(this._offsetX)) + "px";
        this._container.style.top = (Math.round(this._offsetY)) + "px";
        // Establece le primer item inicial
        this.setCurrent(0);
        // Muestra formulario
        Sys.UI.DomElement.setVisible(this._container, true);
    },
    // Oculta el formulario
    hideForm: function() {
        Sys.UI.DomElement.setVisible(this._container, false);
    },
    // Establece el layout con flecha para arriba
    setLayoutTop: function() {
        Sys.UI.DomElement.removeCssClass(this._form, "ui_eventinfo_form_bottom");
        Sys.UI.DomElement.addCssClass(this._form, "ui_eventinfo_form_top");
        Sys.UI.DomElement.setVisible(this._shadowB, false);
        Sys.UI.DomElement.setVisible(this._shadowT, true);

    },
    // Establece el layout con flecha hacia abajo
    setLayoutBottom: function() {
        Sys.UI.DomElement.removeCssClass(this._form, "ui_eventinfo_form_top");
        Sys.UI.DomElement.addCssClass(this._form, "ui_eventinfo_form_bottom");
        Sys.UI.DomElement.setVisible(this._shadowB, true);
        Sys.UI.DomElement.setVisible(this._shadowT, false);
    },
    // Limpia campos.
    clearFields: function() {
        this._dataPanel.innerHTML = "";
        this._titlePanel.innerHTML = "";
    },
    // Establece el item actual
    setCurrent: function(current) {
        this.clearFields();
        this._currentIndex = current;
        var delId = this._idList[current];
        this.showEvent(delId);
    },
    // Muestra el evento dado su Id, primero lo busca en la cache, si no lo pide al servidor
    showEvent: function(delId) {
        // Muestra registro actual y cantidad total
        this._lblCurrentRecord.innerHTML = String.format("{0} / {1}", this._currentIndex + 1, this._idList.length);
        // Verifica si se encuentra en la cache
        if (typeof (this._cache[delId]) != 'undefined' && this._cache[delId]) {
            var obj = this._cache[delId];
            this._titlePanel.innerHTML = obj.HtmlTitle;
            this._dataPanel.innerHTML = obj.HtmlInfo;
        } else {
            // TODO: Mostrar un trhobber
            this.invokeGetInfoTipDelitoWebService(delId);
        }
    },

    // Invoca al servicio web para traer infor de un delito
    invokeGetInfoTipDelitoWebService: function(delId) {
        var param = new Object();
        param.delId = delId;
        Sys.Net.WebServiceProxy.invoke(this._ServicePath, "GetInfoTipDelito", false, param,
        Function.createDelegate(this, this.onGetInfoTipMethodComplete),
        Function.createDelegate(this, this.onGetInfoTipMethodError), null, 50000);

    },

    // Se completo invocación al web service - GetLocalidades
    onGetInfoTipMethodComplete: function(result, userContext, methodName) {
        if (result.IsValid) {
            this._cache[result.DelId] = result;
            if (this._idList[this._currentIndex] == result.DelId) {
                this.showEvent(result.DelId);
            }
        }

    },
    // Error al invocar web service
    onGetInfoTipMethodError: function(webServiceError, userContext, methodName) {
        var txt = "No se pudo obtener información del delito debido a los siguientes errores:";
        for (var i = 0; i < this._errors.length; i++) {
            txt = txt + "\n  " + webServiceError.toString();
        }
        alert(txt);
    },
    //--------------------------------------------------------------------------
    // Acceso a Propiedades
    //--------------------------------------------------------------------------
    get_ServicePath: function() {
        return this._ServicePath;
    },
    set_ServicePath: function(value) {
        if (this._ServicePath != value) {
            this._ServicePath = value;
            this.raisePropertyChanged('ServicePath');
        }
    },
    //--------------------------------------------------------------------------
    // Manejadores de Eventos
    //--------------------------------------------------------------------------
    _btnCancel_onMouseDownHandler: function(sender, args) {
        this.hideForm();
    },
    _btnCancel_onClickHandler: function(sender, args) {
        sender.preventDefault();
        sender.stopPropagation();
    },
    // Al realizar paneo cierra tip
    _mapControl_onPanningMove: function(sender, args) {
        this.hideForm();
    },
    // Al cambiar la extensión del mapa cierra el tip
    _mapControl_onMapExtentChanged: function(sender, args) {
        this.hideForm();
    },
    // Botón registro anterior
    _btnPreviousRecord_onMouseDownHandler: function(sender, args) {
        if (this._currentIndex > 0) {
            this.setCurrent(this._currentIndex - 1);
        }
    },
    _btnPreviousRecord_onClickHandler: function(sender, args) {
        sender.preventDefault();
        sender.stopPropagation();
    },
    // Botón registro siguiente
    _btnNextRecord_onMouseDownHandler: function(sender, args) {
        if (this._currentIndex < this._idList.length - 1) {
            this.setCurrent(this._currentIndex + 1);
        }
    },
    _btnNextRecord_onClickHandler: function(sender, args) {
        sender.preventDefault();
        sender.stopPropagation();
    }

}

UI.Controls.EventInfoTipBehavior.registerClass('UI.Controls.EventInfoTipBehavior', AjaxControlToolkit.BehaviorBase, SGis.MapToolkit.IPlugIn);



if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();