﻿//Maps Namespace
//=================================================================================
Maps = {}

//Click Handle Type Enum
//=================================================================================
Maps.ClickHandleTypes = {InfoWindow : "InfoWindow" , CallHandler : "CallHandler"};

Maps.Icons = {};
Maps.Icons.IconsCache = {};
Maps.Icons.IconsTypes = {
    Office     : "Office", 
    Houses      : "Houses", 
    Flats       : "Flats",
    RentFlats   : "RentFlats",
    Village     : "Village",
    Cottage     : "Cottage",
    Ground      : "Ground", 
    Kopernik   : "Kopernik", 
    Rejisser   : "Rejisser", 
    NordPark   : "NordPark", 
    AcademyLux : "AcademyLux",
    iHouses     : "iHouses",
    iMan         : "iMan"
    };
Maps.Icons.GetIcon = function(iconType){
    if(iconType == null) return null;
    if(Maps.Icons.IconsCache[iconType] == null){
        var icon = null;
        switch(iconType){
            case Maps.Icons.IconsTypes.Office:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/Office.gif";
                icon.iconSize = new GSize(21, 30);
                icon.iconAnchor = new GPoint(21, 15);
                icon.infoWindowAnchor = new GPoint(21, 15);
            break;
            case Maps.Icons.IconsTypes.AcademyLux:            
            case Maps.Icons.IconsTypes.NordPark:
            case Maps.Icons.IconsTypes.Houses:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/House.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);            
            break;
            case Maps.Icons.IconsTypes.iMan:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/IPhone/man.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);            
            break;
            case Maps.Icons.IconsTypes.iHouses:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/IPhone/house.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);            
            break;
            case Maps.Icons.IconsTypes.Rejisser:
            case Maps.Icons.IconsTypes.Flats:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/Flat.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);             
            break;       
            case Maps.Icons.IconsTypes.RentFlats:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/Flat.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);
                break;
            case Maps.Icons.IconsTypes.Cottage:   
            case Maps.Icons.IconsTypes.Village:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/Country.png";
                icon.iconSize = new GSize(36, 34);
                icon.iconAnchor = new GPoint(8, 34);
                icon.infoWindowAnchor = new GPoint(8, 34);             
            break;                         
            case Maps.Icons.IconsTypes.Kopernik:
                icon = new GIcon();
                icon.image = "/Images/MapIcons/Kopernik.gif";
                icon.iconSize = new GSize(64, 57);
                icon.iconAnchor = new GPoint(21, 15);
                icon.infoWindowAnchor = new GPoint(10, 4);            
            break;
//            case Maps.Icons.IconsTypes.AcademyLux:            
//                icon = new GIcon();
//                icon.image = "/Images/MapIcons/AcademyLux.gif";
//                icon.iconSize = new GSize(69, 52);
//                icon.iconAnchor = new GPoint(35, 52);
//                icon.infoWindowAnchor = new GPoint(35, 52);            
//            break;              
        }
        Maps.Icons.IconsCache[iconType] = icon;
    }
    return Maps.Icons.IconsCache[iconType];    
}
//Map Object Class
//=================================================================================
//options: title, clickHandleType, icon, iconType,  infoHtml, clickHandler, clickContext
Maps.MapObject = function(objectID, point, options, addressID) {
    this.ObjectID = objectID;
    try {
        this.Point = new GLatLng(point.lat, point.lon);
        if (options != null) {
            this.Title = options.title;
            this.zIndex = options.zIndex;
            //icon
            this.Icon = options.icon;
            if (this.Icon == null) this.Icon = Maps.Icons.GetIcon(options.iconType);
            //click handle
            this.ClickHandleType = options.clickHandleType;
            this.ClickHandlerInfoWindow = options.ClickHandlerInfoWindow;
            this.InfoHtml = options.infoHtml;
            this.ClickHandler = options.clickHandler;
            this.ClickContext = options.clickContext;
        }
        this.AddressID = addressID;
    }
    catch (ex) {

    }
}

//Map Class
//=================================================================================
Maps.Map = function(mapID, options) {
    this.MapObjects = new Mian.Lib.Dictionary();
    this.MapControlID = mapID;
    this.Map = null;
    this.Directions = null;
    this.CenterLat = 0,
    this.CenterLon = 0;
    this.CenterZoom = 11;
    this.AttachEvents();
    this.m_firstShow = false;
    this.Options = options;
}
Maps.Map.prototype.SetCenter = function(lat, lon, zoom){
    this.CenterLat = lat;
    this.CenterLon = lon;
    this.CenterZoom = zoom;    
}
Maps.Map.prototype.AttachEvents = function(){
    var thisObject = this;
    Mian.Lib.EventManager.Instance.AddEventHandler("DOM_Load", document, function() { thisObject.DocumentLoadHandler(); })
}
Maps.Map.prototype.DocumentLoadHandler = function() {
    this.MapControl = document.getElementById(this.MapControlID);
    if (this.MapControl != null) {
        try {
            if (GBrowserIsCompatible()) {
                this.Map = new GMap2(this.MapControl);
                if (this.Options == null || this.Options.NoMapControl == false) this.Map.addControl(new GLargeMapControl());
                if (this.Options == null || this.Options.NoMapTypeControl == false) this.Map.addControl(new GMapTypeControl());
                // this.Map.addControl(new ButtonMapControl('На карте показано 100 объектов', 'Отобразить все', function() { alert('Все'); }));
                this.Map.enableDoubleClickZoom();
                this.Map.setCenter(new GLatLng(this.CenterLat, this.CenterLon), this.CenterZoom);
                var thisObject = this;
                GEvent.addListener(this.Map, "click", function(overlay, point) { thisObject.MapClickHandler(overlay, point); });
                this.SetMarkers();
                Mian.Lib.EventManager.Instance.RaiseEvent("load", this);
            }
        } catch (e) {
            this.Hide();
        }
    }
}
Maps.Map.prototype.Show = function(){
    if(this.MapControl!=null && this.Map!=null){
        this.MapControl.style.display='block';
        if(this.m_firstShow != true) { 
            this.m_firstShow = true;
            this.Map.checkResize();
            this.Map.setCenter(new GLatLng(this.CenterLat, this.CenterLon), this.CenterZoom);
        }
    }
}
Maps.Map.prototype.Hide = function(){
    if(this.MapControl!=null){
        this.MapControl.style.display='none';
    }
}
Maps.Map.prototype.GetMarkerZIndex = function(marker){
    return  marker.MapObject.zIndex 
            ? marker.MapObject.zIndex 
            : GOverlay.getZIndex(marker.getPoint().lat());
}
Maps.Map.prototype.SetMarkers = function() {
    if (this.Map != null) {
        var mapObjects = this.MapObjects.GetValues();
        for (var index = 0; index < mapObjects.length; index++) {
            var mapObject = mapObjects[index];
            if (mapObject == null) continue;
            mapObject.marker = new GMarker(mapObject.Point, { icon: mapObject.Icon, title: mapObject.Title, zIndexProcess: this.GetMarkerZIndex });
            mapObject.marker.MapObject = mapObject; //two way links
            this.Map.addOverlay(mapObject.marker);
        }
    }
}

Maps.Map.prototype.SetMarkersVisibility = function(mapObjectIDs, propertyExtractor) {
    if (this.Map != null && mapObjectIDs != null) {
        var mapObjects = this.MapObjects.GetValues();
        var index = mapObjects.lenght;
        var dic = new Object();
        for (var indexID = 0; indexID < mapObjectIDs.length; indexID++)
            dic[mapObjectIDs[indexID]] = true;

        if (propertyExtractor == null)
            propertyExtractor = new Mian.Lib.PropertyExtractor("ObjectID");

        for (var index = 0; index < mapObjects.length; index++) {
            var mapObject = mapObjects[index];
            if (mapObject == null) continue;
            var marker = mapObject.marker;
            if (marker == null) continue;
            //            var flagFind = false;
            //            for(var indexID =0;indexID <  mapObjectIDs.length;indexID++){
            //                var mapObjectID = mapObjectIDs[indexID];
            //                if(mapObjectID == null) continue;
            //                if(mapObjectID == mapObject.ObjectID){
            //                    flagFind = true;
            //                    break;
            //                }
            //  


            if (dic[propertyExtractor.Extract(mapObject)])
                marker.show();
            else
                marker.hide();

            //if(flagFind) marker.show(); else marker.hide();
        }
    }
}
Maps.Map.prototype.ZoomToObject = function(mapObject){
    if (mapObject != null && this.Map != null) {
        this.Map.closeInfoWindow();
        //mapObject.marker.closeInfoWindow();
        this.Map.setCenter(mapObject.marker.getPoint(), 14);     
    }
}
Maps.Map.prototype.ZoomToObjectByID = function(mapObjectID) {
    var mapObject = this.MapObjects.GetValueByKey(mapObjectID);
    if (mapObject != null) {
        this.ZoomToObject(mapObject);
    }
}

Maps.Map.prototype.GetPointObjectByID = function(mapObjectID) {
    var mapObject = this.MapObjects.GetValueByKey(mapObjectID);
    if (mapObject != null) return mapObject.marker.getPoint();
}


Maps.Map.prototype.MapClickHandler = function(overlay, point) {
    if (overlay) {
        var mapObject = overlay.MapObject;
        if (mapObject != null) {
            if (mapObject.ClickHandleType == Maps.ClickHandleTypes.InfoWindow) {
                if (mapObject.ClickHandlerInfoWindow != null) {
                    var thisobject = overlay;
                    thisobject.handler = overlay.openInfoWindowHtml;
                    mapObject.ClickHandlerInfoWindow(mapObject.ObjectID, overlay);
                } else
                    overlay.openInfoWindowHtml(mapObject.InfoHtml);
            } else if (mapObject.ClickHandleType == Maps.ClickHandleTypes.CallHandler) {
                mapObject.ClickHandler(mapObject.ClickContext);
            }
        }
    } else {
        //for click on map
    }
}
Maps.Map.prototype.AddMapObject = function(mapObject){
    this.MapObjects.Add(mapObject.AddressID, mapObject);
    //this.MapObjects.Add(mapObject.ObjectID, mapObject);
}
Maps.Map.prototype.Clear = function(){
    if(this.Map!=null){
        this.Map.clearOverlays();
        this.MapObjects.Clear();
    }
}





//ButtonMapControl = function(title, text, action) {
//    this.m_title = title;
//    this.m_text = text;
//    this.m_action = action;
//}

//// Чтобы создать подкласс элемента GControl, задаем в качестве объекта-прототипа объект GControl
//ButtonMapControl.prototype = new GControl();

//// Создаем элементы DIV для каждой кнопки и размещаем их в контейнере
//// DIV. Контейнер мы вернем 
//// из функции чтобы класс Map
//// правильно его позиционировал
//// Кроме того, мы добавим его в контейнер карты
//ButtonMapControl.prototype.initialize = function(map) {
//    var container = document.createElement("div");
//    container.appendChild(document.createTextNode(this.m_title));
//    container.setAttribute("class", "map_allbutton");
//    //this.setButtonStyle_(container);
//    container.appendChild(document.createElement("br"));
//    var link = document.createElement("nobr");
//    link.innerHTML = "<p><img src='/images/MapIcons/showall.gif'></img> <span>Показать все объекты</span></p>";
//    var thisobject = this;
//    GEvent.addDomListener(link, "click", function() { thisobject.m_action(); return false; });
//    container.appendChild(link);


//    map.getContainer().appendChild(container);
//    return container;
//}

//// По умолчанию элемент управления будет расположен в левом верхнем углу карты с отступом 7 пикселов
//ButtonMapControl.prototype.getDefaultPosition = function() {
//    return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(7, 7));
//}


    