﻿window.requestQueue = new Array();

gMap = {
    Brokers: {},
    Bounds: {},
    Container: {},
    Map: {},
    InitialZoom: 12,
    MaxDialogWidth: 20,
    NameBoxDefaultValue: "",
    // Google map registration
    MapRegistration: function(containerID, mapObject) {

        // Map object initialization
        gMap.Container = document.getElementById(containerID);
        if (!window.google) {
            gMap.NoServiceHandler(gMap.Container);
            return;
        }
        gMap.InitialZoom = mapObject.InitialZoom;
        gMap.MaxDialogWidth = mapObject.MaxDialogWidth;
        gMap.Bounds = null;
        var centerPostion = new google.maps.LatLng(52.1326330, 5.2912660);
        var myOptions = {
            zoom: gMap.InitialZoom,
            center: centerPostion,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        gMap.Map = new google.maps.Map(gMap.Container, myOptions);

        // Brokers markers initialization
        $(mapObject.Brokers).each(function() {
            gMap.addBroker(this);
            if (!gMap.Bounds) {
                gMap.Bounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(this.Marker.Latitude, this.Marker.Longitude),
                    new google.maps.LatLng(this.Marker.Latitude, this.Marker.Longitude));
            }
            else {
                // Extend map bounds according markers position
                gMap.Bounds.extend(new google.maps.LatLng(this.Marker.Latitude, this.Marker.Longitude));
            }
        });

        if ($(mapObject.Brokers).size() == 0) {
            gMap.Bounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(50.731588, 7.073364),
                    new google.maps.LatLng(53.391846, 4.096069));
        }
        else {
            gMap.Map.fitBounds(gMap.Bounds);
        }
        // Subscribe to event "bounds_changed"
        google.maps.event.addListener(gMap.Map, 'bounds_changed', function() {
            ;
            gMap.checkBounds();
        });

    },


    // no-service message initialization
    NoServiceCssClass: "",
    NoServiceMessage: "There isn't access to google map service.",
    NoServiceHandler: function(container) {
        if (gMap.NoServiceCssClass != "") {
            container.className = gMap.NoServiceCssClass;
        }
        container.innerHTML = gMap.NoServiceMessage;
    },


    // "bounds_changed" event handler
    checkBounds: function() {
        var request = function() {
        var newBounds = gMap.Map.getBounds();
            
            //new corner coordinates
            nSb = newBounds.getSouthWest().lat();
            nMc = newBounds.getSouthWest().lng();
            nSc = newBounds.getNorthEast().lat();
            nMb = newBounds.getNorthEast().lng();

            //old corner coordinates
            oSb = gMap.Bounds.getSouthWest().lat();
            oMc = gMap.Bounds.getSouthWest().lng();
            oSc = gMap.Bounds.getNorthEast().lat();
            oMb = gMap.Bounds.getNorthEast().lng();

            if (oMc == nMc && oMb == nMb && oSc == nSc && oSb == nSb) {
                return;
            }
            var name = $("#inpName").val();
            name = name == gMap.NameBoxDefaultValue ? "" : name;
            // bounds data for server request
            var postData = {
                oldBounds: {
                    M: {
                        c: oMc,
                        b: oMb
                    },
                    S: {
                        c: oSc,
                        b: oSb
                    }
                },
                newBounds: {
                    M: {
                        c: nMc,
                        b: nMb
                    },
                    S: {
                        c: nSc,
                        b: nSb
                    }
                },
                options: gMap.Options,
                name: name
            };
            //request new brokers
            $.getJSON('/Handlers/GetMoreBrokers.ashx', postData, function(data) {
                if (window.requestQueue.length > 1) {
                    while (window.requestQueue.length > 1) {
                        window.requestQueue.splice(0, 1);
                    }
                    window.requestQueue[0]();
                    return;
                }
                var table = $("table.nvmSearchResultsTable tbody");

                if (data.Code == 0) {
                    gMap.Bounds = newBounds;

                    //new brokers adding
                    $(data.Brokers).each(function() {
                        gMap.addBroker(this);
                    });
                    // brokers table reinitialization                    
                    table.empty();
                    var rows = new Array();
                    jQuery.each(gMap.Brokers, function(i, val) {
                        if (newBounds.contains(gMap.Brokers[i].marker.position)) {
                            // broker information row initialization
                            var link = "";
                            if (gMap.Brokers[i].Url != "") {
                                link = "<td><a href='http://" + gMap.Brokers[i].Url + "' target='_blank'>" + gMap.Brokers[i].Url + "</a></td>";
                            }
                            informationRow = "<tr><td width='235'><b>" + gMap.Brokers[i].Name + "</b></td><td width='235'>" +
                                    gMap.Brokers[i].Address + "<br>" + gMap.Brokers[i].Phone + "</td>" + link + "</tr>";
                            rows.push(informationRow);
                        }
                        // clear memory to prevent memory leaks
                        else {
                            gMap.Brokers[i].marker.setMap(null);
                            google.maps.event.removeListener(gMap.Brokers[i].listner)
                            delete gMap.Brokers[i].marker;
                            delete gMap.Brokers[i];
                        }
                    });
                    if (rows.length > 0) {
                        $(".searchResults").show();
                        $("#brokersCount").html("" + rows.length);
                        $(".tooManyResults").hide();
                        $(".noResults").hide();
                    }
                    else {
                        $(".searchResults").hide();
                        $(".tooManyResults").hide();
                        $(".noResults").show();
                    }
                    // add rows to brokers table randomly
                    while (rows.length > 0) {
                        var pos = Math.floor(Math.random() * (rows.length - 1));
                        table.append(rows[pos]);
                        rows.splice(pos, 1);
                    }

                }
                // Error message hanler
                if (data.Code == 1) {
                    table.empty();
                    gMap.Bounds = new google.maps.LatLngBounds(
                    new google.maps.LatLng(gMap.Map.center.Latitude, gMap.Map.center.Longitude),
                    new google.maps.LatLng(gMap.Map.center.Latitude, gMap.Map.center.Longitude));
                    // clear memory to prevent memory leaks
                    jQuery.each(gMap.Brokers, function(i, val) {
                        gMap.Brokers[i].marker.setMap(null);
                        google.maps.event.removeListener(gMap.Brokers[i].listner)
                        delete gMap.Brokers[i].marker;
                        delete gMap.Brokers[i];
                    });
                    $(".searchResults").hide();
                    $(".tooManyResults").show();
                    $(".noResults").hide();
                }
                window.requestQueue.splice(0, 1);
                if (window.requestQueue.length > 0) {
                    var queuedRequest = window.requestQueue.shift();
                    queuedRequest();
                }
            });

        }
        window.requestQueue.push(request);
        if (window.requestQueue.length == 1) {
            setTimeout(function() { request(); }, 1);
        }
    },
    addBroker: function(broker) {

        // whether brokers collection already contains this broker
        var newBroker = true;
        var currentID = broker.Marker.ID;
        if (gMap.Brokers[currentID]) {
            newBroker = false;
            return;
        };

        //new broker's marker object initialization
        if (newBroker) {

            gMap.Brokers[currentID] = broker;
            // brokers option
            var markerOptions = {
                id: broker.Marker.ID,
                map: gMap.Map,
                isLoaded: false,
                position: new google.maps.LatLng(broker.Marker.Latitude, broker.Marker.Longitude),
                longitude: broker.Marker.Longitude,
                latitude: broker.Marker.Latitude,
                iconwidth: 32,
                iconheight: 32
            };
            if (broker.Marker.Icon) {
                markerOptions["icon"] = broker.Marker.Icon;
            }
            if (broker.Marker.Shadow) {
                markerOptions["shadow"] = broker.Marker.Shadow;
            }
            if (broker.Name) {
                markerOptions["title"] = broker.Name;
            }
            if (broker.Marker.IconWidth) {
                markerOptions["iconwidth"] = broker.Marker.IconWidth;
            }
            if (broker.Marker.IconHeight) {
                markerOptions["iconheight"] = broker.Marker.IconHeight;
            }

            broker.marker = new google.maps.Marker(markerOptions);



            broker.listner = google.maps.event.addListener(broker.marker, 'click', function() {
                if (!broker.infowindow) {
                    // broker dialog window initialization
                    var title = "<h4 style='color:#4C1038'>" + broker.Name + "</h4>";
                    if (broker.Url != "") {
                        title = "<a class='nvmGooglePopupLink' href='http://" + broker.Url + "' target='_blank'>" + broker.Name + "</a>";
                    }
                    var content = "<div>" + title + "<span class='nvmGooglePopupText'>" + broker.Address + "<span></div>";

                    broker.infowindow = new google.maps.InfoWindow({ content: content, maxWidth: gMap.MaxDialogWidth });
                }
                broker.infowindow.open(gMap.Map, broker.marker);
            });
        }
    }
}

