// status - Police Station Data is being processed.

// Constants ----------------------

var LawOrderIndex = 0;
var TrafficIndex = 1;
var WomenIndex = 2;

var CenterOfHydLat = 17.42316;
var CenterOfHydLon = 78.47463;
var CenterOfHydZoomLevel = 13;
var RadiusOFHyd = 0.0185; //0.01846648248569

// Global Variables ---------------

var map = null;
var control;
var searchShape;
//var SearchResultIcon = "<Img src='../../MapImages/poi_viewer_hover.gif'></Img>";
var SearchResultIcon = "../MapImages/poi_viewer_hover.gif";


var LOpushpinIcon = "../MapImages/PolicePin1.png"; //HPLogosm1.gif
var TrafficpushpinIcon = "../MapImages/PolicePinTraffic.png";
var WomenpushpinIcon = "../MapImages/PolicePinWomen2.png";
var ClusterPushpinIcon = "../MapImages/PolicePinmulti2.png";

var ClusterIconSpec = new VECustomIconSpecification();
ClusterIconSpec.Image = ClusterPushpinIcon;
var clusterOptions = new VEClusteringOptions();
clusterOptions.Icon = ClusterIconSpec;
clusterOptions.Callback = ClusterCallback;

function ClusterCallback(arrClusterSpec) {
    var i = 0;
    for (i = 0; i < arrClusterSpec.length; i++) {
        var clusterShape = arrClusterSpec[i].GetClusterShape();
        var subShapes = arrClusterSpec[i].Shapes
        var title = subShapes.length + " stations near here.";
        clusterShape.SetTitle(title);
        var j = 0;
        var description = "";
        for (j = 0; j < subShapes.length; j++) {
            description += subShapes[j].GetTitle() + "<br/>";
        }
        description += "Zoom in for details.";
        clusterShape.SetDescription(description);
    }
}

var StationLayers;

var PoliceStationArray;
var PoliceStationArrIndex = 0;

function PoliceStation() {
    this.Type = LawOrderIndex;  // Type. i.e LawOrder, Traffic etc.
    this.Name = "";             // Police station name.
    this.Index = 0;             // index in its layer (type)
    this.lat = 0.0;
    this.lon = 0.0;
}

// Configurable Constants ---------

var qBoxWidth = 200;

// Main functions -----------------



function GetMap() {
    // this check is required because other scripts in the Police Site trigger "OnLoad" again, but we dont want to reload the map.
    if (map == null) {
        map = new VEMap('myMap');
        map.LoadMap(new VELatLong(17.425718, 78.485685), 12, 'r', false);

        // customise the dashboard
        document.getElementById("MSVE_navAction_toggleGlyphWrapper").style.display = 'none';
        var topBar = document.getElementById("MSVE_navAction_topBar")
        topBar.innerHTML = '<div id = "searchLabelDiv" valign="center">Find Police Station: </div>'; //<input id="q" type="text" width="200px" />
        document.getElementById("qBoxDiv").style.display = "block";
        document.getElementById("q").style.width = qBoxWidth + "px";
        PostionSearchBox();
        document.getElementById("MSVE_navAction_topBackground").style.width = document.getElementById("qBoxDiv").offsetWidth + document.getElementById("searchLabelDiv").offsetWidth + 10;

        // Process Police Station Data and Show GeoRSS.
        StationLayers = new Array();
        PoliceStationArray = new Array();

        AddWomenPoliceStation(VEDataType.GeoRSS, '../MapData/WomenPS.xml');
        AddTrafficPoliceStation(VEDataType.GeoRSS, '../MapData/TrafficPS.xml');
        AddLOPoliceStation(VEDataType.GeoRSS, '../MapData/L&OPS.xml');

        // for IE - adjust hieght of vertical background.
        if (window.ActiveXObject != undefined) {
            document.getElementById("MSVE_navAction_leftBackground").style.height = '130px';
        }

        // add window OnResize event to reposition the queryBox on resize.
        if (window.attachEvent) {
            window.attachEvent("onresize", PostionSearchBox);
        } else {
            window.addEventListener("resize", PostionSearchBox, false);
        }

        map.SetCenterAndZoom(new VELatLong(CenterOfHydLat, CenterOfHydLon), CenterOfHydZoomLevel);
        LoadSuggestions();
        queryBox.focus();
    }
}


function ShowDebugAlert() {
    alert(PoliceStationArray.length + " : " + PoliceStationArrIndex + ":" + PoliceStationArray[PoliceStationArray.length - 1].Name);
}

// Positions the Search Box on top of the Dashboard.
function PostionSearchBox() {
    var qBox = document.getElementById("qBoxDiv");
    var searchLabel = document.getElementById("searchLabelDiv");
    qBox.style.position = "absolute";
    qBox.style.left = +GetAbsoluteLeft(searchLabel) + searchLabel.offsetWidth + 5;
    qBox.style.top = GetAbsoluteTop(searchLabel) + 2;
}

function AddLOPoliceStation(type, source) {
    var lawOrderLayer = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(type, source, lawOrderLayer);
    map.ImportShapeLayerData(veLayerSpec, LOPoliceStation_onFeedLoad);

    lawOrderLayer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);
}
function LOPoliceStation_onFeedLoad(feed) {
    StationLayers[LawOrderIndex] = feed;
    for (var i = 0; i < feed.GetShapeCount(); i++) {
        var shape = feed.GetShapeByIndex(i);
        var station = new PoliceStation();
        station.Index = i;
        station.Name = shape.GetTitle();
        var points = shape.GetPoints();
        station.lat = points[0].Latitude;
        station.lon = points[0].Longitude;
        station.Type = LawOrderIndex;

        PoliceStationArray[PoliceStationArrIndex++] = station;

        if (LOpushpinIcon)
            shape.SetCustomIcon(LOpushpinIcon);
    }
}

function AddTrafficPoliceStation(type, source) {
    var trafficLayer = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(type, source, trafficLayer);
    map.ImportShapeLayerData(veLayerSpec, TrafficPoliceStation_onFeedLoad);
    trafficLayer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);
}

function TrafficPoliceStation_onFeedLoad(feed) {
    StationLayers[TrafficIndex] = feed;
    for (var i = 0; i < feed.GetShapeCount(); i++) {
        var shape = feed.GetShapeByIndex(i);
        var station = new PoliceStation();
        station.Index = i;
        station.Name = shape.GetTitle();
        var points = shape.GetPoints();
        station.lat = points[0].Latitude;
        station.lon = points[0].Longitude;
        station.Type = TrafficIndex;

        PoliceStationArray[PoliceStationArrIndex++] = station;

        if (TrafficpushpinIcon)
            shape.SetCustomIcon(TrafficpushpinIcon);
    }
}

function AddWomenPoliceStation(type, source) {
    var womenLayer = new VEShapeLayer();
    var veLayerSpec = new VEShapeSourceSpecification(type, source, womenLayer);
    map.ImportShapeLayerData(veLayerSpec, WomenPoliceStation_onFeedLoad);
    womenLayer.SetClusteringConfiguration(VEClusteringType.Grid, clusterOptions);
}
function WomenPoliceStation_onFeedLoad(feed) {
    StationLayers[WomenIndex] = feed;

    for (var i = 0; i < feed.GetShapeCount(); i++) {
        var shape = feed.GetShapeByIndex(i);
        var station = new PoliceStation();
        station.Index = i;
        station.Name = shape.GetTitle();
        var points = shape.GetPoints();
        station.lat = points[0].Latitude;
        station.lon = points[0].Longitude;
        station.Type = WomenIndex;

        PoliceStationArray[PoliceStationArrIndex++] = station;

        if (WomenpushpinIcon)
            shape.SetCustomIcon(WomenpushpinIcon);
    }
}

// Suggest variables --------------

// query box
var queryBox;
// table container of suggestions.
var suggestTable;
// cell container of the suggestions.
var suggestContainer;
// current selection
var currentSelectedIndex = 0;
// total number of suggestions.
var totalNumSuggestions = 0;

var highlightColor = "#D5DFEE"; //A4BBDB";

// Zoom Level shown when we center on a police station that the user is searching for
var zoomLevel = 16;

// Suggest Functions --------------

function LoadSuggestions() {
    // query box
    queryBox = document.getElementById("q");
    // table container of suggestions.
    suggestTable = document.getElementById("suggestionsTable");
    // cell container of the suggestions.
    suggestContainer = document.getElementById("suggestionsContainer");

    // set autocomplete off
    queryBox.setAttribute("autocomplete", "off");
    queryBox["autocomplete"] = "off";

    if (window.attachEvent) {
        queryBox.attachEvent("onkeyup", ShowSuggestion);
        queryBox.attachEvent("onblur", HideSuggestion);
    } else {
        queryBox.addEventListener("onkeyup", ShowSuggestion, false);
        queryBox.addEventListener("onblur", HideSuggestion, false);
    }
}

function GetSuggestions(enteredText) {
    var suggestions = new Array();
    var index = 0;
    enteredText = enteredText.toLowerCase();
    for (i = 0; i < PoliceStationArray.length; i++) {
        //        if (PoliceStationArray[i].Name.toLowerCase().indexOf(enteredText) == 0) {
        //            suggestions[index++] = PoliceStationArray[i].Name;
        //        }
        var lowerName = PoliceStationArray[i].Name.toLowerCase();
        var ind = lowerName.indexOf(enteredText);
        if (ind < 0)
            continue;
        if (ind == 0)
            suggestions[index++] = PoliceStationArray[i].Name;
        // add to suggestion if it mathces the beginning of any of the words in the name.
        else if (lowerName[ind - 1] == ' ') {
            suggestions[index++] = PoliceStationArray[i].Name;
        }
    }
    return suggestions;
}

// event handler for keyboard entries in the query box.
function ShowSuggestion(e) {
    var key;
    if (window.event) {
        key = window.event.keyCode;
    }
    else {
        key = e.keyCode;
    }
    // up key
    if (key == 38 && totalNumSuggestions != 0) {
        if (currentSelectedIndex != -1) {
            Dehighlight(document.getElementById("Suggestion" + currentSelectedIndex));
        }
        currentSelectedIndex = (currentSelectedIndex + totalNumSuggestions - 1) % totalNumSuggestions;
        Highlight(document.getElementById("Suggestion" + currentSelectedIndex));
        queryBox.value = document.getElementById("Suggestion" + currentSelectedIndex).getElementsByTagName("TD")[0].innerHTML;
        return;
    }
    // down key
    if (key == 40 && totalNumSuggestions != 0) {
        if (currentSelectedIndex != -1) {
            Dehighlight(document.getElementById("Suggestion" + currentSelectedIndex));
        }
        currentSelectedIndex = (currentSelectedIndex + totalNumSuggestions + 1) % totalNumSuggestions;
        Highlight(document.getElementById("Suggestion" + currentSelectedIndex));
        queryBox.value = document.getElementById("Suggestion" + currentSelectedIndex).getElementsByTagName("TD")[0].innerHTML;
        return;
    }
    if (key == 13) {
        HideSuggestion();
        if (currentSelectedIndex != -1 && totalNumSuggestions != 0) {
            queryBox.value = document.getElementById("Suggestion" + currentSelectedIndex).getElementsByTagName("TD")[0].innerHTML;
            PlotStation(queryBox.value);
        }
        else {
            SearchLocation(queryBox.value);
        }
        return;
    }
    // queryBox = query box.
    if (queryBox.value == "") {
        HideSuggestion();
        return;
    }

    ShowSuggestionNew(queryBox.value);

    return true;
};

function ShowSuggestionNew(enteredText) {
    var suggestions;
    var i;
    var innerHtml = "<table width=100% cellpadding=0 cellspacing=0>";
    suggestTable.style.top = (GetAbsoluteTop(queryBox) + queryBox.offsetHeight) + "px";
    suggestTable.style.left = GetAbsoluteLeft(queryBox) + "px";
    suggestTable.style.width = queryBox.offsetWidth + "px";
    suggestTable.style.visibility = "visible";
    suggestions = GetSuggestions(enteredText);
    currentSelectedIndex = -1;
    totalNumSuggestions = suggestions.length;
    if (suggestions.length == 0) {
        HideSuggestion();
        return;
    }
    for (i = 0; i < suggestions.length; ++i) {
        innerHtml += "<tr id='Suggestion" + i + "' style='cursor: default' onmouseover='Highlight(this);' onmouseout='Dehighlight(this);' onmousedown='Select(this);'><td style='font-family: Arial; font-size:x-small;'>" + suggestions[i] + "</td></tr>"
    }
    innerHtml += "<tr><td style='font-family: Arial; font-size:xx-small;text-align: right; color: Blue'><a href='javascript:HideSuggestion();'>close</a></td></tr>";
    innerHtml += "</table>";
    suggestContainer.innerHTML = innerHtml;
    queryBox.focus();
}

function HideSuggestion() {
    suggestTable.style.visibility = "hidden";
    //queryBox.focus();
}

function Highlight(obj) {
    obj.style.backgroundColor = highlightColor;  //'#afafaf';
    currentSelectedIndex = parseInt(obj.id.replace("Suggestion", ""));
}

function Dehighlight(obj) {
    obj.style.backgroundColor = '#ffffff';
}

function Select(obj) {
    queryBox.value = obj.getElementsByTagName("TD")[0].innerHTML;
    HideSuggestion();
    PlotStation(queryBox.value);
}

function HandleSearchButton() {
    PlotStation(queryBox.value);
}

function PlotStation(name) {
    if (name == "")
        return;
    var i;
    for (i = 0; i < PoliceStationArray.length; i++) {
        if (PoliceStationArray[i].Name.toLowerCase() == name.toLowerCase()) {
            break;
        }
    }

    if (i == PoliceStationArray.length) {
        SearchLocation(name);
    }
    else {
        map.SetCenterAndZoom(new VELatLong(PoliceStationArray[i].lat, PoliceStationArray[i].lon), zoomLevel);
    }
}

function SearchLocation(text) {
    if (text == "")
        return;
    try {
        map.Find(null, text, null, null, 0, 10, true, null, true, false, FindCallback);
    }
    catch (e) { alert(e.message); }
}

function FindCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (searchShape != null) {
        map.DeleteShape(searchShape);
        searchShape = null;
    }

    if (layer == null && resultsArray == null && places == null) {
        alert("No results found in Hyderabad.");
    }
    else {
        var lat = places[0].LatLong.Latitude;
        var lon = places[0].LatLong.Longitude;

        if (GetDistance(lat, lon, CenterOfHydLat, CenterOfHydLon) > RadiusOFHyd) {
            alert("No results found in Hyderabad.");
            return;
        }
        searchShape = new VEShape(VEShapeType.Pushpin, new VELatLong(lat, lon));
        searchShape.SetCustomIcon(SearchResultIcon);
        searchShape.SetTitle('Your Search Result');
        searchShape.SetDescription(places[0].Name + "<br/><br/><hr><b>Directions: </b><a href='http://mapindia.live.com/default.aspx?v=2&FORM=LMLTCP&cp=" + lat + "~" + lon + "&style=r&lvl=17&tilt=-90&dir=0&alt=-1000&phx=0&phy=0&phscl=1&rtp=~pos." + lat + "_" + lon + "_" + places[0].Name + "&rtop=0~0~0&encType=1' target='_blank'><u>From</u></a> | <a href='http://mapindia.live.com/default.aspx?v=2&FORM=LMLTCP&cp=" + lat + "~" + lon + "&style=r&lvl=17&tilt=-90&dir=0&alt=-1000&phx=0&phy=0&phscl=1&rtp=pos." + lat + "_" + lon + "_" + places[0].Name + "&rtop=0~0~0&encType=1' target='_blank'><u>To</u></a> | <a href='http://mapindia.live.com/OneClickDirections.aspx?mkt=en-in&rtp=~pos." + lat + "_" + lon + "&FORM=LLMP' target='_blank'><u>1-Click</u></a><br/><b>Find more using </b><a href='http://mapindia.live.com' target='_blank'><u>Microsoft Maps</u></a>");
        map.AddShape(searchShape);
        map.SetCenterAndZoom(new VELatLong(lat, lon), zoomLevel);

        var lat1, lon1;

        // Find closest Police Station
        var index = -1;
        minDistance = 99999999;
        for (var i = 0; i < PoliceStationArray.length; i++) {
            lat1 = PoliceStationArray[i].lat;
            lon1 = PoliceStationArray[i].lon;
            distance = GetDistance(lat, lon, lat1, lon1);
            if (distance < minDistance) {
                minDistance = distance;
                index = i;
            }
        }
        if (index < 0 || index == PoliceStationArray.length)
            alert("Error : Closest Station Index is " + index);
        else {
            document.getElementById("debug").innerText += PoliceStationArray[index].Name;
            map.IncludePointInView(new VELatLong(PoliceStationArray[index].lat, PoliceStationArray[index].lon));
        }
    }
}

function GetDistance(lat1, lon1, lat2, lon2) {
    return (lat2 - lat1) * (lat2 - lat1) + (lon2 - lon1) * (lon2 - lon1)
}

// Helper functions ---------------

function GetAbsoluteLeft(obj) {
    var left = 0;
    if (obj == null) return left;
    while (obj.nodeName != "BODY") {
        left += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    return left;
}

function GetAbsoluteTop(obj) {
    var top = 0;
    if (obj == null) return top;
    while (obj.nodeName != "BODY") {
        top += obj.offsetTop;
        obj = obj.offsetParent;
    }
    return top;
}

