
/**
 * On Google API Loads
 */
function initialize()
{
    Cajeros.init();

    $(window).unload(function()
    {
        GUnload();
    });

    $('#go').click(function() { Cajeros.go(); return false; });
    $('#update').click(function() { Cajeros.update(); return false; });

    if ( $('#cpostal').val() )
    {
        $('#go').click();
    }
}

var Cajeros = {

    div : null,
    map : null,

    geocoder : null,

    cicle         : null,
    circleRadio   : null,
    circleOpacity : 0.06,
    circleRadius  : null,
    circleCount   : null,

    /**
     * 0.0036 : 300 m
     * 0.0072 : 600 m
     * 1      : 1  km
     */
    radio : 0.0036,
    zoom  : 15,

    place : '',
    point : null,

    marker  : null,
    markers : [],

    init : function()
    {
        Cajeros.div = $('#map')[0];

        Cajeros.map = new google.maps.Map2(Cajeros.div);
        Cajeros.map.setCenter(new google.maps.LatLng(40.396764, -3.713379), 5);
        Cajeros.map.setUIToDefault();

        Cajeros.geocoder = new GClientGeocoder();
    },

    getPlace : function()
    {
        var pais      = $('#pais').val();
        var provincia = $('#provincia').val();
        var poblacion = $('#poblacion').val();
        var cpostal   = $('#cpostal').val();

        var place = cpostal;

        if ( poblacion && poblacion.length > 0 )
            place += ' ' + poblacion;
        if ( provincia && provincia.length > 0 )
            place += ' ' + provincia;
        if ( pais && pais.length > 0 )
            place += ' ' + pais;

        return place;
    },

    cicleDraw : function()
    {
        if ( Cajeros.circle )
            Cajeros.map.removeOverlay(Cajeros.circle);

        var center = Cajeros.marker.getPoint();
        var bounds = new GLatLngBounds();

        var circlePoints = Array();

        with ( Math )
        {
            Cajeros.radio = $('#radio').val();

            if ( 0.0018 == Cajeros.radio )
                Cajeros.circleRadius = 1;
            else if ( 0.0036 == Cajeros.radio )
                Cajeros.circleRadius = 2;
            else if ( 0.0072 == Cajeros.radio )
                Cajeros.circleRadius = 4;
            else if ( 1 == Cajeros.radio )
                Cajeros.circleRadius = 6;

            var d = Cajeros.circleRadius / 25000;

            var lat1 = ( PI / 180 ) * center.lat();
            var lng1 = ( PI / 180 ) * center.lng();

            for ( var a = 0; a < 361; a++ )
            {
                var tc = ( PI / 180 ) * a;
                var y = asin( sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc) );
                var dlng = atan2( sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y) );
                var x = ( ( lng1 - dlng + PI ) % ( 2 * PI ) ) - PI; // MOD function
                var point = new GLatLng( parseFloat( y * ( 180 / PI ) ), parseFloat( x * ( 180 / PI ) ) );

                circlePoints.push(point);
                bounds.extend(point);
            }

            Cajeros.circle = new GPolygon(circlePoints, '#0000FF', 2, 1, '#0000FF', Cajeros.circleOpacity);	// 3875D7
            Cajeros.circleBox = {
                latmin : bounds.getSouthWest().lat(),
                latmax : bounds.getNorthEast().lat(),
                lngmin : bounds.getSouthWest().lng(),
                lngmax : bounds.getNorthEast().lng()
            };

            Cajeros.map.addOverlay(Cajeros.circle);
        }
    },

    add : function( point, html )
    {
        var tinyIcon = new GIcon(G_DEFAULT_ICON);

        tinyIcon.image = root + 'theme/styles/images/marker.png';
        tinyIcon.iconSize = new GSize(12, 20);
        tinyIcon.shadowSize = new GSize(12, 20);
        tinyIcon.iconAnchor = new GPoint(6, 20);
        tinyIcon.infoWindowAnchor = new GPoint(5, 1);
        tinyIcon.shadow = false;

        var marker = new GMarker(point, {
            icon : tinyIcon
        });

        GEvent.addListener(marker, 'click', function()
        {
            marker.openInfoWindowHtml(html);
        });

        Cajeros.markers.push(marker);
        Cajeros.map.addOverlay(marker);
    },

    go : function()
    {
        Cajeros.place = Cajeros.getPlace();
        Cajeros.geocoder.getLatLng(Cajeros.place, function( point )
        {
            if ( point )
            {
                // $('div.place').css({ backgroundColor : '#eee' });
                $('input#cpostal').css({ backgroundColor : '#fff' });
                $('div#goerror').hide();

                Cajeros.point = point;
                Cajeros.reload();
            }
            else
            {
                // $('div.place').css({ backgroundColor : 'red' });
                $('input#cpostal').css({ backgroundColor : '#ffe100' });
                $('div#goerror').show();
            }
        });
    },

    update : function()
    {
        Cajeros.radio = $('#radio').val();

        Cajeros.reload();
        Cajeros.load();
    },

    reload : function()
    {
        if ( Cajeros.marker )
            Cajeros.map.removeOverlay(Cajeros.marker);

        if ( Cajeros.markers )
            Cajeros.markersHide();

        Cajeros.map.setCenter(Cajeros.point, 15);

        var tinyIcon = new GIcon(G_DEFAULT_ICON);
            tinyIcon.shadow = false;

        Cajeros.marker = new GMarker(Cajeros.point,
        {
            icon          : tinyIcon,
            draggable     : true,
            zIndexProcess : function(a, b) { return 1; }
        });

        GEvent.addListener(Cajeros.marker, 'dragstart', function() { Cajeros.map.closeInfoWindow(); });
        GEvent.addListener(Cajeros.marker, 'dragend', function()
        {
            Cajeros.marker.openInfoWindowHtml('<span style="font-size: 13px;">' + lang.cargando + '</span>');
            Cajeros.point = Cajeros.marker.getPoint();
            Cajeros.load();
        });

        Cajeros.map.addOverlay(Cajeros.marker);

        if ( Cajeros.circle )
            Cajeros.map.removeOverlay(Cajeros.circle);
    },

    load : function()
    {
        Cajeros.cicleDraw();

        if ( Cajeros.markers )
        {
            Cajeros.markersHide();
            Cajeros.markers = [];
        }

        Cajeros.map.setCenter(Cajeros.point, 15);
        Cajeros.map.closeInfoWindow();

        // $.get(root + 'xml/cajeros/' + Cajeros.point.lat() + ',' + Cajeros.point.lng() + '/' + Cajeros.radio + '/', {}, function( response )
        $.get(root + 'xml/cajeros/' + Cajeros.point.lat() + ',' + Cajeros.point.lng() + '/' + Cajeros.circleBox.latmin + ',' + Cajeros.circleBox.latmax + ',' + Cajeros.circleBox.lngmin + ',' + Cajeros.circleBox.lngmax + '/', {}, function( response )
        {
            if ( response )
            {
                $(response).find('cajero').each(function()
                {
                    var id = $(this).attr('id');

                    var codigo  = $(this).find('codigo').text();
                    var lugar   = $(this).find('lugar').text();
                    var entidad = $(this).find('entidad').text();

                    var entidadImg = entidad.replace(/ /g, '_').toString().toLowerCase();

                    var lat = $(this).find('geo').attr('lat');
                    var lng = $(this).find('geo').attr('lng');

                    var html = '<div class="tooltip"><div class="lugar">' + lugar + '</div><div class="entidad"><img src="' + root + 'theme/upload/entidades/' + entidadImg + '.png" alt="" /></div></div>';

                    //-->

                    if ( lat && lng )
                    {
                        Cajeros.add(new GLatLng(lat, lng), html);
                    }
                    else
                    {
                        Cajeros.geocoder.getLatLng(lugar, function( point )
                        {
                            if ( point )
                            {
                                $.get(
                                    root + 'xml/cajeros/' + point.lat() + ',' + point.lng() + '/' + id + '/save/'
                                );

                                Cajeros.add(point, html);
                            }
                        });
                    }
                });
            }
            else
            {
                Cajeros.marker.openInfoWindowHtml('<span style="font-size: 13px;">' + lang.sinresultados + '</span>');
            }
        });
    },

    markersHide : function()
    {
        for ( var i = 0; i < Cajeros.markers.length; i++ )
            Cajeros.map.removeOverlay(Cajeros.markers[i]);
    },

    markersShow : function()
    {
        for ( var i = 0; i < Cajeros.markers.length; i++ )
            Cajeros.map.addOverlay(Cajeros.markers[i]);
    }
};

$(function()
{
    $('select#pais').change(function()
    {
        var pais = $(this).val();

        if ( pais.length == 0 )
            return;

        $.get(root + 'xml/lugares/provincias/' + encodeURIComponent( pais.replace(/ /g, '_') ) + '/', {}, function( response )
        {
            var select = $('#provincia').empty();

            select.append('<option value="" disabled="disabled" selected="selected">' + lang.seleccionar + '</option>');
            select.append('<option value="" disabled="disabled">--</option>');

            $(response).find('lugar').each(function()
            {
                select.append('<option value="' + $(this).text() + '">' + $(this).text() + '</option>');
            });

            // $('div#provincia-container').show();
            // $('div#poblacion-container').hide();

            $('#poblacion').empty();
        });
    });

    $('select#provincia').change(function()
    {
        var provincia = $(this).val();

        if ( provincia.length == 0 )
            return;

        $.get(root + 'xml/lugares/poblaciones/' + encodeURIComponent( provincia.replace(/ /g, '_') ) + '/', {}, function( response )
        {
            var select = $('#poblacion').empty();

            select.append('<option value="" disabled="disabled" selected="selected">' + lang.seleccionar + '</option>');
            select.append('<option value="" disabled="disabled">--</option>');

            $(response).find('lugar').each(function()
            {
                select.append('<option value="' + $(this).text() + '">' + $(this).text() + '</option>');
            });

            // $('div#poblacion-container').show();
        });
    });

    $('#listar').click(function()
    {
        var poblacion = $('#poblacion').val();

        if ( !( poblacion ) )
            alert(lang.seleccionarPoblacion);
        else
        {
            window.location.href = root
                + langCurrent + '/cajeros/listado/'
                + encodeURIComponent( poblacion.replace(/ /g, '_') ) + '/';

            return false;
        }
    });
});