﻿function EstateWeb_Map_Control(oid) {
    this.id = oid;
    this.createUniqueID = EstateWeb_Map_Control_CreateUniqueID;
    //objects (public)
    //objects (private)
    this.mapoptions = new EstateWeb_Map_Control_MapOptions(this);
    this.markers = new EstateWeb_Map_Control_Markers(this);
    //methods
    this.load = EstateWeb_Map_Control_Load;
    this.setCenter = EstateWeb_Map_Control_SetCenter;
    this.preloadvalidation = EstateWeb_Map_Control_PreloadValidation;
    //events
    this.events = new HttpManager.Browser.eventManager();
    this.onPageDispose = EstateWeb_Map_Control_onPageDispose;
    this.onMapMoveEnd = EstateWeb_Map_Control_OnMapMoveEnd;
    this.onBrowserWindowResize = EstateWeb_Map_Control_OnBrowserWindowResize;
}

//methods
function EstateWeb_Map_Control_CreateUniqueID(id) {
    return HttpManager.Strings.Format("{0}_{1}", this.id, id);
}

//Prepares the map
function EstateWeb_Map_Control_Load() {
    if (this.preloadvalidation()) {
        if (GBrowserIsCompatible()) {
            this.mapoptions.checkSize();
            this.mapoptions.mapreference = new GMap2(HttpManager.Document.GetObject(this.mapoptions.renderToContainer));
            this.mapoptions.mapreference.setMapType(this.mapoptions.defaultMapType);
            this.mapoptions.apply();
            this.events.raiseEvent("mapload", this, null);
        }
    }
}

//mapoptions

function EstateWeb_Map_Control_MapOptions(o) {
    this.parent = o;
    this.styleDirectory = "";
    this.mapreference;
    this.renderToContainer = "";
    this.alignToContainer = "";
    this.mapLayoutContainer = "";
    this.resultsLayoutContainer = "";
    this.disabledContainer = "";
    this.defaultMapType = G_NORMAL_MAP;
    this.minimumHeight = 300;
    this.heightPadding = 0;
    this.showSmallNavigationControl = false;
    this.showLargeNavigationControl = false;
    this.enableDoubleClickZooming = true;
    this.showMapTypeControl = false;
    this.apply = EstateWeb_Map_Control_MapOptions_Apply;
    this.checkSize = EstateWeb_Map_Control_MapOptions_CheckSize;
    this.disable = EstateWeb_Map_Control_MapOptions_Disable;
    this.enable = EstateWeb_Map_Control_MapOptions_Enable;
}

function EstateWeb_Map_Control_MapOptions_Enable() {
    if (this.disabledContainer) {
        document.getElementById(this.disabledContainer).style.display = "none";
    }
}

function EstateWeb_Map_Control_MapOptions_Disable() {
    if (this.disabledContainer) {
        document.getElementById(this.disabledContainer).style.display = "block";
    }
}

function EstateWeb_Map_Control_MapOptions_Apply() {
    var o = this;
    if (this.showSmallNavigationControl) {
        this.mapreference.addControl(new GSmallMapControl());
    } else if (this.showLargeNavigationControl) {
        this.mapreference.addControl(new GLargeMapControl());
    }
    if (this.showMapTypeControl) {
        this.mapreference.addControl(new GMapTypeControl());
    }
    if (this.enableDoubleClickZooming) {
        this.mapreference.enableDoubleClickZoom();
        this.mapreference.enableContinuousZoom();
    }
    GEvent.addListener(this.mapreference, "moveend", function() {
        o.parent.events.raiseEvent("onmapmoveend", o.parent, null);
    });
    GEvent.addListener(this.mapreference, "infowindowclose", function() {
        o.parent.events.raiseEvent("onmapinfowindowclose", o.parent, null);
    });
}

function EstateWeb_Map_Control_MapOptions_CheckSize() {
    if (HttpManager.Document.GetObject(this.alignToContainer)) {
        var isize = Math.max(this.minimumHeight, HttpManager.Document.GetObject(this.alignToContainer).offsetHeight);
        HttpManager.Document.GetObject(this.renderToContainer).style.height = (isize + this.heightPadding) + "px";
    }
}

function EstateWeb_Map_Control_Markers(o) {
    this.parent = o;
    this.items = new Array();
    this.add = EstateWeb_Map_Control_Markers_Add;
    this.show = EstateWeb_Map_Control_Markers_Show;
    this.calculateCenter = EstateWeb_Map_Control_Mapping_CalculateCenter;
    this.sortLatitudeDesc = EstateWeb_Map_Control_Mapping_Sorting_SortLatitudeDesc;
    this.sortLongitudeDesc = EstateWeb_Map_Control_Mapping_Sorting_SortLongitudeDesc;
    this.geocode = EstateWeb_Map_Control_Markers_Geocode;
    this.enableDragging = false;
    /*this.removeAll = EstateWeb_Map_Control_Markers_RemoveAll;
    this.showByKey = EstateWeb_Map_Control_ShowByKey;*/
}

function EstateWeb_Map_Control_Markers_Geocode(callback, position) {
    var ogeocoder = new GClientGeocoder();
    iposition = (position ? position : 0);
    var oparent = this;
    var oitems = this.items;
    if (oitems.length > 0) {
        var oitem = oitems[iposition];
        if (oitem.requiresGeocoding()) {
            ogeocoder.getLatLng(oitem.geocodeString, function(point) {
                if (point) {
                    with (oitems[iposition]) {
                        latitude = point.lat();
                        longitude = point.lng();
                    }
                }
                if (iposition < (oitems.length - 1)) {
                    //recursive
                    oparent.geocode(callback, iposition + 1);
                } else {
                    callback();
                }
            });
        } else {
            if (iposition < (oitems.length - 1)) {
                oparent.geocode(callback, iposition + 1);
            } else {
                callback();
            }
        }
    } else {
        callback();
    }
}

function EstateWeb_Map_Control_Mapping_Sorting_SortLongitudeDesc() {
    //copy the array so we dont affect the order
    var localproperties = this.items;
    localproperties.sort(function(a, b) { return (b.longitude - a.longitude) });
    return localproperties;
}

function EstateWeb_Map_Control_Mapping_Sorting_SortLatitudeDesc() {
    //copy the array so we dont affect the order
    var localproperties = this.items;
    localproperties.sort(function(a, b) { return (b.latitude - a.latitude) });
    return localproperties;
}

function EstateWeb_Map_Control_Mapping_CalculateCenter() {
    //calculates bounds of a rectangle by getting the min/max latitude and min/max longitude
    var nlat = 0;
    var slat = 0;
    var elon = 0;
    var wlon = 0;
    var isdefault = false;

    if (this.items.length > 0) {
        var aproperties = new Array();
        try {
            aproperties = this.sortLatitudeDesc();
            nlat = aproperties[0].latitude;
            slat = aproperties[aproperties.length - 1].latitude;
            aproperties = this.sortLongitudeDesc();
            elon = aproperties[0].longitude;
            wlon = aproperties[aproperties.length - 1].longitude;
        } catch (e) {
            HttpManager.Document.Errors.add("Property Search Manager", "Unable to calculate center point from results");
            HttpManager.Document.Errors.show();
        }
    } else {
        nlat = 53.800651;
        slat = 53.800651;
        elon = -4.064941;
        wlon = -4.064941;
        isdefault = true;
    }



    return [nlat, slat, elon, wlon, isdefault];
}

function EstateWeb_Map_Control_Markers_Add(o) {
    this.items.push(o);
}

function EstateWeb_Map_Control_Markers_Show() {
    omapoptions = this.parent.mapoptions;
    var iposition = 0;
    //draw markers on the map
    for (var i = 0; i < this.items.length; i++) {
        var oitem = this.items[i];
        var opropertyMarker = new GMarker(new GLatLng(oitem.latitude, oitem.longitude), { draggable: this.enableDragging });
        omapoptions.mapreference.addOverlay(opropertyMarker);
        iposition = i;
        GEvent.addListener(opropertyMarker, "click", function() {
            omapoptions.parent.events.raiseEvent("propertymarkerclick", omapoptions.parent, { "marker": this });
        });
        GEvent.addListener(opropertyMarker, "mouseover", function() {
            omapoptions.parent.events.raiseEvent("propertymarkermouseover", omapoptions.parent, { "marker": this });
        });
        GEvent.addListener(opropertyMarker, "mouseout", function() {
            omapoptions.parent.events.raiseEvent("propertymarkermouseout", omapoptions.parent, { "marker": this });
        });
        GEvent.addListener(opropertyMarker, "dragend", function() {
            omapoptions.parent.events.raiseEvent("markerdragend", omapoptions.parent, { "marker": this });
        });
    }
}

function EstateWeb_Map_Control_SetCenter(bounds, withCorrectZoomLevel) {
    var viewWidth = HttpManager.Document.GetObject(this.mapoptions.renderToContainer).offsetWidth * 0.9;
    var viewHeight = HttpManager.Document.GetObject(this.mapoptions.renderToContainer).offsetHeight * 0.9;
    var oGLatLng = new GLatLng(((bounds[0] + bounds[1]) / 2), ((bounds[2] + bounds[3]) / 2));
    var oGLatLngBounds = new GLatLngBounds(new GLatLng(bounds[0], bounds[3]), new GLatLng(bounds[1], bounds[2]));
    var ocorrectzoomlevel = this.mapoptions.mapreference.getBoundsZoomLevel(oGLatLngBounds);
    if (bounds[4] == true) {
        ocorrectzoomlevel = 5;
    }
    this.mapoptions.mapreference.setCenter(oGLatLng, ocorrectzoomlevel);
}

//####### Error Handling ###############

function EstateWeb_Map_Control_PreloadValidation() {
    var msg = "";

    if (typeof GBrowserIsCompatible != "function") {
        HttpManager.Document.Errors.add("Mapping Manager", "Unable to find google API");
    } else if (this.mapoptions.renderToContainer.length == 0) {
        HttpManager.Document.Errors.add("Mapping Manager", "renderToContainer not set");
    } else if (!HttpManager.Document.GetObject(this.mapoptions.renderToContainer)) {
        HttpManager.Document.Errors.add("Mapping Manager", "Unable to find the object in the DOM for " + this.mapoptions.renderToContainer);
    }

    this.events.addHandler("onmapmoveend", this, this.onMapMoveEnd);
    this.events.addHandler("onmapinfowindowclose", this, this.onMapInfoWindowClose);
    HttpManager.Browser.events.addHandler("onresize", this, this.onBrowserWindowResize);

    return true;
}

function EstateWeb_Map_Control_ShowError(msg) {
    alert("EstateWeb Mapping Manager:\n\nAn Error has occured in this application.\n\n" + msg);
}

function EstateWeb_Map_Control_onPageDispose(creator, sender, eventArgs) {
    //perform any tear down - cleanup methods
    try {
        GUnload();
    } catch (e) { }
    delete creator.mapoptions.groupManager.reference;
}

function EstateWeb_Map_Control_OnMapMoveEnd(creator, sender, eventArgs) { }

function EstateWeb_Map_Control_OnBrowserWindowResize(creator, sender, eventArgs) {
    if (creator.mapoptions.mapreference) {
        creator.mapoptions.mapreference.checkResize();
        creator.mapoptions.mapreference.panTo(creator.mapoptions.mapreference.getCenter());
    }
}

//

function EstateWeb_Map_Control_PointInformation(lat, lng, geocodeS) {
    this.latitude = 0;
    this.longitude = 0;
    this.geocodeString = "";
    this.requiresGeocoding = function() {
        if (this.latitude == 0 && this.longitude == 0) {
            return true;
        }
        return false;
    }
    if (lat) {
        this.latitude = lat;
    }
    if (lng) {
        this.longitude = lng;
    }
    if (geocodeS) {
        this.geocodeString = geocodeS;
    }
}
