//PortalScripts.js


function sleep(milliseconds) {
    var now = new Date();
    var exitTime = now.getTime() + milliseconds;

    while (true) {
        now = new Date();
        if (now.getTime() > exitTime) return;
    }
}

function ClearRouting() {
    document.getElementById('flashDiv').style.visibility = 'visible';
}

function PreparePrinting() {
    //document.getElementById('flashDiv').style.visibility = 'hidden';
}


function SetStyleOfElement(styleObj) {
    var styleObject = JSON.parse(styleObj);
    var elem = document.getElementById(styleObject.ElementId);
    if (elem != null) {
        elem.className = styleObject.CssClass;
    }
}


function GetBounds() {
    var startBoundsElem = document.getElementById('PortalBounds');
    return GetBoundsOfElement(startBoundsElem);
}

function GetBoundsOfElement(element) {

    if (!element) {
        return false;
    }

    if (element.value == "") {
        return false;
    }

    var bndJS = JSON.parse(element.value);

    var bounds = { "bottomLeft": { "longitude": bndJS.LowerLeft.Longitude, "latitude": bndJS.LowerLeft.Latitude },
        "topRight": { "longitude": bndJS.UpperRight.Longitude, "latitude": bndJS.UpperRight.Latitude }
    };

    return bounds;
}

function HideSingleElement(elementToHideID) {
    var elem = document.getElementById(elementToHideID);
    if (elem) {
        elem.style.display = 'none';
    }
}

function ShowSingleElement(elementToHideID) {
    var elem = document.getElementById(elementToHideID);
    if (elem) {
        elem.style.visibility = 'visible';
    }
}






function ChangeTab(elements, styles) {
    var theElements = JSON.parse(elements);
    var theStyles = JSON.parse(styles);

    document.getElementById(theElements.ElementToShow).className = theStyles.VisibleStyle;
    document.getElementById(theElements.ElementToActivated).className = theStyles.ActiveStyle;

    for (var x = 0; x < theElements.ElementsToHide.length; x++) {
        document.getElementById(theElements.ElementsToHide[x]).className = theStyles.HiddenStyle;
    }

    for (var x = 0; x < theElements.ElementsToDeactivate.length; x++) {
        document.getElementById(theElements.ElementsToDeactivate[x]).className = theStyles.InActiveStyle;
    }
}

/*************************    methods of poiSwitch   *************************/

function PoiSwitchSwitchPoiCategorieOn(keyOfPoi) {
    ShowPoisById(keyOfPoi);
}

function PoiSwitchSwitchPoiCategorieOff(keyOfPoi) {
    HidePoisById(keyOfPoi);
}

/*************************    endOf methods of poiSwitch   *******************/


/*************************    methods of dynamic roadbook   ******************/


function MoaDynamicRoadBookShowInstruction(instruction) {
    AddInstructionMarker(instruction);
}

function MoaDynamicRoadBookShowStartPosition(instruction) {
    SetCenterPosition(instruction);
}

function MoaDynamicRoadBookShowEndPosition(instruction) {
    SetCenterPosition(instruction);
}

function MoaDynamicRoadBookShowRouteOverview(bounds) {
    var theBounds = JSON.parse(bounds);
    var jsonBounds = { 'bottomLeft': { 'longitude': theBounds.LowerLeft.Longitude, 'latitude': theBounds.LowerLeft.Latitude },
        'topRight': { 'longitude': theBounds.UpperRight.Longitude, 'latitude': theBounds.UpperRight.Latitude }
    };
    SetBounds(jsonBounds);
}

function MoaDynamicRoadBookPrintRoadBook(routeId) {
    window.open('RoadbookPrintOutAsPdf.aspx?RouteId=' + routeId, 'PrintWindow');
}

/*************************    endOf methods of dynamic roadbook   ******************/



/*************************    methods of addressSearch   *********************/

function MoaAddressSearchClearMarker(idOfAddressSearch) {
    RemoveMarkerInMap('MoaSearchMarker');
    RemoveMagnifyingGlass();
    RemoveAllMoaForms();
    RemoveInstructionMarker();
}

function MoaAddressSearchDisplayAddress(address) {
    var theAddress = JSON.parse(address);

    if (CoordinatesAreValid(address)) {
        onSuccessMoaAddressSearchDisplayAddress(theAddress);
    }
    else {
        //GetCoords of address
        var service = new Novasys.Maponair.WebContainer.MoaServices();
        service.GetPositionOfAddress(document.getElementById('PortalToken').value, theAddress.SearchPrecision, theAddress.Country,
         theAddress.State, theAddress.Zip, theAddress.City, theAddress.Street, theAddress.HouseNumber, theAddress.Ids,
          theAddress.ZoomLevelOnMap, onSuccessMoaAddressSearchDisplayAddress, null, null);
    }
}



function onSuccessMoaAddressSearchDisplayAddress(adrWithCoords) {
    delete adrWithCoords.__type;
    delete adrWithCoords.Position.__type;

    RemoveMarkerInMap('MoaSearchMarker');
    RemoveMagnifyingGlass();
    RemoveAllMoaForms();

    //add address to hidden field so that it can be set when one of the routing buttons of the addressSeach is clicked
    var hidAdr = document.getElementById("PortalAddressToShow");
    hidAdr.value = JSON.stringify(adrWithCoords);

    if (adrWithCoords.SearchPrecision == "HOUSE_NUMBER_RANGE" || adrWithCoords.SearchPrecision == "PRECISE_STREET") {
        ShowPolyLines(JSON.stringify(adrWithCoords));
        AddMarkerToMap(JSON.stringify(adrWithCoords), 'MoaSearchMarker', false);
    }
    else {
        AddMarkerToMap(JSON.stringify(adrWithCoords), 'MoaSearchMarker', true);
    }

}


function MoaAddressSearchOnRoute(direction) {
    onRouting(direction);
}


function MoaAddressSearchShowMagnifier(address) {
    var theAddress = JSON.parse(address);

    if (CoordinatesAreValid(address)) {
        onSuccessMoaAddressSearchShowMagnifier(theAddress);
    }
    else {
        //GetCoords of address
        var service = new Novasys.Maponair.WebContainer.MoaServices();
        service.GetPositionOfAddress(document.getElementById('PortalToken').value, theAddress.SearchPrecision, theAddress.Country,
        theAddress.State, theAddress.Zip, theAddress.City, theAddress.Street, theAddress.HouseNumber, theAddress.Ids,
        theAddress.ZoomLevelOnMap, onSuccessMoaAddressSearchShowMagnifier, null, null);
    }

    SetZoomLevel(theAddress.ZoomLevelOnMap);
}

function onSuccessMoaAddressSearchShowMagnifier(adrWithCoords) {
    try {
        delete adrWithCoords.__type;
    }
    catch (e) {
        //empty catch because it isnt sure if __type exists
    }

    //In some cases we want to highlight the street on the map
    if (adrWithCoords.SearchPrecision == "HOUSE_NUMBER_RANGE" || adrWithCoords.SearchPrecision == "PRECISE_STREET") {
        ShowPolyLines(JSON.stringify(adrWithCoords));
    }
    else {
        AddMagnifyingGlass(JSON.stringify(adrWithCoords));
    }
}

function GetCoordinatesOfAddress(address) {
    var theAddress = JSON.parse(address);
    var position;

    try {
        var service = new Novasys.Maponair.WebContainer.MoaServices();
        position = service.GetPositionOfAddress(document.getElementById('PortalToken').value, theAddress.SearchPrecision,
         theAddress.Country, theAddress.State, theAddress.Zip, theAddress.City, theAddress.Street, theAddress.HouseNumber,
         theAddress.Ids, theAddress.ZoomLevelOnMap, null, null, null);
        return position;
    }
    catch (e) {
        alert('GetCoordinatesOfAddress->' + e.message);
    }
}

function CoordinatesAreValid(address) {
    var theAddress = JSON.parse(address);

    //if the address or the position is not valid
    if (theAddress == null || theAddress.Position == null) {
        return false;
    }

    //if the values position of the address aren't valid
    if (theAddress.Position.Longitude == null || theAddress.Position.Longitude == null) {
        return false;
    }

    //if the position of the address is impossible
    if (theAddress.Position.Longitude == '0' && theAddress.Position.Longitude == '0') {
        return false;
    }

    return true;
}

/*************************    endOf methods of addressSearch   ***************/


/*************************    methods of addressList   ***************/

var theRoutingPostbackId;

function onSuccessRoutingAddressListGetRoute(routeId) {
    if (routeId == null || routeId == "") {
        document.getElementById("PortalRouteId").value = "";
    }
    else {
        document.getElementById("PortalRouteId").value = routeId;
        AddRouteToMap(routeId);
    }
    __doPostBack(theRoutingPostbackId, null);
}


function RoutingAddressListGetRoute(postbackId, watermarks, startAdrHidField, endAddrHidField, isBackWay) {
    theRoutingPostbackId = postbackId;
    //Get the ids of the value controls out of the hiddenfields
    if (startAdrHidField != null && endAddrHidField != null) {
        var startAdrFields = document.getElementById(startAdrHidField);
        var endAdrFields = document.getElementById(endAddrHidField);
        if (startAdrFields != null && endAdrFields != null) {
            //parse the json of the controls to objects that represents the different values of the address control
            var start = JSON.parse(startAdrFields.value);
            var ende = JSON.parse(endAdrFields.value);
        }
    }

    if (start != null && ende != null && watermarks != null) {

        var theWatermarks = JSON.parse(watermarks);

        //extract the actual address coresponding to the situation
        var st = GetActualAddress(start, theWatermarks);
        var end = GetActualAddress(ende, theWatermarks);


        var service = new Novasys.Maponair.WebContainer.MoaServices();
        service.GetRouteId(document.getElementById('PortalToken').value, isBackWay,
          st.Country, st.State, st.Zip, st.City, st.Street, st.HouseNumber, st.Ids, st.Longitude, st.Latitude,
          end.Country, end.State, end.Zip, end.City, end.Street, end.HouseNumber, end.Ids, end.Longitude, end.Latitude,
          onSuccessRoutingAddressListGetRoute, null, null);
    }
}

function GetActualAddress(controls, watermarks) {

    var country = document.getElementById(controls.Country).value;
    //because we use watermarks in the textboxes we have to replace them by empty string if they are the as value
    var zip = CleanStringIf(document.getElementById(controls.Zip).value, watermarks.Zip);
    var city = CleanStringIf(document.getElementById(controls.City).value, watermarks.City);
    var street = "";
    var doSearch = false;
    var houseNumber = "";
    var ids = "";
    var state = "";
    var searchPrecision = "";
    var longitude = "";
    var latitude = "";
    var description = "";

    if (AddressIsNotModified(controls, watermarks)) {
        street = document.getElementById(controls.HidStreet).value;
        houseNumber = document.getElementById(controls.HidHouseNumber).value;
        ids = document.getElementById(controls.HidIds).value
        state = document.getElementById(controls.HidState).value;
        searchPrecision = document.getElementById(controls.HidSearchPrecision).value;

        //add only position if correct value are in the hiddenfields
        if (document.getElementById(controls.HidLong).value != "" && document.getElementById(controls.HidLat).value) {

            longitude = document.getElementById(controls.HidLong).value;
            latitude = document.getElementById(controls.HidLat).value;
        }

        description = document.getElementById(controls.HidDescription).value;

        //mark that there is no need to research the position
        doSearch = false;
    }
    else {
        street = CleanStringIf(document.getElementById(controls.Street).value, watermarks.Street);
        ids = ""
        doSearch = true;
    }

    var adr = { "Country": country, "Zip": zip, "City": city, "State": state, "Street": street, "DoSearch": doSearch, "HouseNumber": houseNumber,
        "Ids": ids, "SearchPrecision": searchPrecision, "Longitude": longitude, "Latitude": latitude, "Description": description
    };
    return adr;
}


function AddressIsNotModified(controls, watermarks) {
    if (document.getElementById(controls.HidCity).value != CleanStringIf(document.getElementById(controls.City).value, watermarks.City)) {
        return false;
    }
    if (document.getElementById(controls.HidCountry).value != document.getElementById(controls.Country).value) {
        return false;
    }
    var streetWithHouseNumber = document.getElementById(controls.HidStreet).value;
    if (document.getElementById(controls.HidHouseNumber).value != "") {
        streetWithHouseNumber += " " + document.getElementById(controls.HidHouseNumber).value;
    }

    if (streetWithHouseNumber != CleanStringIf(document.getElementById(controls.Street).value, watermarks.Street)) {
        return false;
    }
    return true;
}

function CleanStringIf(original, searchString) {
    if (original == searchString) {
        return "";
    }
    else {
        return original;
    }
}

/*************************    endOf methods of addressList   ***************/



//function Tastendruck(Ereignis) {
//    if (!Ereignis) {
//        Ereignis = window.event;
//    }
//    if (Ereignis.keyCode == 13) {
//        CloseAllAndSearch(); return false;
//    }
//}

//document.onkeydown = Tastendruck;

//function CloseAllAndSearch() {
//    CloseAllSelectionPanels();

//    var fieldWithId = document.getElementById("PortalButtonToBeClicked");

//    document.getElementById(fieldWithId.value).click();
//}
