﻿/// <reference path="jQuery/jquery-1.4.1-vsdoc.js" />

//-----------------------------------------------------------------------------
//Create map variable for use by other functions.

var map = null;
var lastZoomedPushpin = null;
var lastZoomedPushpinImg = null;
var firstLoad = true;

//-----------------------------------------------------------------------------
//Executed on page load complete, and after async postback.

function pageLoad(sender, args) {
    if (!(firstLoad)) {
        setTimeout("hideLoadingScreen()", 1000);
    }

    //Resize page elements.
    $("#myMap").height($(window).height() - 100);
    $("#IncidentList").height($("#myMap").height());

    $(window).resize(function () {
        $("#myMap").height($(window).height() - 115);
        $("#IncidentList").height($("#myMap").height());
    });

    //reload map.
    if (!(map)) {
        initMap();
    } else {
        //Delete only the incident points.
        map.GetShapeLayerByIndex(0).DeleteAllShapes();
    }

    initPushpins();

    //Set no longer first load.
    firstLoad = false;
}

//-----------------------------------------------------------------------------
//Deals with click events on Pin Points.

function mouseEventHandler(e) {
    if (e.elementID) {
        switch(map.GetShapeByID(e.elementID).Type) {
            case "Point":
                var description = map.GetShapeByID(e.elementID).GetDescription()
                var cfsnumber = (description.substr(description.indexOf(" / ") + 3));

                //Scroll!
                $("#IncidentList").scrollTo(0);

                //alert($("#" + cfsnumber).length);
                $("#" + cfsnumber + ":first").each(function () {
                    $("#IncidentList").scrollTo($(this).position().top + 16, 500);
                });

                break;
        }
    }
}

//-----------------------------------------------------------------------------
//Callback function for ward loading.

function wardSourceLoad(feed) {
    //Hide the loading screen, because ward data is loaded.
    setTimeout("hideLoadingScreen()", 500);
}

//-----------------------------------------------------------------------------
//Initializes Bing map.

function initMap() {
    //Display loading screen.
    showLoadingScreen();

    map = new VEMap("myMap");
    map.LoadMap();
    //map.LoadMap(new VELatLong(46.874012, -113.996429, 0, VEAltitudeMode.RelativeToGround), 10);

    //Load KML ward source.
    //Generate new layer to put the info on.
    var wardlayer = new VEShapeLayer()
    var wardspec = new VEShapeSourceSpecification(VEDataType.ImportXML, "http://www.co.missoula.mt.us/wards.kml", wardlayer);

    //Attach ward layer to map.
    map.ImportShapeLayerData(wardspec, wardSourceLoad, 1);

    //Attach mouse event handler.
    map.AttachEvent("onclick", mouseEventHandler);
}

//-----------------------------------------------------------------------------
//Programatically loads all pushpin objects.

function initPushpins() {
    $(function () {
        var sBtn = "";
        var now = new Date();

        resetMap();

        $.getJSON("pinpoints.ashx?startdate=" + escape($("select[privateid*=ddlRange]").val()) +
                  "&enddate=" + escape(now.getMonth() + 1 + "/" + now.getDate() + "/" + now.getFullYear()), function (data) {
            $.each(data, function (key, value) {
                //get proper button color.
                sBtn = "orange";

                if (value.Agency == "MCSO") {
                    sBtn = "green";
                }

                if (value.Agency == "MPD") {
                    sBtn = "turquoise";
                }

                //Generate shape & set props.
                var newShape = new VEShape(VEShapeType.Pushpin,
                                                   new VELatLong(value.Latitude,
                                                                 value.Longitude,
                                                                 0,
                                                                 VEAltitudeMode.RelativeToGround))

                newShape.SetCustomIcon('<img src="_images/' + sBtn + '_button.png\" />');
                newShape.SetTitle(value.Title);
                newShape.SetDescription(value.Description);

                //Add pushpin shape to map.
                map.AddShape(newShape);
            });
        });
    });
}

//-----------------------------------------------------------------------------
//To bring map to default position and zoom (approx).

function resetMap() {
    //Reset zoomed pushpin, if needed.
    resetZoomedPushpin();

    //Reset center and zoom level.
    map.SetCenterAndZoom(new VELatLong(46.874012, -113.996429, 0, VEAltitudeMode.RelativeToGround), 11);
}

//-----------------------------------------------------------------------------
//Resets the last zoomed pushpin.

function resetZoomedPushpin() {
    //Reset last pushpin, if set.
    if (lastZoomedPushpin) {
        lastZoomedPushpin.SetCustomIcon(lastZoomedPushpinImg);
    }
}

//-----------------------------------------------------------------------------
//Zooms to a specific pin point, located by custom attribute.

function zoomToPushpin(CFSNumber, ZoomLevel) {
    //Place to store our pin shape.
    var shape = null;

    //Loop all layer & shape collections.
    for (i = 0; i <= map.GetShapeLayerCount() - 1; i++) {
        var layer = map.GetShapeLayerByIndex(i);

        for (n = 0; n <= layer.GetShapeCount() - 1; n++) {
            if (layer.GetShapeByIndex(n).GetDescription().indexOf(" / " + CFSNumber) != -1) {
                shape = layer.GetShapeByIndex(n);
                break;
            }
        }
    }

    //Ok, if we found the pin, reset it's icon & zoom.
    if (shape) {
        var points = shape.GetPoints()

        if (points) {
            resetZoomedPushpin()

            //Save ref to pin before modification.
            lastZoomedPushpin = shape;
            lastZoomedPushpinImg = shape.GetCustomIcon();

            //Center and zoom the map.
            map.SetCenterAndZoom(new VELatLong(points[0].Latitude, points[0].Longitude, 0, VEAltitudeMode.Default), ZoomLevel);

            //Reset icon.
            shape.SetCustomIcon('<img src="_images/favorite.png\" />');

            //Bring to front.
            shape.SetZIndex(1001);
        }
    }
}

//-----------------------------------------------------------------------------
//Executes in the zoom in/out animation on zoom to pinpoint links.

function doZoomAnimation(me, inout) {
    $(me).each(function () {
        if (inout == "in") {
            $(this).animate({
                width: "165px"
            }, 500, "easeOutCirc");

            return false;
        } else if (inout == "out") {
            $(this).animate({
                width: "32px"
            }, 500, "easeOutCirc");

            return false;
        }
    });
}

//-----------------------------------------------------------------------------
//Print notification.

function printPop() {
    $(function () {
        $("#printPop").dialog({
            title: "Print Notification",
            modal: true,
            resizable: false,
            draggable: false,
            buttons: { "Cancel": function (event, ui) { $(this).dialog("close"); }, "Print": function (event, ui) { $(this).dialog("close"); window.print(); } },
            open: function (event, ui) { $("button").attr("style", "font-size:.7em;"); }
        });
    });
}

//-----------------------------------------------------------------------------
//Notifies .NET if loaded dynamically, that script has finished loading.

//if (Sys && Sys.Application) {
//    Sys.Application.notifyScriptLoaded();
//}
