﻿//Google map class
NG.Portal.Mix.Web.GoogleMapClass = function(curStartPoint, pageUrlWithAjaxMethods, mapPanel, directionPanel, curMapScale, markets) {
    var m_Map;
    var m_Geocoder;
    var m_PageUrlWithAjaxMethods = pageUrlWithAjaxMethods;
    var m_StartPoint = curStartPoint;
    var m_mapScale = curMapScale;
    var m_Markets = null;
    var m_Counties = null;
    var m_SearchPoint = null;
    var m_directions;
    var m_mapPanel = mapPanel;
    var m_directionPanel = directionPanel;
    var m_Bounds;
    var m_customIcon;
    var that = this;
    initialise();

    function initialise() {
        //initialise map
        initIcon();  // Use this if you will have your own icon in the map
        initMap();
        initCounties();

        if (markets == null) {
                $.ajax({
                    type: "POST",
                    url: m_PageUrlWithAjaxMethods + "/GetMarkets",
                    contentType: "application/json; charset=utf-8",
                    data: "{}",
                    success: function(response) {
                        var jsonObj = response.d;
                        showPoints(jsonObj);
                    },
                    error: function() {
                        console.log("markets were not loaded");
                    }
                });
        }
        else {
            console.log("markets already populated");
            showPoints(markets);
        }

    }

    function initIcon() {
        m_customIcon = new GIcon(G_DEFAULT_ICON)
//        m_customIcon.image = UrlBase + '/Templates/images/tree_24x23.png';
//        m_customIcon.iconSize = new GSize(24, 23);
//        m_customIcon.shadow = "";
    }

    //Basic initialisation for GoogleMap
    function initMap() {
        m_Map = new GMap2(m_mapPanel);
        //map.setMapType(G_HYBRID_MAP);
        m_Map.setCenter(m_StartPoint, m_mapScale);
        m_Map.addControl(new GLargeMapControl());
        m_Map.addControl(new GMapTypeControl());
        m_Geocoder = new GClientGeocoder();
        m_directions = new GDirections(m_Map, m_directionPanel);
        GEvent.addListener(m_directions, "error", handleErrors);
        $(window).unload(function() {
            GUnload();
        });
    }

    function initCounties() {
        if (m_Counties == null) {
            $.ajax({
                type: "POST",
                url: m_PageUrlWithAjaxMethods + "/GetCounties",
                contentType: "application/json; charset=utf-8",
                data: "{}",
                success: function(response) {
                    m_Counties = response.d;
                },
                error: function() {
                    m_Counties = null;
                }
            });
        }
        else {
            //assert: should always be null on init
        }
    }

    function handleErrors() {
        if (m_directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
            alert(getAlertMessage("G_GEO_UNKNOWN_ADDRESS"));

        else if (m_directions.getStatus().code == G_GEO_SERVER_ERROR)
            alert(getAlertMessage("G_GEO_SERVER_ERROR"));

        else if (m_directions.getStatus().code == G_GEO_MISSING_QUERY)
            alert(getAlertMessage("G_GEO_MISSING_QUERY"));

        else if (m_directions.getStatus().code == G_GEO_BAD_KEY)
            alert(getAlertMessage("G_GEO_BAD_KEY"));

        else if (m_directions.getStatus().code == G_GEO_BAD_REQUEST)
            alert(getAlertMessage("G_GEO_BAD_REQUEST"));

        else alert(getAlertMessage("G_GEO_UNOWN_ERROR"));

    }
    //Create a marker for market
    function createMarker(market) {
        if (market.Longitude == null || market.Latitude == null)
            return null;

        var markerOptions = { icon: m_customIcon };
        var marker = new GMarker(new GLatLng(market.Latitude, market.Longitude), markerOptions);
        marker.value = market.MarketId;

        //        GEvent.addListener(marker, "mouseover", function() {
        //            showName(market, marker);
        //        });

        GEvent.addListener(marker, "click", function() {
            showDescription(market, marker);
        });

        return marker;
    }

    function createMousOverEvent(market) {
    }

    function showDescription(market, marker) {
        //that.ClearDirection(false);
        if (market.Description) {
            //m_Map.openInfoWindowHtml(new GLatLng(market.Latitude, market.Longitude), market.Description);
            marker.openInfoWindowHtml(market.Description);
        }
        else if (NG.Portal.Mix.Web.CommonMethods.ShowAjax("ShowDescription")) {
            $.ajax({
                type: "POST",
                url: m_PageUrlWithAjaxMethods + "/GetMarketDescription",
                contentType: "application/json; charset=utf-8",
                data: '{"MarketID":' + market.MarketId + "}",
                success: function(response) {
                    var description = response.d; //NOTE: This function has changed in jquery.1.4.2, can remove evalJSON???
                    if (description) {
                        market.Description = description;
                        //m_Map.openInfoWindowHtml(new GLatLng(market.Latitude, market.Longitude), market.Description);
                        marker.openInfoWindowHtml(market.Description);
                    }
                    NG.Portal.Mix.Web.CommonMethods.HideAjax("ShowDescription");
                },
                error: function() {
                    NG.Portal.Mix.Web.CommonMethods.HideAjax("ShowDescription");
                }
            });
        }
    }

    function showName(market, marker) {
        if (market.Name) {
            marker.openInfoWindowHtml('<div class="shopPopup"><br/>' + market.Name + '</div>');
        }
        else {
            $.ajax({
                type: "POST",
                url: m_PageUrlWithAjaxMethods + "/GetMarketById",
                data: '{"MarketID:"' + market.MarketId + "}",
                success: function(response) {
                    var mt = response.d;
                    if (mt) {
                        market.Name = mt.Name;
                        marker.openInfoWindowHtml('<div class="shopPopup"><br/><br/>' + market.Name + '<br/><br/></div>');
                    }
                }
            });
        }
    }

    //mark all supermarkets in the map
    function showPoints(list) {
        m_Markets = list;
        for (var i in m_Markets) {
            if (i == undefined || m_Markets[i].Longitude == null || m_Markets[i].Latitude == null){
                continue;
            }
            m_Map.addOverlay(createMarker(m_Markets[i]));
        }
        m_Map.setCenter(m_StartPoint, m_mapScale);
    }

    //show found address with information popup
    this.ShowAddress = function(firstAddress, secondAddress) {
        that.ClearDirection(false);
        if (firstAddress.toLowerCase().indexOf("norway") == -1) {
            firstAddress = "Norway " + firstAddress;
        }
        if (secondAddress.toLowerCase().indexOf("norway") == -1) {
            secondAddress = "Norway " + secondAddress;
        }
        $(m_directionPanel).hide();
        m_Map.closeInfoWindow();
        m_directions.load("from: " + firstAddress + " to: " + secondAddress, { "locale": "NO" });
    }
    this.ClearDirection = function(withBounds) {
        if (m_directions) {
            if (m_directions.getNumRoutes() > 0) {
                withBounds = true;
            }
            m_directions.clear();
            $(m_directionPanel).hide();
            if (withBounds)
                m_Map.setCenter(m_StartPoint, m_mapScale);
        }
    }

    this.ToggleDirectionDiv = function() {
        if (m_directions) {
            $(m_directionPanel).toggle();
            if ($(m_directionPanel).html() != '') {
                $.scrollTo($(m_directionPanel));
            }
        }
    }

    this.SetCenterForMarket = function(marketId, curScale) {
        //alert(m_Markets);
        for (var i in m_Markets) {
            if (m_Markets[i].MarketId == marketId) {
                var curlatlng = new GLatLng(m_Markets[i].Latitude, m_Markets[i].Longitude);
                m_Map.setCenter(curlatlng, curScale);
                showDescription(m_Markets[i]);
                $.scrollTo($(m_mapPanel));
                return;
            }
        }
    }

    this.SetCenterForCounty = function(countyId, curScale) {
        //alert(m_Counties);
        for (var i in m_Counties) {
            if (m_Counties[i].CountyId == countyId) {
                var curlatlng = new GLatLng(m_Counties[i].Latitude, m_Counties[i].Longitude);
                if (!(m_Counties[i].Zoom <= 0)) {
                    curScale = m_Counties[i].Zoom;
                }
                m_Map.setCenter(curlatlng, curScale);
                $.scrollTo($(m_mapPanel));
                return;
            }
        }
    }

    this.SetCenterAndScale = function(latitude, longitude, curScale) {
        var curlatlng = new GLatLng(latitude, longitude);
        m_Map.setCenter(curlatlng, curScale);
        $.scrollTo($(m_mapPanel));
        return;
    }

    //initialise all recieved markets
    //    function initMarkets(marketArray, counter) {
    //        if (counter == marketArray.length) {
    //            for (var i in m_Markets) {
    //                m_Map.addOverlay(createMarker(m_Markets[i]));
    //            }
    //            //setBounds();
    //            return;
    //        }
    //        var market = new NG.Portal.Mix.Web.MarketClass(marketArray[counter].MarketId, marketArray[counter].Name, marketArray[counter].Address);
    //        if (m_Geocoder) {
    //            m_Geocoder.getLatLng(market.Address, function(point) {
    //                market.LatLng = point;
    //                m_Markets.push(market);
    //                counter++;
    //                initMarkets(marketArray, counter);

    //            });
    //        }
    //    }
    //get nearest market
    function getNearestMarket(point) {
        var nearestMarket;
        var minDistance = Number.MAX_VALUE;
        for (var i in m_Markets) {
            var curDist = m_Markets[i].LatLng.distanceFrom(point);
            if (curDist < minDistance) {
                minDistance = curDist;
                nearestMarket = m_Markets[i];
            }
        }
        return nearestMarket;
    }
    //    function setBounds() {
    //        // Create a bounds objects 
    //        m_Bounds = new GLatLngBounds();

    //        for (var i in m_Markets) {
    //            // Extend it to cover all markets
    //            if (m_Markets[i].Longitude == null || m_Markets[i].Latitude == null)
    //                continue;
    //            m_Bounds.extend(new GLatLng(m_Markets[i].Latitude, m_Markets[i].Longitude));
    //        }
    //        //add searched point if it is existed
    //        //        if (m_SearchPoint)
    //        //            bounds.extend(m_SearchPoint.getLatLng());

    //        // Position map at centre of bounds
    //        // and set zoom to include include them all
    //        setTimeout(showWithBounds, 1000);

    //    }
    function showWithBounds() {
        //        if (m_Bounds && m_Map) {
        //            m_Map.setCenter(m_Bounds.getCenter(), m_Map.getBoundsZoomLevel(m_Bounds));
        //        }
    }
}




