/// <reference path="Util.js"/>
/// <reference path="MicrosoftAjax.js"/>
/// <reference path="PortalScripts.js"/>

//MapFunctions.js

var myFlashClient;
var theDuration = 0;


function onSuccessofSetCenterPosition(result) {
    localAddress.Position.Longitude = result.Position.Longitude;
    localAddress.Position.Latitude = result.Position.Latitude;

    //    alert("onSuccessofSetCenterPosition SetCenterPosition long:" + result.Position.Longitude + " lat:" + result.Position.Latitude);
    myFlashClient.SetCenterPosition({ longitude: result.Position.Longitude, latitude: result.Position.Latitude }, 500);
}

function SetSearchedAddress() {
    //Set position of single hit
    try {
        adrOrig = document.getElementById('PortalAddressToShow');
        var adr = JSON.parse(adrOrig.value);
        if (adr != null) {
            RemoveMarkerInMap('MoaSearchMarker');
            RemoveMagnifyingGlass();
            RemoveAllMoaForms();
            RemoveInstructionMarker();

            SetCenterPosition(adrOrig.value);
            var date = new Date();

            // todo after we have new maps we can draw polylines
            if (adr.SearchPrecision == "PRECISE_STREET" || adr.SearchPrecision == "HOUSE_NUMBER_RANGE") {
                ShowPolyLines(adrOrig.value);
                AddMarkerToMap(adrOrig.value, 'MoaSearchMarker', false);
            }
            else {
                AddMarkerToMap(adrOrig.value, 'MoaSearchMarker', true);
            }

            SetZoomLevel(adr.ZoomLevelOnMap);
        }
    }
    catch (e)
        { }
}

function SetCenterPosition(theAddress) {
    var address = JSON.parse(theAddress);

    if (myFlashClient != null) {
        if (address.Position.Longitude != null && address.Position.Longitude != '0') {

            //            alert("SetCenterPosition SetCenterPosition long:" + address.Position.Longitude + " lat:" + address.Position.Latitude);

            myFlashClient.SetCenterPosition({ longitude: address.Position.Longitude,
                latitude: address.Position.Latitude
            }, 200);
        }
        else {
            try {
                var service = new Novasys.Maponair.WebContainer.MoaServices();
                service.GetPositionOfAddress(document.getElementById('PortalToken').value, address.SearchPrecision, address.Country, address.State, address.Zip, address.City, address.Street, address.HouseNumber, address.Ids, address.ZoomLevelOnMap, onSuccessofSetCenterPosition, null, null);
            }
            catch (e) {
                alert('unable to navigate to position');
            }
        }
    }
    else {
        window.status = 'SetCenterPosition-> instance of flash client is null';
    }
}

function RemoveAllRoutes() {
    if (myFlashClient != null && myFlashClient.RemoveAllRoutes != null) {
        myFlashClient.RemoveAllRoutes();
        sleep(200);
    }
}

function AddRouteToMap(routeId) {

    if (routeId) {

        //'check if route is not already on map
        if (myFlashClient == null || myFlashClient.RouteExists(routeId)) {
            return;
        }

        //remove all routes from card
        myFlashClient.RemoveAllRoutes();
        sleep(200);
        myFlashClient.RemoveAllMarkers();

        var typ = document.getElementById('PortalFlashRouteType');
        var col = document.getElementById('PortalFlashRouteColor');
        var freq = document.getElementById('PortalFlashRouteArrowFrequence');
        var trans = document.getElementById('PortalFlashRouteTransparency');

        var arrowObj = { 'type': typ.value, 'color': col.value, 'frequency': freq.value };

        //Add new Route
        var route = { 'id': routeId, 'transparency': trans.value, 'arrows': arrowObj, 'token': document.getElementById('PortalToken').value };

        myFlashClient.AddRoute(route);
    }
}

function AddRouteToMapWithPolyline(routeId, polyline) {

    if (routeId) {

        //'check if route is not already on map
        if (myFlashClient == null || myFlashClient.RouteExists(routeId)) {
            return;
        }

        //remove all routes from card
        myFlashClient.RemoveAllRoutes();
        sleep(200);
        myFlashClient.RemoveAllMarkers();

        var typ = document.getElementById('PortalFlashRouteType');
        var col = document.getElementById('PortalFlashRouteColor');
        var freq = document.getElementById('PortalFlashRouteArrowFrequence');
        var trans = document.getElementById('PortalFlashRouteTransparency');

        var arrowObj = { 'type': typ.value, 'color': col.value, 'frequency': freq.value };

        //Add new Route
        if (polyline != null && polyline != "") {
            var route = { 'id': routeId, 'transparency': trans.value, 'points': polyline, 'arrows': arrowObj, 'token': document.getElementById('PortalToken').value };
        }
        else {
            var route = { 'id': routeId, 'transparency': trans.value, 'arrows': arrowObj, 'token': document.getElementById('PortalToken').value };
        }

        myFlashClient.AddRoute(route);
    }
}



function SetZoomLevel(level) {
    if (myFlashClient != null && myFlashClient.SetZoomLevel != null) {
        myFlashClient.SetZoomLevel(level);
    }
    else {
        window.status = 'SetZoomLevel-> instance of flash client is null';
    }
}

function SetZoomLevelBySearchPrecision(precision) {
    if (!precision) { return; }

    var level = 0;

    switch (precision) {
        case "INTERPOLATED_HOUSE_NUMBER":
            level = 16;
            break;
        case "PRECISE_HOUSE_NUMBER":
            level = 16;
            break;
        case "PRECISE_STREET":
            level = 16;
            break;
        case "PRECISE_CITY":
            level = 14;
            break;

        default:
            level = 14;
    }

    if (myFlashClient != null) {
        myFlashClient.SetZoomLevel(level);
    }
}


function RemoveMarkerInMap(idOfMarker) {
    if (myFlashClient != null && myFlashClient.MarkerExists != null) {
        try {
            if (idOfMarker && myFlashClient.MarkerExists(idOfMarker)) {
                myFlashClient.RemoveMarker(idOfMarker);
            }
        }
        catch (e) {
            window.status = 'RemoveMarkerInMap-> could not remove Markers';
        }
    }
}


var localToken;
var localAddress;


function SetBounds(bounds) {
    myFlashClient.SetVisibleBounds(bounds, true);
}


function SetMinZoomLevel(minLevel) {
    if (myFlashClient.GetZoomLevel() < minLevel) {
        myFlashClient.SetZoomLevel(minLevel);
    }
}

function AddFormToMap(xmlCode, formId) {

    var theForm = { "id": formId, "type": 5, "transparency": 38, "color": 16715776, "polyline": { "points": xmlCode} };
    if (myFlashClient != null) {
        myFlashClient.AddForm(theForm);
    }
    else {
        window.status = 'AddFormToMap-> instance of flash client is null';
    }
}

function onSuccessOfShowPolyLines(result) {

    myFlashClient.RemoveAllForms();

    for (i = 0; i < result.length; i++) {
        AddFormToMap(result[i], i.toString());
    }
}

function ShowPolyLines(addr) {

    if (addr == null) {
        alert('ShowPolyLines->address is invalid');
    }

    var address = JSON.parse(addr);

    localAddress = address;
    //    localToken = token;

    SetCenterPosition(addr);

    try {
        var service = new Novasys.Maponair.WebContainer.MoaServices();
        service.GetPolyLinesOfAddress(document.getElementById('PortalToken').value, address.SearchPrecision, address.Country, address.State, address.Zip, address.City, address.Street, address.HouseNumber, address.Ids, address.ZoomLevelOnMap, onSuccessOfShowPolyLines, null, null);

    }
    catch (e) {
        window.status('unable to draw Polyline');
        //todo handle exception
    }
}

function RemoveMagnifyingGlass(theAddress) {
    if (myFlashClient != null && myFlashClient.MarkerExists != null) {
        if (myFlashClient.MarkerExists != null && myFlashClient.MarkerExists("magnifier")) {
            myFlashClient.RemoveMarker("magnifier");
        }
    }
}


function AddMagnifyingGlass(theAddress) {

    var address = JSON.parse(theAddress);

    if (myFlashClient != null) {

        if (myFlashClient.MarkerExists("magnifier")) {
            myFlashClient.RemoveMarker("magnifier");
        }

        var labelText = GetLabelOfAddress(theAddress);
        var iconType = GetIconTypeOfAddress(theAddress);

        if (iconType == "city") {
            address.Position.Latitude = address.Position.Latitude + 0.0008;
        }

        //        alert("AddMagnifyingGlass SetCenterPosition long:" + address.Position.Longitude + " lat:" + address.Position.Latitude);

        myFlashClient.SetCenterPosition({ longitude: address.Position.Longitude, latitude: address.Position.Latitude }, theDuration);

        var marker = { "id": "magnifier", "labelText": labelText, "symbolCenterX": 5, "symbolCenterY": 5, "symbolURL": baseIconUrl + "/flash/lupe.png",
            "position": { "longitude": address.Position.Longitude, "latitude": address.Position.Latitude }
        };

        setTimeout(function() { myFlashClient.AddMarker(marker); }, 600);
    }
    else {
        window.status = 'AddMagnifyingGlass-> instance of flash client is null';
    }
}



function RemoveInstructionMarker() {
    if (myFlashClient != null && myFlashClient.RemoveMarker != null && myFlashClient.MarkerExists != null) {
        if (myFlashClient.MarkerExists("MoaInstruction")) {
            myFlashClient.RemoveMarker("MoaInstruction");
        }
    }
}

function AddInstructionMarker(instruction) {

    var theInstruction = JSON.parse(instruction);

    var moaId = "MoaInstruction";

    var flashtext = CreateFlashFormattedText(theInstruction.Text);

    var marker = { "id": moaId, "labelText": flashtext, "symbolCenterX": 5, "symbolCenterY": 5, "symbolURL": baseIconUrl + "/roadbook/redCircle_50px.png",
        "position": { "longitude": theInstruction.Position.Longitude, "latitude": theInstruction.Position.Latitude }
    };

    myFlashClient.RemoveMarker(moaId);
    myFlashClient.AddMarker(marker);

    SetCenterPosition(instruction);
    SetMinZoomLevel(15);
}


function CreateFlashFormattedText(origText) {

    var maxChars = 30;

    if (origText.length < maxChars) {
        return origText;
    }

    var flashtext = "";
    var copyOfOrigtext = origText;
    var rowtext = "";
    var pos = 0;

    for (i = 0; i < origText.length / maxChars && copyOfOrigtext.length > 0; i++) {
        pos = GetPositionOfNextSpaceAfterPosition(copyOfOrigtext, maxChars);
        rowtext = copyOfOrigtext.substr(0, pos);
        flashtext += rowtext + "<br/>";
        copyOfOrigtext = copyOfOrigtext.substr(pos + 1);
    }

    return flashtext;
}

function GetPositionOfNextSpaceAfterPosition(text, position) {
    var index = position;
    for (index; index <= text.length; index++) {
        if (text.charAt(index) == " ") {
            return index;
        }
    }

    //if there was no whitespace after the postion we return the actual position
    return index;
}



function GetIconTypeOfAddress(theAddress) {
    var address = JSON.parse(theAddress);
    var iconType = "";

    if (address.Zip != null && address.Zip != "0") {
        //        if (iconType == "") {
        iconType = "city";
        //        }
    }

    if (address.City != null && address.City != "") {
        //        if (iconType == "") {
        iconType = "city";
        //        }
    }

    if (address.Street != null && address.Street != "") {
        iconType = "street";
        if (address.HouseNumber != null && address.HouseNumber != "") {
            iconType = "houseNumber";
        }
    }

    return iconType;
}

function GetLabelOfAddress(theAddress) {
    var address = JSON.parse(theAddress);
    var labelText = "";

    if (address.Street != null && address.Street != "") {
        labelText = address.Street;
        if (address.HouseNumber != null && address.HouseNumber != "") {
            labelText += " " + address.HouseNumber;
        }
        labelText += "\n";
    }

    if (address.Zip != null && address.Zip != "0") {
        labelText += address.Zip + " ";
    }

    if (address.City != null && address.City != "") {
        labelText += address.City;
    }

    return labelText;
}

function GetSymbolUrl(iconType) {
    var symbolURL = "";

    switch (iconType) {
        case "city":
            symbolURL = baseIconUrl + "/flash/star.png";
            break;
        case "street":
            symbolURL = baseIconUrl + "/flash/street.png";
            break;
        case "houseNumber":
            symbolURL = baseIconUrl + "/flash/redBall.png";
            break;
        default:
            symbolURL = "";
    }

    return symbolURL;
}


function AddMarkerToMap(theAddress, markerId, withSymbol) {
    var address = JSON.parse(theAddress);

    if (myFlashClient != null) {

        myFlashClient.SetZoomLevel(address.ZoomLevelOnMap);

        //        alert("AddMarkerToMap SetCenterPosition long:" + address.Position.Longitude + " lat:" + address.Position.Latitude);

        myFlashClient.SetCenterPosition({ longitude: address.Position.Longitude, latitude: address.Position.Latitude }, 0);

        var iconType = GetIconTypeOfAddress(theAddress);
        var symbolURL = ""
        var labelText = GetLabelOfAddress(theAddress);

        if (withSymbol) {
            symbolURL = GetSymbolUrl(iconType);
        }

        if (iconType == "city") {
            address.Position.Latitude = address.Position.Latitude + 0.0004;
        }

        //if a marker with the same id alredy exists then we remove it
        if (myFlashClient.MarkerExists(markerId)) {
            myFlashClient.RemoveMarker(markerId);
        }



        /*
        function OnRouteDemand(instanceId, args) {
        ///<summary>This an event handler when the user clicks on routing to or from in a poi</summary>
        ///<param name="instanceId">id of the flash instance</param>
        ///<param name="args">arguments including id of the flash instance</param>*/

        var mouseOverText;
//        if (document.getElementById("PortalAddRoutingToAddress").value == "true") {
//            labelText += "<div  style=\"float: left;height:15px;width:100px;\"><br /><hr /><div style=\"float: left;height:15px;width:50px;\">";
//            labelText += "<font style=\"font-family: Arial; font-size: 10px; float: left\">Route&nbsp;&nbsp;&nbsp;</font>";
//            labelText += "</div>";
//            labelText += "<div style=\"float: right;height:15px;width:50px;\">";
//            labelText += "<font style=\"font-family: Arial; font-size: 10px; float: left;color:Blue;\"><a href=\"javascript:onRouting('FROM');\">from</a> | <a href=\"javascript:onRouting('TO');\">to</a></font>";
//            labelText += "</div>"
//            labelText += "</div>";
//        }

//        var labelFormat = { "withRouteBar": "true" };


        var marker;
        if (iconType != "") {
            if (withSymbol) {
                marker = { "id": markerId, "labelText": labelText, "symbolCenterX": 5, "symbolCenterY": 5, "symbolURL": symbolURL,
                    "position": { "longitude": address.Position.Longitude, "latitude": address.Position.Latitude }
                };
            }
            else {
                marker = { "id": markerId, "labelText": labelText, "symbolCenterX": 5, "symbolCenterY": 5,
                    "position": { "longitude": address.Position.Longitude, "latitude": address.Position.Latitude }
                };
            }
        }

        setTimeout(function() { myFlashClient.AddMarker(marker); }, 600);
    }
    else {
        window.status = 'AddMarkerToMap-> instance of flash client is null';
    }
}


function RemoveAllMoaMarkers() {
    if (myFlashClient != null && myFlashClient.RemoveAllMarkers != null) {
        myFlashClient.RemoveAllMarkers();
    }
}

function RemoveAllMoaForms() {
    if (myFlashClient != null && myFlashClient.RemoveAllForms != null) {
        myFlashClient.RemoveAllForms();
    }
}


function AddMarkersOfHiddenField(idOfHiddenField) {

    //Add address marker if there is one
    var markers = document.getElementById(idOfHiddenField);

    if (markers != null && markers.value != "") {
        var mapObjects = JSON.parse(markers.value);

        for (i = 0; i < mapObjects.length; i++) {
            sleep(50);
            AddMarkerWithPosition(mapObjects[i]);
        }
    }
}

function AddMarkerWithPosition(marker) {
    var icon = "";

    var flashMarker = { "id": marker.Id, "labelText": marker.Lb, "mouseOverText": marker.Dt, "symbolCenterX": 5, "symbolCenterY": 5, "symbolURL": baseIconUrl + "/flash/VehicleState/" + marker.Ic,
        "position": { "longitude": marker.P.X, "latitude": marker.P.Y }
    };

    myFlashClient.AddMarker(flashMarker);
}

function OnFormAdded(myInstanceId, args) {
    //    alert("OnFormAdded:" + args.id);
}

// Subscribe to events
function OnMapClientLoaded(myInstanceId, args) {

    if (myFlashClient != null) {
        SetMapOptions();
        myFlashClient.EnableDrawingEvents(true);
        myFlashClient.EnableRoutingEvents(true);
        try {
            if (document.getElementById("PortalPanelRouting").className == "PortalPanelRouting") {
                myFlashClient.SetRoutingEnabled(true);
            }
        }
        catch (e) {
            myFlashClient.SetRoutingEnabled(false);
        }

        //Set start bounds of the map
        try {
            var bounds = GetBounds();

            if (bounds) {
                myFlashClient.SetVisibleBounds(bounds, true);
            }
        }
        catch (e) {
            var adrOrig = document.getElementById('PortalCenterOfMap');
            if (adrOrig != null && adrOrig.value != "") {
                var adrPos = JSON.parse(adrOrig.value);
                if (adrPos != null) {
                    if (adrPos.Longitude != null && adrPos.Longitude != '0') {
                        try {
                            //                            alert("OnMapClientLoaded SetCenterPosition long:" + adrPos.Longitude + " lat:" + adrPos.Latitude);

                            myFlashClient.SetCenterPosition({ longitude: adrPos.Longitude, latitude: adrPos.Latitude }, 300);
                        }
                        catch (e) {
                            window.status = "Can't set center of map";
                            //                            alert("OnMapClientLoaded SetCenterPosition long:7.4442 lat:46.9465");
                            myFlashClient.SetCenterPosition({ longitude: 7.4442, latitude: 46.9465 }, 0);
                        }

                    }
                }
            }
        }

        var adrOrig = document.getElementById('PortalCenterOfMap');
        if (adrOrig != null && adrOrig.value != "") {
            var adrPos = JSON.parse(adrOrig.value);
            if (adrPos != null) {
                if (adrPos.Longitude != null && adrPos.Longitude != '0') {
                    try {
                        //                        alert("OnMapClientLoaded SetCenterPosition long:" + adrPos.Longitude + " lat:" + adrPos.Latitude);

                        myFlashClient.SetCenterPosition({ longitude: adrPos.Longitude, latitude: adrPos.Latitude }, 300);
                        myFlashClient.SetZoomLevel(16);
                    }
                    catch (e) {
                        window.status = "Can't set center of map";
                        //                        alert("OnMapClientLoaded SetCenterPosition long:7.4442 lat:46.9465");
                        myFlashClient.SetCenterPosition({ longitude: 7.4442, latitude: 46.9465 }, 0);
                    }

                }
            }
        }

        myFlashClient.ShowMap();
        //alert("OnMapClientLoaded->lang:" + document.getElementById("PortalFlashLanguage").value);
        SetFlashLanguage(document.getElementById("PortalFlashLanguage").value);


        AddMarkersOfHiddenField("PortalStaticMarkers");

        //Set searched address passed by url
        SetSearchedAddress();

        if (document.getElementById("PortalShowInitialRoute").value == "true") {
            var routeId = document.getElementById('PortalRouteId').value;
            RemoveMarkerInMap('MoaSearchMarker');
            RemoveMagnifyingGlass();
            RemoveAllMoaForms();
            RemoveAllRoutes();
            RemoveInstructionMarker();

            var token = document.getElementById('PortalToken').value;

            var polyLine = document.getElementById('PortalPolyLine').value;

            //AddRouteToMap(routeId);
            AddRouteToMapWithPolyline(routeId, polyLine);

            //__doPostBack("PortalButtonGetRoadBook");
        }
    }
    else {
        window.status = 'OnMapClientLoaded-> instance of flash client is null';
    }
}

function SetMapOptions() {
    //read map objects
    var mapObj = document.getElementById("PortalMapObjects");
    if (mapObj != null) {
        var theMapObj = JSON.parse(mapObj.value);
    }

    //Set Minimap visibility
    if (theMapObj.Hm != null) {
        myFlashClient.SetWidgetVisible("OVERVIEW", !theMapObj.Hm);
    }

    //Set Poi chooser visibility
    if (theMapObj.Hp != null) {
        myFlashClient.SetWidgetVisible("POICHOOSER", !theMapObj.Hp);
    }

    //Set toolbar visibility
    if (theMapObj.Ht != null) {
        myFlashClient.SetWidgetVisible("TOOLBAR", !theMapObj.Ht);
    }
}


function OnError(instanceId, errorObject) {
    try {
        window.status = instanceId + ' : ' + errorObject.time + ' : ' + errorObject.className + '.' + errorObject.functionName + '() : ' + errorObject.message;
    }
    catch (e) {
        //empty catch because of crossdomain problems
    }
}

function OnMapClick(myInstanceId, args) {

    CloseAllSelectionPanels();
}


function LoadClient(token) {
    try {
        //myFlashClient = LoadMapClient(token, 'Mercator', 'flashDiv', false);
        myFlashClient = LoadMapClient(token, 'NOVASYS_ROADMAP_MERCATOR', 'flashDiv', false);
        //        myFlashClient = LoadMapClient('1070', 'Mercator', 'flashDiv', false);
    }
    catch (e) {
        alert('javascript for Mapclient is missing' + '->' + e.message);
    }
}


function SetFlashLanguage(language) {
    myFlashClient.SetLanguage(language);
}



/****************************  POI ROUTING ***********************************/

function onSuccessOfGetAddressByPosition(routeAnswer) {

    //    alert("in onSuccessOfGetAddressByPosition:");

    delete routeAnswer.__type;
    delete routeAnswer.AddressWithPosition.__type;
    delete routeAnswer.AddressWithPosition.Position.__type;

    SetRoutingAddress(routeAnswer.TypeOfEndPoint, routeAnswer.AddressWithPosition);
}

function SetRoutingAddress(direction, address) {
    var answerAsString = JSON.stringify(address);

    if (direction == "TO") {
        var hidPoiRoutingTo = document.getElementById("PortalPoiToAddress");
        hidPoiRoutingTo.value = JSON.stringify(address);
        //                alert("hidPoiRoutingTo:" + hidPoiRoutingTo.value);
    }
    else {
        var hidPoiRoutingFrom = document.getElementById("PortalPoiFromAddress");
        hidPoiRoutingFrom.value = JSON.stringify(address);
        //                alert("hidPoiRoutingFrom:" + hidPoiRoutingFrom.value);
    }

    //define if the address is the departure or the arrival
    var idOfSender = "";
    if (direction == "TO") {
        idOfSender = document.getElementById("PortalIdButtonPoiRoutingTo").value;
    }
    else {
        idOfSender = document.getElementById("PortalIdButtonPoiRoutingFrom").value;
    }
    __doPostBack(idOfSender, answerAsString);
}


function OnRouteDemand(instanceId, args) {
    ///<summary>This an event handler when the user clicks on routing to or from in a poi</summary>
    ///<param name="instanceId">id of the flash instance</param>
    ///<param name="args">arguments including id of the flash instance</param>

    /*
    args.direction = "TO" / "FROM" 
    args.position = {longitude :xxx,latitude :xxxx} 
    args.text = "POI Name" 
    args.id = "POI ID"
    */
    //        alert(args.text + " " + args.id + "\n" + args.direction + ":" + args.position.longitude + ";" + args.position.latitude);
    var service = new Novasys.Maponair.WebContainer.MoaServices();
    //    service.GetAddressByPosition(document.getElementById('PortalToken').value, args.position.longitude, args.position.latitude, args.direction, onSuccessOfGetAddressByPosition, null, null);
    service.GetAddressOfPoi(document.getElementById('PortalToken').value, args.id, args.position.longitude, args.position.latitude, args.direction, onSuccessOfGetAddressByPosition, null, null);
}

function onRouting(direction) {
    var hidAddress = document.getElementById("PortalAddressToShow");
    if (hidAddress != null && hidAddress.value != "") {
        var address = JSON.parse(hidAddress.value);
        SetRoutingAddress(direction, address);
    }

}

/****************************  end POI ROUTING *******************************/


function ShowPoisById(idPoiCategorie) {
    myFlashClient.ShowPOICategory(idPoiCategorie);
}

function HidePoisById(idPoiCategorie) {
    myFlashClient.HidePOICategory(idPoiCategorie);
}



function HelloWorld() {
    alert('Hello World');
}