var localUserID = this.userIDD;
var localUserType = this.userType;

Ext.require(['*']);
Ext.Loader.setConfig({ enabled: true });
Ext.Loader.setPath('Ext.ux', '../Recursos/Ext/ux');
Ext.require([
    'Ext.window.*',
    'Ext.ux.GMapPanel'
]);
Ext.onReady(function () {

    Ext.tip.QuickTipManager.init();
    var mapa = new Array(2);
    var mapwin = new Array(2);
    var markers = new Array(2);
    var infowindow = new Array(2);

    Ext.define('MyApp.store.StSituacionB', {
        extend: 'Ext.data.Store',

        constructor: function (cfg) {
            var me = this;
            cfg = cfg || {};
            me.callParent([Ext.apply({
                storeId: 'StSituacionB',
                proxy: {
                    type: 'ajax',
                    timeout: 0,
                    url: '../General/Consultas.php',
                    actionMethods:
                    {
                        read: 'POST'
                    },
                    extraParams:
                    {
                        Filsc: 'Situacion',
                        IncludeAll: 'true'
                    },
                    reader: {
                        type: 'json',
                        root: 'Data',
                        totalProperty: 'totalcount'
                    }
                },
                fields: [
                {
                    name: 'SituationInspectionID'
                },
                {
                    name: 'Description'
                }
            ]
            }, cfg)]);
        }
    });

    var StSituacionB = Ext.create('MyApp.store.StSituacionB', {
        autoLoad: true,
        listeners: {
            load: function (store, records, o) {
                if (store.getCount() >= 1) {
                    Ext.getCmp('cbSituacionB').setValue('-1');
                }
            }
        }
    });

    Ext.define('ModelBusqueda', {
        extend: 'Ext.data.Model',
        fields: [
                {
                    name: 'InspectionID'
                },
                {
                    name: 'Description'
                },
                {
                    name: 'Location'
                },
                {
                    name: 'Provincia'
                },
                {
                    name: 'Canton'
                },
                {
                    name: 'Parroquia'
                },
                {
                    name: 'Latitude'
                },
                {
                    name: 'Longitude'
                },
                {
                    name: 'Zone'
                }
            ]
    });

    Ext.define('MyApp.store.StBusqueda', {
        extend: 'Ext.data.Store',

        constructor: function (cfg) {
            var me = this;
            cfg = cfg || {};
            me.callParent([Ext.apply({
                storeId: 'StBusqueda',
                proxy: {
                    type: 'ajax',
                    timeout: 0,
                    url: '../General/Consultas.php',
                    actionMethods:
                    {
                        read: 'POST'
                    },
                    extraParams:
                    {
                        Filsc: 'ReporteProyectosSituacion'
                        //loadCall: false
                    },
                    reader: {
                        type: 'json',
                        root: 'Data',
                        totalProperty: 'totalcount'
                    }
                }

            }, cfg)]);
        }
    });

    var StBusqueda = Ext.create('MyApp.store.StBusqueda', {
        model: 'ModelBusqueda',
        autoLoad: false,
        listeners: {
            load: function (store, records, o) {
                if (store.getCount() < 1) {
                    //debugger;
                    Ext.Msg.show({ title: '.::Mensaje del Sistema::.', msg: "No existen Registros para la Busqueda" + "<br>...Gracias!!!", buttons: Ext.Msg.OK, icon: Ext.MessageBox.WARNING });
                    return;
                }
            }
        }
    });

    Ext.define('MyApp.store.StProvinciaB', {
        extend: 'Ext.data.Store',

        constructor: function (cfg) {
            var me = this;
            cfg = cfg || {};
            me.callParent([Ext.apply({
                storeId: 'StProvinciaB',
                proxy: {
                    type: 'ajax',
                    timeout: 0,
                    url: '../General/Consultas.php',
                    actionMethods:
                    {
                        read: 'POST'
                    },
                    extraParams:
                    {
                        Filsc: 'Provincia',
                        IncludeAll: 'true'
                    },
                    reader: {
                        type: 'json',
                        root: 'Data',
                        totalProperty: 'totalcount'
                    }
                },
                fields: [
                {
                    name: 'ProvinceID'
                },
                {
                    name: 'Description'
                }
            ]
            }, cfg)]);
        }
    });

    var StProvinciaB = Ext.create('MyApp.store.StProvinciaB', {
        autoLoad: true
    });

    Ext.define('MyApp.store.StCantonB', {
        extend: 'Ext.data.Store',

        constructor: function (cfg) {
            var me = this;
            cfg = cfg || {};
            me.callParent([Ext.apply({
                storeId: 'StCantonB',
                proxy: {
                    type: 'ajax',
                    timeout: 0,
                    url: '../General/Consultas.php',
                    actionMethods:
                    {
                        read: 'POST'
                    },
                    extraParams:
                    {
                        Filsc: 'Canton',
                        IncludeAll: 'true'
                    },
                    reader: {
                        type: 'json',
                        root: 'Data',
                        totalProperty: 'totalcount'
                    }
                },
                fields: [
                {
                    name: 'CantonID'
                },
                {
                    name: 'Description'
                }
            ]
            }, cfg)]);
        }
    });

    var StCantonB = Ext.create('MyApp.store.StCantonB', {
        autoLoad: true
    });

    Ext.define('MyApp.store.StParroquiaB', {
        extend: 'Ext.data.Store',

        constructor: function (cfg) {
            var me = this;
            cfg = cfg || {};
            me.callParent([Ext.apply({
                storeId: 'StParroquiaB',
                proxy: {
                    type: 'ajax',
                    timeout: 0,
                    url: '../General/Consultas.php',
                    actionMethods:
                    {
                        read: 'POST'
                    },
                    extraParams:
                    {
                        Filsc: 'Parroquia',
                        IncludeAll: 'true'
                    },
                    reader: {
                        type: 'json',
                        root: 'Data',
                        totalProperty: 'totalcount'
                    }
                },
                fields: [
                {
                    name: 'ParroquiaID'
                },
                {
                    name: 'Description'
                }
            ]
            }, cfg)]);
        }
    });

    var StParroquiaB = Ext.create('MyApp.store.StParroquiaB', {
        autoLoad: true
    });

    this.cbProvinciaB = new Ext.form.ComboBox({
        store: StProvinciaB,
        id: 'cbProvinciaB',
        margin: '0 0 0 0',
        width: 220,
        fieldLabel: 'Provincia',
        labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
        labelWidth: 60,
        valueField: 'ProvinceID',
        displayField: 'Description',
        emptyText: 'Provincia',
        editable: false,
        forceSelection: true,
        queryMode: 'remote'
    });

    this.cbCantonB = new Ext.form.ComboBox({
        store: StCantonB,
        id: 'cbCantonB',
        margin: '0 0 0 10',
        width: 200,
        fieldLabel: 'Canton',
        labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
        labelWidth: 40,
        valueField: 'CantonID',
        displayField: 'Description',
        emptyText: 'Canton',
        editable: false,
        forceSelection: true,
        queryMode: 'remote',
        disabled: true
    });

    this.cbParroquiaB = new Ext.form.ComboBox({
        store: StParroquiaB,
        id: 'cbParroquiaB',
        margin: '0 0 0 10',
        width: 200,
        fieldLabel: 'Parroquia',
        labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
        labelWidth: 60,
        valueField: 'ParroquiaID',
        displayField: 'Description',
        emptyText: 'Parroquia',
        editable: false,
        forceSelection: true,
        queryMode: 'remote',
        disabled: true
    });

    this.cbProvinciaB.on('select', function (cmb, record, index) { //step 1  
        this.cbCantonB.enable();         //step 2  
        this.cbCantonB.clearValue();
        this.cbParroquiaB.clearValue();
        this.cbParroquiaB.disable();     //step 3  
        StCantonB.load({          //step 4  
            params: {
                ProvinciaID: record[0].data.ProvinceID //step 5  
            }
        });
    }, this);

    this.cbCantonB.on('select', function (cmb, record, index) { //step 1  
        this.cbParroquiaB.enable();         //step 2  
        this.cbParroquiaB.clearValue();     //step 3  
        StParroquiaB.load({          //step 4  
            params: {
                CantonID: record[0].data.CantonID //step 5  
            }
        });
    }, this);

    Ext.define('MyApp.view.ui.MyViewport', {
        extend: 'Ext.container.Viewport',

        layout: {
            type: 'fit'
        },
        initComponent: function () {
            var me = this;
            me.items = [
            {
                id: 'tabContenedor',
                xtype: 'panel',
                activeTab: 0,
                layout: {
                    type: 'border'
                },
                items: [
                    {

                        xtype: 'panel',
                        layout: {
                            type: 'fit'
                            //type: 'table'
                            //columns: 2
                        },
                        title: 'Resultado de la Busqueda',
                        region: 'center',
                        items: []
                    },
                    {
                        xtype: 'panel',
                        height: 135,
                        region: 'north',
                        dockedItems: [
                            {
                                xtype: 'toolbar',
                                dock: 'top',
                                items: [
                                    {
                                        xtype: 'buttongroup',
                                        title: '',
                                        columns: 3,
                                        layout: {
                                            columns: 3,
                                            type: 'table'
                                        },
                                        items: [
                                            {
                                                xtype: 'button',
                                                id: 'btBuscar',
                                                text: 'Buscar',
                                                handler: function () {
                                                    //Ext.getCmp('btBuscar').disable();
                                                    var dateFin = new Date(Ext.getCmp('txFechaFin').getValue());
                                                    var dateIni = new Date(Ext.getCmp('txFechaInicio').getValue());
                                                    dateFin.setHours(23);
                                                    dateFin.setMinutes(59);
                                                    dateFin.setSeconds(59);
                                                    dateIni.setHours(00);
                                                    dateIni.setMinutes(00);
                                                    dateIni.setSeconds(00);
                                                    StBusqueda.data.removeAll();
                                                    StBusqueda.load({ params: { SituacionFilsc: Ext.getCmp('cbSituacionB').getValue(),
                                                        ProvinciaFilsc: Ext.getCmp('cbProvinciaB').getValue(),
                                                        CantonFilsc: Ext.getCmp('cbCantonB').getValue(),
                                                        ParroquiaFilsc: Ext.getCmp('cbParroquiaB').getValue(),
                                                        FechaInicio: dateIni,
                                                        FechaFin: dateFin
                                                    }
                                                    });
                                                    verMap();
                                                    //Ext.getCmp('btBuscar').enable();
                                                }
                                            },
                                            {
                                                xtype: 'button',
                                                id: 'btImprimir',
                                                text: 'Detalle',
                                                handler: function () {
                                                    //VerMapaBusqueda();
                                                }
                                            }
                                        ]
                                    }
                                ]
                            }
                        ],
                        defaults: {
                            enableKeyEvents: true,
                            listeners: {
                                specialKey: function (field, el) {
                                    if (el.getKey() == Ext.EventObject.ENTER) {
                                        Ext.getCmp('btBuscar').handler.call(Ext.getCmp('btBuscar').scope);
                                    }
                                }
                            }
                        },
                        items: [
                            {
                                xtype: 'fieldset',
                                height: 100,
                                //width: 300,                                                                            
                                margin: '1 1 1 1',
                                padding: '0 3',
                                layout: {
                                    columns: 1,
                                    type: 'table'
                                },
                                title: 'Filtro de Busqueda',
                                items: [
                                    {
                                        xtype: 'fieldcontainer',
                                        height: 25,
                                        //width: 200,
                                        layout: {
                                            columns: 3,
                                            type: 'table'
                                        },
                                        items: [
                                            {
                                                xtype: 'combobox',
                                                id: 'cbSituacionB',
                                                margin: '0 0 0 0',
                                                width: 220,
                                                fieldLabel: 'Situación', //////situacion puede ser anulado, en espera, en proceso etc
                                                labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
                                                labelWidth: 60,
                                                displayField: 'Description',
                                                valueField: 'SituationInspectionID',
                                                queryMode: 'local',
                                                editable: false,
                                                //selectOnFocus: true,
                                                forceSelection: true,
                                                lazyRender: true,
                                                store: StSituacionB
                                            },
                                            {
                                                xtype: 'datefield',
                                                id: 'txFechaInicio',
                                                margin: '0 0 0 10',
                                                //height: 50,
                                                width: 135,
                                                fieldLabel: 'Desde',
                                                labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
                                                labelWidth: 40,
                                                value: new Date(),
                                                format: 'd/m/Y H:i:s',
                                                hidden: false
                                            },
                                            {
                                                xtype: 'datefield',
                                                id: 'txFechaFin',
                                                margin: '0 0 0 10',
                                                //height: 50,
                                                width: 135,
                                                fieldLabel: 'Hasta',
                                                labelStyle: 'font-familia:tahoma;font-size:10px;font-weight:bold;color:black',
                                                labelWidth: 40,
                                                value: new Date(),
                                                format: 'd/m/Y H:i:s',
                                                hidden: false
                                            }
                                        ]
                                    },
                                    {
                                        xtype: 'fieldcontainer',
                                        height: 25,
                                        layout: {
                                            type: 'table',
                                            columns: 3
                                        },
                                        items: [
                                            cbProvinciaB,
                                            cbCantonB,
                                            cbParroquiaB
                                        ]
                                    }
                                ///////////////
                                ]


                            }
                        ]
                    }
                ]
            }
        ];
            me.callParent(arguments);
        }
    })

    var f = Ext.create('MyApp.view.ui.MyViewport', {
        renderTo: Ext.getBody()

    });

    //    Ext.getCmp('btBuscar').on('click', function () {
    //        Ext.MessageBox.show({
    //            msg: 'Cargando el mapa con los registros...',
    //            progressText: 'Saving...',
    //            width: 300,
    //            wait: true,
    //            waitConfig: { interval: 200 },
    //            icon: 'ext-mb-download'
    //        });
    //        setTimeout(function () { Ext.MessageBox.hide(); }, 3000);
    //    });

    function setAllMap(val, map) {
        for (var i = 0; i < markers.length; i++) {
            if (markers[val][i] == null) continue;
            markers[val][i].setMap(map);
        }
    }

    function removeMarker(val) {
        setAllMap(val, null);

    }

    function addMarker(longitude, latitude, title, description, provincia, canton, parroquia, ubicacion, val) {
        /*var contentString = '<div id="content">' +
        '<div id="siteNotice">' +
        '</div>' +
        '<div id="bodyContent">' +
        '<p><b>' + Ext.getCmp("txDescripcion").getValue() + '</b>,  ubicado en la <b>provincia</b> de ' + Ext.getCmp('cbProvincia').getRawValue() +
        ' <b>Canton</b> ' + Ext.getCmp('cbCanton').getRawValue() + ' <b>Parroquia </b>' + Ext.getCmp('cbParroquia').getRawValue() + ', ' +
        Ext.getCmp('txUbicacion').getValue() + '</p>' +
        '</div>' +
        '</div>';*/
        markers[val] = new Array();
        infowindow[val] = new Array();
        for (i = 0; i < longitude.length; i++) {
            var contentString = '<div id="content">' +
            '<div id="siteNotice">' +
            '</div>' +
            '<div id="bodyContent">' +
            '<p><b>' + title[i] + '</b>,  ubicado en la <b>provincia</b> de ' + provincia[i] +
            ' <b>Canton</b> ' + canton[i] + ' <b>Parroquia </b>' + parroquia[i] + ', ' +
            ubicacion + '</p>' +
            '</div>' +
            '</div>';
            //var position = new google.maps.LatLng(latitude[i] * -1, longitude[i] * -1);
            var position = new google.maps.LatLng(latitude[i], longitude[i]);
            marker = new google.maps.Marker({
                title: title[i],
                map: mapa[val],
                position: position,
                animation: google.maps.Animation.DROP
            });
            mapa[val].setCenter(position);

            markers[val].push(marker);

            attachMessage(markers[val][i], contentString, val);
            //markers.show();
            /*google.maps.event.addListener(marker, 'dblclick', function (event) {
            Ext.Msg.alert('Proyecto:', title[i]);
            });*/
            /*            infowindow = new google.maps.InfoWindow({
            content: contentString
            });
            google.maps.event.addListener(marker, 'click', function (event) {
            infowindow.open(mapa[val], marker);
            // this.open(mapa[val], marker);
            });*/
        }
    }

    function attachMessage(marker, message, val) {

        var infowindow = new google.maps.InfoWindow(
                      { content: message,
                          size: new google.maps.Size(50, 50)
                      });
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(mapa[val], marker);
        });
    }

    function showMap(id, longitude, latitude, titleWin, title, description, provincia, canton, parroquia, ubicacion, val, zoom) {
        if (latitude == null || longitude == null || latitude == '' || longitude == '') {
            Ext.Msg.show({ title: '.::Mensaje del Sistema::.', msg: "Por favor verificar las coordenadas" + "<br>...Gracias!!!", buttons: Ext.Msg.OK, icon: Ext.MessageBox.WARNING });
            return;
        };
        // if (val == 1) {
        if (mapwin[val]) {
            removeMarker(val);
            addMarker(longitude, latitude, title, description, provincia, canton, parroquia, ubicacion, val);
            mapwin[val].show();
        }
        else {
            mapwin[val] = Ext.create('Ext.window.Window', {
                autoShow: true,
                layout: 'fit',
                id: id,
                title: titleWin,
                closeAction: 'hide',
                width: Ext.getCmp('tabContenedor').getSize().width,
                height: Ext.getCmp('tabContenedor').getSize().height,
                border: false,
                resizable: true,
                maximizable: true,
                x: 40 + (450 * val),
                y: 60

            });
            var center = new google.maps.LatLng(latitude[0], longitude[0]);
            var mapOptions = {
                zoom: zoom,
                center: center,
                mapTypeId: google.maps.MapTypeId.HYBRID,
                overviewMapControl: true,
                streetViewControl: true
            };
            mapa[val] = new google.maps.Map(mapwin[val].body.dom, mapOptions);
            addMarker(longitude, latitude, title, description, provincia, canton, parroquia, ubicacion, val);
        }
    }

    function VerMapaBusqueda() {

        quantity = StBusqueda.data.items.length;
        var longitude = new Array(quantity);
        var latitude = new Array(quantity);
        var title = new Array(quantity);
        var description = new Array(quantity);
        var provincia = new Array(quantity);
        var canton = new Array(quantity);
        var parroquia = new Array(quantity);
        var ubicacion = new Array(quantity);

        for (i = 0; i < quantity; i++) {
            latlon = new Array(2);
            x = parseFloat(StBusqueda.data.items[i].data.Longitude);
            y = parseFloat(StBusqueda.data.items[i].data.Latitude);
            zone = parseFloat(StBusqueda.data.items[i].data.Zone);
            UTMXYToLatLon(x, y, zone, true, latlon);
            longitude[i] = RadToDeg(latlon[1]);
            latitude[i] = RadToDeg(latlon[0]);
            title[i] = StBusqueda.data.items[i].data.Description;
            description[i] = StBusqueda.data.items[i].data.Description;
            provincia[i] = StBusqueda.data.items[i].data.Provincia;
            canton[i] = StBusqueda.data.items[i].data.Canton;
            parroquia[i] = StBusqueda.data.items[i].data.Parroquia;
            ubicacion[i] = StBusqueda.data.items[i].data.Location;

        }

        //markers[0][0] = new Arra
        //titleWin, title, mapPanel, mapa, description, provincia, canton,parroquia, ubicacion,markers
        showMap('MapProjects', longitude, latitude, 'MAPA DE LOS PROYECTOS - SENAGUA Demarcación Hidrográfica del Guayas', title, description, provincia, canton, parroquia, ubicacion, 1, 8);
    }

    var interMap = function () { VerMapaBusqueda(); };

    function verMap() {
        ref = setTimeout(interMap, 2000);
        setTimeout("clearInterval(" + ref + ")", 2200)
    };
})
