$(document).ready( function (e) {
        // verificar el numero del buscador por id al enviar el formulario
        $('#formFindById').bind('submit',
            function (e) {
                var valor = $('#idPropiedad').attr('value').split('.');

                if (valor.length === 3) {
                    if ( !isNaN(valor[0]) && !isNaN(valor[1]) && !isNaN(valor[2]) ) {
                        return true;
                    }
                }

                if (null===ocultarErrorFormFindById) {
                    ocultarErrorFormFindById = false;
                    $('#errorFormFindById').html('Debe ingresar tres números unidos por un punto ejemplo: 11.54.21')
                        .slideDown('slow',function () {
                            ocultarErrorFormFindById = window.setTimeout( function () {
                                $('#errorFormFindById').slideUp('slow', function () {
                                    window.clearTimeout(ocultarErrorFormFindById);
                                    ocultarErrorFormFindById = null;
                                });
                            }, 6000 );
                        });
                }
                return false;
            }
        ); // FIN - verificar el numero del buscador

/******************************************************************************/
        $.rgt.set('Zonas', {
            ajax : null,
            selZona : null,
            selManzanas : null,
            btnMostrar : null,
            idZona : null,
            idManzana : null,
            colZonas : [],
            set : function (k, v) { this.colZonas[k] = v; return this; },
            get : function (k) { return this.colZonas[k]; },
            isset : function (k) { return (this.colZonas[k] === undefined) ? false : true; },
            prepare : function (selZona, selManzanas, btnMostrar) {
                this.selZona = selZona;
                this.selManzanas = selManzanas;
                this.btnMostrar = btnMostrar;
                this.selZona.bind('change', function (e) {
                    if (this.selectedIndex > 0) {
                        $.rgt.get('Zonas').cargarZona( this.options[this.selectedIndex].value );
                    }
                });
                this.selManzanas.bind('change', function (e) {
                    if (this.selectedIndex > 0) {
                        $.rgt.get('Zonas').abilitarManzana( this.options[this.selectedIndex].value  );
                    }
                });
                this.btnMostrar.bind('click', function (e) {
                    $.rgt.get('Zonas').mostrarManzana();
                });
            },
            cargarZona : function (idZona) {
                this.idZona = idZona;

                if (this.isset( idZona )) {
                    return this.actualizarManzanas( idZona );
                }

                this.selManzanas.attr('disabled', true)
                    .empty()
                    .append( $( document.createElement('option') )
                        .append( document.createTextNode('Cargando...') )
                    );
                this.selZona.attr('disabled', true);
                this.btnMostrar.attr('disabled', true);

                this.ajax = jQuery.ajax({
                    dataType: 'json',
                    url: '/ajax/getmanzanas/',
                    data: {zona: idZona, nocache : Math.random() },
                    type: 'POST',
                    contentType: 'application/x-www-form-urlencoded',
                    timeout: 6000,
                    async: true,
                    beforeSend: function () {
                    },
                    success: function (datos) {
                        var zonas = $.rgt.get('Zonas');
                        zonas.set(zonas.idZona, (datos['resultado'] || null) )
                             .actualizarManzanas();
                    },
                    error: function () {
                        $.rgt.get('Zonas').actualizarManzanas();
                    }
                });
            },
            actualizarManzanas : function () {
                if (true === this.isset(this.idZona)) {
                    if (this.colZonas[this.idZona] != null) {
                        this.selManzanas.empty()
                            .append( $( document.createElement('option') )
                                .append( document.createTextNode('seleccione') )
                                .attr('value', 0)
                            );

                        var selManzanas = this.selManzanas;
                        jQuery.map(
                            this.colZonas[this.idZona].manzanas,
                            function(manzana, key) {
                                selManzanas.append(
                                    $( document.createElement('option') )
                                        //.attr('value', manzana.id)
                                        .attr('value', key)
                                        .append( document.createTextNode(manzana.numero) )
                                );
                            }
                        );

                        this.selManzanas.attr('disabled', false);
                    } else {
                        this.selManzanas.empty()
                            .append( $( document.createElement('option') )
                                .append( document.createTextNode('Sin datos...') )
                            );
                    }
                } else {
                    this.selManzanas.empty()
                        .append( $( document.createElement('option') )
                            .append( document.createTextNode('Error...') )
                        );
                }

                this.selZona.attr('disabled', false);
            },
            abilitarManzana : function (idManzana) {
                this.idManzana = idManzana || this.idManzana;
                this.btnMostrar.attr('disabled', false);
            },
            mostrarManzana : function () {
                this.btnMostrar.attr('disabled', true);

                var zona = this.colZonas[this.idZona];

                $.rgt.get('findMapa').drag(
                    zona.manzanas[this.idManzana].latitud,
                    zona.manzanas[this.idManzana].longitud,
                    zona.manzanas[this.idManzana].poligono,
                    zona.descripcion,
                    'Zona: '+ zona.zona +' / Manzana: '+zona.manzanas[this.idManzana].numero
                );
            }
        }).get('Zonas').prepare($('#selZona'), $('#selManzanas'), $('#btnMostrar'));

        $.rgt.set('findMapa', {
            map : null,
            apiMapIsLoad : false,
            apiKey : 'ABQIAAAAAa4rFw8S_pxh8DmQAD7mEBSHv5m1x-uGKeGcvbiS4oXI4vGC_xRFnyFFPdjZqDYIfhF-z9d0T0VOMw',

            zonaContenedor : null,
            zonaTitulo : null,
            zonaMapa : null,

            confDefault : {
                latLng : [-34.95777988068559, -54.941280484199524],
                zoom : 16,
                mapType : 'G_HYBRID_MAP'
            },

            mostrar : null,

            preparar : function (zonaContenedor, zonaTitulo, cerrarMapa, zonaMapa, latLng, zoom, mapType) {
            	cerrarMapa.bind('click', function() {
                    $.rgt.get('findMapa').zonaContenedor.slideUp('slow');
                    $.rgt.get('Zonas').btnMostrar.attr('disabled', false);
                });

                this.zonaContenedor = zonaContenedor;
                this.zonaTitulo = zonaTitulo;
                this.zonaMapa = zonaMapa;

                this.confDefault = {
                    latLng : latLng || this.confDefault.latLng,
                    zoom : zoom || this.confDefault.zoom,
                    mapType : mapType || this.confDefault.mapType
                };
            },
            createMap : function () {
                if (null === this.map) {
                        if (GBrowserIsCompatible()) {
                            window.onunload = GUnload;
                            this.map = new GMap2( this.zonaMapa );
                            this.map.setCenter(
                                new GLatLng(this.confDefault.latLng[0], this.confDefault.latLng[1]),
                                this.confDefault.zoom,
                                (window[this.confDefault.mapType] || null)
                            );
                            this.map.addControl( new GOverviewMapControl() );
                            this.map.addControl( new GLargeMapControl() );
                        } else {
                            $(this.zonaMapa).html('<center>No se puede mostrar el mapa.</center>');
                            return false;
                        }
                }
                this.show();
            },
            show : function () {
                if (null!=this.map && null!=this.mostrar) {
                    this.zonaTitulo.html(this.mostrar.titulo);

                    this.map.clearOverlays();

                    if (this.mostrar.latitud != null && this.mostrar.longitud != null) {
                        this.map.panTo( new GLatLng(this.mostrar.latitud, this.mostrar.longitud) );

                        if (this.mostrar.infoHtml != null && this.mostrar.infoHtml != 'descripcion ND') {
                            var infoHtml = this.mostrar.infoHtml;
                            this.map.openInfoWindowHtml(new GLatLng(this.mostrar.latitud, this.mostrar.longitud), '<div style="width: 200px;">'+infoHtml+'</div>');
                        }
                    }

                    if (this.mostrar.poligono != null) {
                        var puntos = [];
                        for (var p in this.mostrar.poligono) {
                            puntos.push( new GLatLng(this.mostrar.poligono[p][0], this.mostrar.poligono[p][1]) );
                        }
                        var poligono = new GPolygon(puntos, '#FFE100', 3, 1, '#FFE100', 0.1);
                        this.map.addOverlay( poligono );
			GEvent.addListener(poligono, 'click', function () {
                                var findMapa = $.rgt.get('findMapa');
                                if (findMapa.mostrar.infoHtml != null && findMapa.mostrar.infoHtml != 'descripcion ND') {
                                    var infoHtml = findMapa.mostrar.infoHtml;
                                    findMapa.map.openInfoWindowHtml(new GLatLng(findMapa.mostrar.latitud, findMapa.mostrar.longitud), '<div style="width: 200px;">'+infoHtml+'</div>');
                                }
			});
                    }
                }
            },
            drag : function (latitud, longitud, poligono, infoHtml, titulo) {
                if (false === this.apiMapIsLoad) {
                    this.apiMapIsLoad = null;
                    $.getScript('http://maps.google.com/maps?file=api&v=2&key='+this.apiKey +'&async=2&callback=fnCallbackMap');
                }

                this.mostrar = {
                    latitud : latitud || null,
                    longitud : longitud || null,
                    poligono : poligono || null,
                    infoHtml : infoHtml || null,
                    titulo : titulo || null
                }

                this.zonaContenedor.slideDown('slow');
                this.zonaTitulo.html('Cargando....');

                this.show();
                return this;
            }
        }).get('findMapa').preparar($('#zonaMapa'), $('#tituloMapa'), $('#cerrarMapa'), document.getElementById('contMapa'), [-34.95777988068559, -54.941280484199524], 16, 'G_SATELLITE_MAP');

} );

function fnCallbackMap()  {
	var findMapa = $.rgt.get('findMapa');
	findMapa.apiMapIsLoad = true;
        findMapa.createMap();
}
