
mfbMapControl = {

    GoogleMap: null,
    MarkerTitle: '',
    Markers: [],
    MarkerIndex: 0,
    KeyboardHandler: null,
    DisplayIncidents: true,
    DisplayFireStations: false,
    DisplayZones: false,
    DisplayCFAIncidents: false,

    // start map display control click events

    toggleDisplayIncidents: function () {
        if (mfbMapControl.DisplayIncidents == true) {
            mfbMapControl.DisplayIncidents = false;
        }
        else {
            mfbMapControl.DisplayIncidents = true;
        }

        mfbMapControl.refreshMap();

        return false;
    },

    toggleDisplayFireStations: function () {
        if (mfbMapControl.DisplayFireStations == true) {
            mfbMapControl.DisplayFireStations = false;
        }
        else {
            mfbMapControl.DisplayFireStations = true;
        }

        mfbMapControl.refreshMap();

        return false;
    },

    toggleDisplayZones: function () {
        if (mfbMapControl.DisplayZones == true) {
            mfbMapControl.DisplayZones = false;
        }
        else {
            mfbMapControl.DisplayZones = true;
        }

        mfbMapControl.refreshMap();

        return false;
    },

    toggleDisplayCFAIncidents: function () {
        if (mfbMapControl.DisplayCFAIncidents == true) {
            mfbMapControl.DisplayCFAIncidents = false;
        }
        else {
            mfbMapControl.DisplayCFAIncidents = true;
        }

        mfbMapControl.refreshMap();

        return false;
    },

    // end map display control click events

    // A function to create the marker and set up the event window
    // Icons are assigned according to their type
    // Also sets the image within the info window for incidents
    createMarker: function (point, html, icontype, title, pinPrefix) {
        var gicons = [];
        //var image="<img src='/Images/mapPage/icon-alarm.jpg'/></div>";

        gicons["iconType"] = new GIcon(G_DEFAULT_ICON, "/Images/mapPage/pin-station.png");
        gicons["iconType"].image = "/Images/mapPage/pin-station.png";
        gicons["iconType"].iconSize = new GSize(28, 50);
        gicons["iconType"].shadowSize = new GSize(60, 40);
        gicons["iconType"].iconAnchor = new GPoint(14, 25);
        gicons["iconType"].infoWindowAnchor = new GPoint(12, 44);

        if (icontype == "0") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-station.png";
            icontype = "iconType";
        }
        else if (icontype == "1") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-fire.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-fire.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "2") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-fire.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-fire.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "3") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-fire.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-fire.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "4") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-accident.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-accident.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "5") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-hazzard.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-hazzard.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "6") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-alarm.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-alarm.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "10") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-alarm.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-alarm.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "17") {
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-medical.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon_medical.jpg'/></div>";
            html = html + image;
        }
        else if (icontype == "999") { //FIXME: not sure what "other" icon code is yet. 999 is temp
            gicons["iconType"].image = "/Images/mapPage/" + pinPrefix + "pin-other.png";
            icontype = "iconType";
            image = "<img src='/Images/mapPage/icon-other.jpg'/></div>";
            html = html + image;
        }

        var marker = new GMarker(point, gicons[icontype]);
        marker.title = title;

        GEvent.addListener(marker, "click", function () {

            var lat = marker.getPoint().lat();
            var lng = marker.getPoint().lng();

            mfbMapControl.GoogleMap.setCenter(new GLatLng(lat, lng));

            marker.openInfoWindowHtml(html);
        });

        mfbMapControl.Markers[mfbMapControl.MarkerIndex] = marker;
        mfbMapControl.MarkerIndex++;

        return marker;
    },

    displayMarker: function () {
        for (var i = 0; i < mfbMapControl.Markers.length; i++) {
            if (typeof (mfbMapControl.Markers[i]) != 'undefined' && mfbMapControl.MarkerTitle.length > 0) {
                if (decodeURI(mfbMapControl.Markers[i].title) == mfbMapControl.MarkerTitle) {
                    // move to point
                    var lat = mfbMapControl.Markers[i].getPoint().lat();
                    var lng = mfbMapControl.Markers[i].getPoint().lng();

                    mfbMapControl.GoogleMap.setCenter(new GLatLng(lat, lng), 14);

                    GEvent.trigger(mfbMapControl.Markers[i], "click");

                    break;
                }
            }
        }
    },
    displayMapTimeStamp: function () {
        var currentTime = new Date()
        var month = currentTime.getMonth() + 1
        var day = currentTime.getDate()
        var year = currentTime.getFullYear()
        var hours = currentTime.getHours()
        var minutes = currentTime.getMinutes()
        currentTime.getDate("dddd, mmmm dS, yyyy, h:MM:ss TT")
        document.getElementById('updatetimestamp').innerHTML = "Map generated | " + day + "/" + month + "/" + year + " " + hours + ":" + minutes
    },
    displayStationZones: function () {

        url_end = "?nocache=" + (new Date()).valueOf();

        var kml2 = new GGeoXml(" http://mfb.staging.reactive.com/kml/DistrictsAndRegions09_05_11.kml" + url_end); // + cacheFix);

        if (mfbMapControl.DisplayZones) {
            //alert("mfbMapControl.DisplayZones");
            mfbMapControl.GoogleMap.addOverlay(kml2);
        }
    },

    displayStationMarkers: function () {
        var request = GXmlHttp.create();
        var cacheFix = Date.parse(Date());

        request.open("GET", "/Xml/Station.xml?" + cacheFix, true);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                var xmlDoc = GXml.parse(request.responseText);

                // obtain the array of markers and loop through it
                var markers = xmlDoc.documentElement.getElementsByTagName("marker");

                for (var i = 0; i < markers.length; i++) {
                    // obtain the attribues of each marker
                    var lat = parseFloat(markers[i].getAttribute("lat"));
                    var lng = parseFloat(markers[i].getAttribute("lng"));
                    var title = markers[i].getAttribute("title");
                    var point = new GLatLng(lat, lng);
                    var html = GXml.value(markers[i].getElementsByTagName("html")[0]);
                    var icontype = GXml.value(markers[i].getElementsByTagName("icontype")[0]);

                    // create the marker
                    var marker = mfbMapControl.createMarker(point, html, icontype, title, '');
                    if (mfbMapControl.DisplayFireStations) {
                        mfbMapControl.GoogleMap.addOverlay(marker);
                    }

                    marker = null;
                    point = null;
                }

                if (mfbMapControl.MarkerTitle.length > 0) {
                    mfbMapControl.displayMarker();
                }
            }
        }

        request.send(null);
    },

    displayIncidentMarkers: function () {
        var request = GXmlHttp.create();
        request.open("GET", "/Xml/data.xml", true);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                var xmlDoc = GXml.parse(request.responseText);

                // obtain the array of markers and loop through it
                var markers = xmlDoc.documentElement.getElementsByTagName("marker");

                for (var i = 0; i < markers.length; i++) {
                    // obtain the attribues of each marker
                    var lat = parseFloat(markers[i].getAttribute("lat"));
                    var lng = parseFloat(markers[i].getAttribute("lng"));
                    var point = new GLatLng(lat, lng);
                    var type_desc = "" + markers[i].getAttribute("type_desc")
                    var status_desc = "" + markers[i].getAttribute("status_desc")
                    var html = "<div class='infoWindow'><h4>" + type_desc.toLowerCase() + "</h4></br><h5>" + status_desc + "</h5>";
                    var icontype = markers[i].getAttribute("type_code");

                    // create the marker
                    var marker = mfbMapControl.createMarker(point, html, icontype, '', '');

                    if (mfbMapControl.DisplayIncidents) {
                        mfbMapControl.GoogleMap.addOverlay(marker);
                    }

                    marker = null;
                    point = null;
                }
            }
        }

        request.send(null);
    },

    displayCFAIncidentMarkers: function () {
        var request = GXmlHttp.create();
        request.open("GET", "/Xml/cfa.xml", true);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                var xmlDoc = GXml.parse(request.responseText);

                // obtain the array of items and loop through it
                var items = xmlDoc.documentElement.getElementsByTagName("publish");

                for (var i = 0; i < items.length; i++) {
                    // obtain the attribues of each marker
                    if (items[i].getElementsByTagName("latitude")[0].textContent) {
                        var lat = parseFloat(items[i].getElementsByTagName("latitude")[0].textContent);
                        var lng = parseFloat(items[i].getElementsByTagName("longitude")[0].textContent);
                        var type_desc = "" + items[i].getElementsByTagName("incidentType")[0].textContent;
                        var status_desc = "" + items[i].getElementsByTagName("incidentStatus")[0].textContent;
                    }
                    else {
                        var lat = parseFloat(items[i].getElementsByTagName("latitude")[0].text);
                        var lng = parseFloat(items[i].getElementsByTagName("longitude")[0].text);
                        var type_desc = "" + items[i].getElementsByTagName("incidentType")[0].text;
                        var status_desc = "" + items[i].getElementsByTagName("incidentStatus")[0].text;
                    }
                    var point = new GLatLng(lat, lng);
                    var html = "<div class='infoWindow'><h4>" + type_desc.toLowerCase() + "</h4></br><h5>" + status_desc + "</h5>";

                    var icontype = 999;
                    switch (type_desc) {
                        case "STRUCTURE":
                            icontype = 1;
                            break;
                        case "NON STRUCTURE":
                            icontype = 1;
                            break;
                        case "GRASS":
                            icontype = 1;
                            break;
                        case "SCRUB":
                            icontype = 1;
                            break;
                        case "FOREST":
                            icontype = 1;
                            break;
                        case "WILD FIRE":
                            icontype = 1;
                            break;
                        case "HAZMAT":
                            icontype = 5;
                            break;
                        case "MVA":
                            icontype = 4;
                            break;
                        case "RESCUE":
                            icontype = 4;
                            break;
                        default:
                    }

                    // create the marker
                    var marker = mfbMapControl.createMarker(point, html, icontype, '', 'cfa-');

                    if (status_desc != 'SAFE') {
                        if (mfbMapControl.DisplayCFAIncidents) {
                            mfbMapControl.GoogleMap.addOverlay(marker);
                        }
                    }

                    marker = null;
                    point = null;
                }
            }
        }

        request.send(null);
    },

    refreshMap: function () {
        // unload google maps to reduce memory leak
        GUnload();

        mfbMapControl.Markers = [];
        mfbMapControl.GoogleMap = null;
        mfbMapControl.KeyboardHandler = null;

        // create the map
        mfbMapControl.GoogleMap = new GMap2(document.getElementById("map"));
        mfbMapControl.GoogleMap.addControl(new YSliderControl());

        mfbMapControl.KeyboardHandler = new GKeyboardHandler(mfbMapControl.GoogleMap);
        mfbMapControl.GoogleMap.enableScrollWheelZoom();
        mfbMapControl.GoogleMap.setCenter(new GLatLng(-37.814251, 144.963169), 7);
        mfbMapControl.GoogleMap.enableContinuousZoom();

        // Overwrite the getMinimumResolution() and getMaximumResolution() methods
        var mt = mfbMapControl.GoogleMap.getMapTypes();
        for (var i = 0; i < mt.length; i++) {
            mt[i].getMinimumResolution = function () { return 7; }
            mt[i].getMaximumResolution = function () { return 14; }

            if (mfbMapControl.DisplayCFAIncidents == true) {
                mfbMapControl.GoogleMap.setCenter(new GLatLng(-36.553775, 144.9646), 7);
            }
            else {
                mfbMapControl.GoogleMap.setCenter(new GLatLng(-37.814251, 144.963169), 10);
            }
        }

        mfbMapControl.displayIncidentMarkers();
        mfbMapControl.displayStationMarkers();
        mfbMapControl.displayStationZones();
        mfbMapControl.displayMapTimeStamp();
        mfbMapControl.displayCFAIncidentMarkers();
    },

    // initialize the map control	
    initialize: function () {
        if (location.hash.length > 0) {
            mfbMapControl.MarkerTitle = decodeURI(location.hash.split('/')[1]);
            mfbMapControl.DisplayFireStations = true;
            $('.mapNav2').parent().addClass('on');
        }

        var easingMethod = 'easeOutExpo';
        var durationTime = 300;

        $('.mapNav1').click(function () {
            mfbMapControl.toggleDisplayIncidents();
            if (mfbMapControl.DisplayIncidents) {
                $(this).parent().addClass('on');
                $(this).next('span.mapNavKey').slideDown({ duration: durationTime, easing: easingMethod });
            }
            else {
                $(this).parent().removeClass('on');
                $(this).next('span.mapNavKey').slideUp({ duration: durationTime, easing: easingMethod });
            }
        });

        $('.mapNav2').click(function () {
            mfbMapControl.toggleDisplayFireStations();
            if (mfbMapControl.DisplayFireStations) {
                $(this).parent().addClass('on');
                //$(this).next('span.mapNavKey').slideDown({ duration: durationTime, easing: easingMethod });
            }
            else {
                $(this).parent().removeClass('on');
                //$(this).next('span.mapNavKey').slideUp({ duration: durationTime, easing: easingMethod });
                mfbMapControl.MarkerTitle = '';
            }
        });

        $('.mapNav3').click(function () {
            mfbMapControl.toggleDisplayZones();
            if (mfbMapControl.DisplayZones) {
                $(this).parent().addClass('on');
            }
            else {
                $(this).parent().removeClass('on');
            }
        });

        $('.mapNav4').click(function () {
            mfbMapControl.toggleDisplayCFAIncidents();
            if (mfbMapControl.DisplayCFAIncidents) {
                $(this).parent().addClass('on');
                $(this).next('span.mapNavKey').slideDown({ duration: durationTime, easing: easingMethod });
            }
            else {
                $(this).parent().removeClass('on');
                $(this).next('span.mapNavKey').slideUp({ duration: durationTime, easing: easingMethod });
            }
        });

        // Turning the zones, stations and region on and off.		  
        mfbMapControl.refreshMap();

        window.setInterval("mfbMapControl.refreshMap()", 60000);
    }
}	
	
// create the map control
$(document).ready(function(){
	if (GBrowserIsCompatible())
	{
		mfbMapControl.initialize();
	}
	else
	{
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}	
});	
	
