/**
 * Namespace "Gmaps"
 * @class Gmaps
 * @desc Subclass of Base
 */
Base.Gmaps = function() {
    // Variables & functions defined here are private
    var infowindow_margin = { top: 30, right: 6, bottom: 18, left: 10 };

    // google maps cache unloader
    function initGMapsUnload() {
        $(window).bind('unload', function() {
            GUnload();
        });
    }


    function initIconObj() {
        // maakt de verschillende icon objecten aan en stop ze in een object
        var icon_types = ['koop', 'nieuwbouw', 'huur', 'project', 'vestiging'];
        //var icons = {};
        $(icon_types).each(function(i, name) {
            var icon = new GIcon();
            icon.image = '/_layouts/images/vestia.branding/icons/gmap-icon-' + name + '.gif';
            icon.shadow = '/_layouts/images/vestia.branding/icons/gmap-icon-shadow.png';
            icon.iconSize = new GSize(21, 22);
            icon.shadowSize = new GSize(25, 27);
            icon.iconAnchor = new GPoint(10, 23);
            Base.Gmaps.icons[name] = icon;
        })
    }


    return {
        // Variables & functions defined here are public
        icons: {},


        addMarker: function(obj, map, latlng) {
            var marker = new GMarker(latlng, { icon: Base.Gmaps.icons[obj.type] })

            GEvent.addListener(marker, "click", function() {
                Base.Gmaps.showInfo(marker, map, obj);
            })

            map.addOverlay(marker);
            return marker;
        },


        showInfo: function(marker, map, obj) {
            var container = map.getContainer();
            $('#gmap-infowindow').remove();

            var offset = map.fromLatLngToDivPixel(marker.getLatLng());
            var html = '<div id="gmap-infowindow" class="' + obj.type + '"><div id="gmap-infowindow-close" />' + Base.Gmaps.getInfoWindowHtml(obj) + '</div>';
            $(html).appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));

            var box_left = offset.x + 15;
            var box_top = offset.y - 23;
            $('#gmap-infowindow').css({ top: box_top, left: box_left });

            if (obj.url) {
                $('#gmap-infowindow').addClass('gotlink').bind('click', function() {
                    document.location = obj.url;
                })
            }

            $('#gmap-infowindow-close').bind('click', function() {
                $('#gmap-infowindow').remove();
            })

            var zoomend = GEvent.addListener(map, 'zoomend', function() {
                $('#gmap-infowindow').remove();
                GEvent.removeListener(zoomend);
            });

            // reposition the map

            var mapNE = map.fromLatLngToDivPixel(map.getBounds().getNorthEast());
            var mapSW = map.fromLatLngToDivPixel(map.getBounds().getSouthWest());

            var box_bottom = box_top + $('#gmap-infowindow').outerHeight();
            var box_right = box_left + $('#gmap-infowindow').outerWidth();

            var moveX = moveY = 0;

            if (box_top - infowindow_margin.top < mapNE.y) { // check top
                moveY = mapNE.y - box_top + infowindow_margin.top;
            } else if (box_bottom + infowindow_margin.bottom > mapSW.y) { // check bottom
                moveY = mapSW.y - box_bottom - infowindow_margin.bottom;
            }

            if (box_right + infowindow_margin.right > mapNE.x) { // check right
                moveX = mapNE.x - box_right - infowindow_margin.right;
            }
            // check left kan niet voor komen

            if (moveX != 0 || moveY != 0) {
                map.panBy(new GSize(moveX, moveY));
            }
        },


        /**
        * built the html of a label's info window
        */
        getInfoWindowHtml: function(obj) {
            var html = '';

            switch (obj.type) {
                case 'koop':
                case 'huur':
                    html += '<div class="title">' + obj.street + '</div>'
                    html += '<div class="clearChildren">';
                    html += '<img src="' + obj.img + '" width="' + obj.img_size.width + '" height="' + obj.img_size.height + '" class="thumb" />';
                    html += '<div class="textwrapper">';
                    html += '<p>' + obj.city + '</p>';
                    html += '<p>' + obj.house + '</p>';
                    html += '<p class="price-size">' + obj.price + ' / ' + obj.size + '</p>';
                    html += '</div>';
                    break;
                case 'nieuwbouw':
                    html += '<div class="title">' + obj.house + '</div>'
                    html += '<div class="clearChildren">';
                    html += '<img src="' + obj.img + '" width="' + obj.img_size.width + '" height="' + obj.img_size.height + '" class="thumb" />';
                    html += '<div class="textwrapper">';
                    html += '<p>' + obj.city + '</p>';
                    html += '<p class="price-size">' + obj.price + '</p>';
                    html += '</div>';
                    break;
                case 'vestiging':
                    html += '<div class="title">' + obj.title + '</div>'
                    html += '<p>' + obj.street + '</p>'
                    html += '<p>' + obj.zipcode + ' &nbsp;' + obj.city + '</p>'
                    html += '<p>' + obj.businesshours + '</p>';
                    break;
                case 'project':
                    html += '<div class="title">' + obj.title + '</div>'
                    html += '<img src="' + obj.img + '" width="' + obj.img_size.width + '" height="' + obj.img_size.height + '"  />';
                    break;
            }
            return html;
        },


        addZoomControls: function(map, noscrollwheel) {
            // set min and max zoom level
            G_NORMAL_MAP.getMinimumResolution = function() { return 7 };
            G_NORMAL_MAP.getMaximumResolution = function() { return 19 };

            if (!noscrollwheel) {
                map.enableScrollWheelZoom();
            }

            var stepsize = 7;

            var zoom = $('<div class="zoom"><div class="in"></div><div class="out"></div><div class="steps"></div></div>').appendTo(map.getContainer());

            $(zoom).find('.in').bind('click', function() {
                map.zoomIn();
            })
            $(zoom).find('.out').bind('click', function() {
                map.zoomOut();
            })

            // zoom als er op de zoomsteps geclicked wordt
            $(zoom).find('.steps').bind('click', function(e) {
                var offset = $(this).offset();
                map.setZoom(G_NORMAL_MAP.getMaximumResolution() - Math.round((e.pageY - offset.top) / stepsize));
            })

            // update het rode streepje van de zoomsteps zodra er gezoomed is
            GEvent.addListener(map, "zoomend", function(old_zoom, new_zoom) {
                var posY = stepsize * (G_NORMAL_MAP.getMinimumResolution() - new_zoom);
                $(zoom).find('.steps').css('background-position', '0 ' + posY + 'px');
            });
        },

        errorHandler: function(gdir) {
            var error;

            switch (gdir.getStatus().code) {
                case G_GEO_UNKNOWN_ADDRESS:
                    error = 'Het opgegeven adres kon niet worden gevonden. Dit komt mogelijke doordat het adres relatief nieuw is of dat het adres incorrect geschreven is.';
                    break;
                case G_GEO_SERVER_ERROR:
                    error = 'Er kon geen route berekend worden, exacte reden hiervan in onbekend. Probeer het alstublieft nogmaals.';
                    break;
                case G_GEO_MISSING_QUERY:
                    error = 'The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.';
                    break;
                case G_GEO_BAD_KEY:
                    error = 'The given key is either invalid or does not match the domain for which it was given.';
                    break;
                case G_GEO_BAD_REQUEST:
                    error = 'Er kon geen route berekend worden.';
                    break;
                default:
                    error = 'Er heeft zich een onbekende fout voor gedaan. Probeer het alstublieft nogmaals.';
            }
            return error;
        },

        /**
        * create a polygon overlay
        */
        createPolygon: function(obj) {
            var polygon = new GPolygon(obj.points, '#333', 2, 0, '#333', .2, { mouseOutTolerance: 1 });
            GEvent.addListener(polygon, "mouseover", function() {
                polygon.setFillStyle({ opacity: 0 })
                polygon.setStrokeStyle({ opacity: 0.75 })
            });

            GEvent.addListener(polygon, "mouseout", function() {
                polygon.setFillStyle({ opacity: 0.2 })
                polygon.setStrokeStyle({ opacity: 0 })
            });
            return polygon;
        },

        createPolygonLabel: function(polygon, map, label) {
            //wijkaanduiding maken en tonen
            GEvent.addListener(polygon, "mouseover", function() {
                $('<div class="polygon-label">' + label + '</div>').appendTo(map.getContainer());
            });
            //wijkaanduiding verwijderen
            GEvent.addListener(polygon, "mouseout", function() {
                $(map.getContainer()).find('.polygon-label').remove();
            });
        },

        /**
        * Initialize this Class
        */
        init: function() {
            if (GBrowserIsCompatible()) {
                initGMapsUnload();
                initIconObj();
            }
        }
    };
} ();

/* Initialize this class */
Base.register(Base.Gmaps.init);
