﻿var RPMap = null;
var intZoomFactor;
var strPropName;
var strToAddress, strFromAddress, strAddress;
// Initial map view

intZoomFactor = 14;
var SearchBox = "ctl00_cntTop_FromAddress_text";

function ShowDirections() {
    ResetError('lblErrorMap');
    document.getElementById("divPrint").style.display = "block";
    GetRouteMapv2(SearchBox);
}

function GetRouteMap() {
    var locations;

    var strToAddress = document.getElementById("PropHiddenAddress").value;
    var strFromAddress = document.getElementById("FromAddress").value;

    if (strFromAddress == "") {
        alert(" Please enter you address, try again!");
        document.getElementById("FromAddress").focus();
        return false;
    }

    locations = new Array(strFromAddress, strToAddress);

    var options = new VERouteOptions;

    // Otherwise what's the point?
    options.DrawRoute = true;

    // So the map doesn't change:
    options.SetBestMapView = false;

    // Call this function when map route is determined:
    options.RouteCallback = function(route) { ShowTurns(route, strFromAddress, strToAddress); }

    // Show as miles
    options.DistanceUnit = VERouteDistanceUnit.Mile;

    // Show the disambiguation dialog
    options.ShowDisambiguation = true;

    // map.GetDirections(locations, options);
    RPMap.GetDirections(locations, options);
}
function GetRouteMapv2(controlID) {
    var locations;

    var strToAddress = document.getElementById("PropHiddenAddress").value;
    var strFromAddress = document.getElementById(controlID).value;


    if (strFromAddress == "") {
        alert(" Please enter you address, try again!");
        document.getElementById(controlID).focus();
        return false;
    }

    locations = new Array(strFromAddress, strToAddress);

    var options = new VERouteOptions;

    // Otherwise what's the point?
    options.DrawRoute = true;

    // So the map doesn't change:
    options.SetBestMapView = false;

    // Call this function when map route is determined:
    options.RouteCallback = function(route) { ShowTurns(route, strFromAddress, strToAddress); }

    // Show as miles
    options.DistanceUnit = VERouteDistanceUnit.Mile;

    // Show the disambiguation dialog
    options.ShowDisambiguation = true;

    // map.GetDirections(locations, options);
    RPMap.GetDirections(locations, options);
}
function formatTurn(turnText) {
    var result = turnText;
    result = result.replace(/\bright\b/i, "<b>RIGHT</b>");
    result = result.replace(/\bleft\b/i, "<b>LEFT</b>");
    result = result.replace(/\bstraight\b/i, "<b>STRAIGHT</b>");
    return result;
}

function ShowTurns(route, strFromAddress, strToAddress) {

    var turns = "<span class='hdrOrange'>Turn by Turn</span> <span class='DriveInstruction'> <b> From: </b>  " + strFromAddress + " <br />  <b> To: </b>  " + strToAddress + " <br /> ";

    turns += "<b>Distance:</b> " + route.Distance.toFixed(1) + " miles";

    turns += "<br/><b>Time:</b> " + GetTime(route.Time) + " <br /> <br /> ";

    //    if (dirsForm.dirsType[0].checked) {
    // Unroll route and populate DIV
    var legs = route.RouteLegs;
    var leg = null;
    var turnNum = 0;  // The turn #

    // Get intermediate legs
    for (var i = 0; i < legs.length; i++) {
        // Get this leg so we don't have to derefernce multiple times
        leg = legs[i];  // Leg is a VERouteLeg object

        var legNum = i + 1;

        // Unroll each intermediate leg
        var turn = null;  // The itinerary leg
        var legDistance = null;  // The distance for this leg

        turns = turns;

        for (var j = 0; j < leg.Itinerary.Items.length; j++) {
            turnNum++;

            turn = leg.Itinerary.Items[j];  // turn is a VERouteItineraryItem object


            turns += "<div class='turnItem'><span class='turnText' style='float:left;width:450px;'> " + turnNum + ". \t" + formatTurn(turn.Text) + "</span>";

            legDistance = turn.Distance;

            // So we don't show 0.0 for the arrival
            if (legDistance > 0) {
                // Round distances to 1/10ths
                turns += "<span style='float:right;'> " + legDistance.toFixed(1) + " mi";

                // Append time if found
                //                if (turn.Time != null) {
                //                    turns += "; " + GetTime(turn.Time);
                //                }

                turns += "</span> &nbsp;</div> ";
            }
        }
        turns += "</span></div> ";
    }

    // Populate DIV with directions
    SetDirections(turns);
    //       }

}

function SetDirections(s) {
    var d = document.getElementById("directions");
    d.innerHTML = s;
}

// time is an integer representing seconds
// returns a formatted string
function GetTime(time) {
    if (time == null) {
        return ("");
    }
    if (time > 60) {                                 // if time == 100
        var seconds = time % 60;       // seconds == 40
        var minutes = time - seconds;  // minutes == 60
        minutes = minutes / 60;    // minutes == 1


        if (minutes > 60) {                                     // if minutes == 100
            var minLeft = minutes % 60;        // minLeft    == 40
            var hours = minutes - minLeft;   // hours      == 60
            hours = hours / 60;          // hours      == 1

            return (hours + "hr, " + minLeft + "min, " + seconds + "s");
        }
        else {
            return (minutes + "min, " + seconds + "s");
        }
    }
    else {
        return (time + "s");
    }
}

function ClearRouteAndDirections() {
    RPMap.DeleteRoute();
    SetDirections("");
}

// Dashboard hide & show calls
function HideDashboard() {
    RPMap.HideDashboard();
}

// This fuction search for a single location. 
function fnLocatePlaceOnMap(argLati, argLong, strMapPlaceTag, intZoomFactor) { // alert(argLati + "    " + argLong)
    if (argLati == 0 && argLong == 0) {
        alert("Mappoint is not selected in the Content Management System");
    }
    else {
        try {

            if (RPMap == null) {
                RPMap = new VEMap(strMapPlaceTag);

                RPMap.LoadMap(new VELatLong(Number(argLati), Number(argLong)), intZoomFactor, 'r', false);
                if (RPLayer == null) {
                    RPLayer = new VEShapeLayer();
                }
            }
            else {

                RPLayer.DeleteAllShapes();
            }
            makePin();

            //RPMap.HideDashboard();


        } catch (e) {
            DisplayError(e);
        }
    }
}


var RPLayer;
// This fuction search for Multi locations. Get info from XML Files
function fnLocateMultiPlaceOnMap(strMapPlaceTag, strXMLURL, intZoomFactor) {
    if (strXMLURL == null) {
        alert("strXMLURL not passed; Map Cannot Load.");
        return;
    }
    if (RPMap == null) {
        RPMap = new VEMap(strMapPlaceTag);

        RPMap.LoadMap();
    }

    if (RPLayer == null) {
        RPLayer = new VEShapeLayer();
    } else {
        RPLayer.DeleteAllShapes();
    }
    var veLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, strXMLURL, RPLayer);

    /*try{*/


    RPMap.ImportShapeLayerData(veLayerSpec, function() {
        var numShapes = RPLayer.GetShapeCount();
        var s, n, icon;
        var zoom = 13;

        if (numShapes == 1) {
            RPMap.SetZoomLevel(zoom);

            prop = RPLayer.GetShapeByIndex(0);
            if (prop.Title == "") {
                RPLayer.DeleteAllShapes();
                RPMap.SetCenterAndZoom(new VELatLong(33, -110), 4);
                return;
            }
        }
        for (var i = 0; i < numShapes; ++i) {
            s = RPLayer.GetShapeByIndex(i);

            n = i + 1;
            icon = "<div class='SmallPinStyleApartment'><span class='pinText'> " + n + " </span></div>";
            s.SetCustomIcon(icon);
        }
    }, true);
    /*} catch (e)
    {
       
    }*/
}


// This fuction search for multiple locations based on a keyword
function FindByKeyword(argKeyword) {
    ResetError('lblErrorMap');
    FindByKeywordWithErrorHandler(argKeyword, function(msg) {
        DisplayError(msg);
    });
}
function FindByKeywordWithErrorHandler(argKeyword, errorHandler) {
    ResetError('lblErrorMap');
    var strLati = document.getElementById("PropHiddenLati").value;
    var strLong = document.getElementById("PropHiddenLong").value;
    var numResults = 10; //Max num of results to plot
    var index = 0; //index into results.

    var objPropLocation = new VELatLong(Number(strLati), Number(strLong))
    // RPMap.LoadMap();
    RPMap.DeleteAllShapes();
    makePin();
    try {
        //http://msdn.microsoft.com/en-us/library/bb429645.aspx
        //VEMap.Find(what, where, findType, shapeLayer, startIndex, numberOfResults, showResults, createResults, useDefaultDisambiguation, setBestMapView, callback);
        RPMap.Find(
          argKeyword,
          objPropLocation,
          null,
          null,
          index,
          numResults,
          true,
          true,
          true,
          true,
          SearchMapCallback);
    }
    catch (e) {
        errorHandler(e.message);
    }
}
function makePin() {
    var strLati = document.getElementById("PropHiddenLati").value;
    var strLong = document.getElementById("PropHiddenLong").value;
    var strPropName = document.getElementById("PropHiddenName").value;
    var strAddress = document.getElementById("PropHiddenAddress").value;
    var strAddressHTML = document.getElementById("PropHiddenAddressHTML").value;

    var objPropLocation = new VELatLong(Number(strLati), Number(strLong))
    var pin = new VEShape(VEShapeType.Pushpin, objPropLocation);
    pin.SetTitle(strPropName);
    pin.SetDescription(strAddressHTML);
    var icon = "<div class='SmallPinStyleApartment'><span class='pinText'> &nbsp; </span></div>";
    pin.SetCustomIcon(icon);
    RPMap.AddShape(pin);
}
function SearchMapCallback(layer, resultsArray, places, hasMore, veErrorMessage) {
    if (layer != null) {
        var n = layer.GetShapeCount();
        var _searchBoxText = document.getElementById(SearchBox).value;
        if (n == 1) 
        {
            DisplayError("No Results found for search criteria: " + _searchBoxText);
        }
        else
         {
            for (
                var index = 0; index < n; index++) {
                var shape = layer.GetShapeByIndex(index);
                var icon = "<div class='SmallPinStyleSearch'><span class='pinText'> &nbsp; </span></div>";
                shape.SetCustomIcon(icon);
            }
        }
    }
    //Recreate pin...
    makePin();
    if (layer == null) {
        DisplayError(veErrorMessage);


    }
}

function FindByKeywordTextField(id, errorlbl) {
    ResetError('lblErrorMap');
    var strKeyword = document.getElementById(id).value;
    if (strKeyword.length == 0) {
        DisplayError("Please Provide Search Criteria");
    }
    else {
        document.getElementById(errorlbl).innerHTML = "";
        FindByKeywordWithErrorHandler(strKeyword, DisplayError)
    }
}

function ResetError(errorlbl) {
    document.getElementById(errorlbl).innerHTML = "";
    document.getElementById('MapCtl').style["display"] = "none";
}

function DisplayError(msg) {
    document.getElementById('MapCtl').style["display"] = "block";
    document.getElementById('lblErrorMap').innerHTML = msg;
}

function DoZoom(lvlzoom) {

    RPMap.SetZoomLevel(lvlzoom);
}
