﻿var addEditMapShape = null;
var addEditMapShapeType = null;
var mapShapeEventTypeSettingsList = null;
var mapShapeUTCOffset = 0;

function ShowMapShapeTools() {
    var tools = $get("mapShapeToolBarTools");
    tools.style.display = "";
    var delegate = function() { document.onclick = HideMapShapeTools; }
    setTimeout(delegate, 0);
}

function HideMapShapeTools() {
    document.onclick = null;
    var tools = $get("mapShapeToolBarTools");
    tools.style.display = "none";
}

function ShapeSelected(shapeType, shape) {
    addEditMapShape = shape;
    addEditMapShapeType = shapeType;
    setDefaultValues();
    ShurWeb.WebServices.MapShapes.GetMapItem(shape.id, OnShapeSelectedComplete, null);
}

function ShapeCreated(shapeType, shape) {
    addEditMapShape = shape;
    addEditMapShapeType = shapeType;
    setDefaultValues();

    $get(mapShape_label_ControlID).value = shape.geoCodingRecord.item;      // Shape label
    $get("_city").value = shape.geoCodingRecord.city;
    $get("_town").value = shape.geoCodingRecord.town;
    $get("_roadOrRiver").value = shape.geoCodingRecord.roadOrRiver;
    $get("_area").value = shape.geoCodingRecord.area;
    $get("_province").value = shape.geoCodingRecord.province;
    $get("_country").value = shape.geoCodingRecord.country;
    $get("_centerLongitude").innerHTML = "";
    $get("_centerLatitude").innerHTML = "";

    $get("_radiusRow").style.display = "none";
    $get("_widthRow").style.display = "none";

    var deleteButton = $get(mapShapePopupDeleteButtonControlID);
    deleteButton.disabled = true;
    var okButton = $get(mapShapePopupOKButtonControlID);
    okButton.disabled = false;

    var mapItemTabControl = $find(mapItemTabControlID);
    mapItemTabControl.get_tabs()[1].set_enabled(true);

    switch (shapeType) {
        case CIRCLE_SHAPE_TYPE:
            {
                $get(mapShape_radius_ControlID).value = shape.radius    // Radius in meters - 16bit int                     
                $get("_radiusRow").style.display = "";
                $get("_centerLongitude").innerHTML = CoordinateToString(shape.center.lonX, false);    // Coordinate
                $get("_centerLatitude").innerHTML = CoordinateToString(shape.center.latY, true);    // Coordinate
            }

            break;
        case POLYGON_SHAPE_TYPE:
            {
                shape.coordinates;   // Coordinate collection - first point != last point
            }

            break;
        case POLYLINE_SHAPE_TYPE:
            {
                shape.coordinates;   // Coordinate collection - first point != last point\
                mapItemTabControl.get_tabs()[1].set_enabled(false);
            }

            break;
        case ROUTE_SHAPE_TYPE:
            {
                $get("_widthRow").style.display = "";
                shape.coordinates   // Coordinate collection - first point != last point
            }

            break;
    }

    var modalPopupBehavior = $find('programmaticMapShapesPopup');
    modalPopupBehavior.show();
}

function DeleteMapShape() {
    var modalPopupBehavior = $find('programmaticMapShapesPopup');
    modalPopupBehavior.hide();

    ShurWeb.WebServices.MapShapes.DeleteMapShape(addEditMapShape, null, null);
    setTimeout(function() { if (cimap && !cimap.IsReplaying()) { cimap.RefreshMap(); } }, 2000);
}

function AddEditMapShape() {
    if (!Page_ClientValidate('MapShapeValGroup')) {
        return false;
    }
    var addEditMapShapeColour;
    var colour = $get(mapShapeItemColourControlID);

    addEditMapShape.geoCodingRecord.item = $get(mapShape_label_ControlID).value;
    addEditMapShape.geoCodingRecord.city = $get("_city").value;
    addEditMapShape.geoCodingRecord.town = $get("_town").value;
    addEditMapShape.geoCodingRecord.roadOrRiver = $get("_roadOrRiver").value;
    addEditMapShape.geoCodingRecord.area = $get("_area").value
    addEditMapShape.geoCodingRecord.province = $get("_province").value;
    addEditMapShape.geoCodingRecord.country = $get("_country").value;
    addEditMapShape.radius = $get(mapShape_radius_ControlID).value;
    addEditMapShape.width = $get(mapShape_width_ControlID).value;

    ShurWeb.WebServices.MapShapes.AddEditMapShape(addEditMapShapeType, addEditMapShape, getEventTypeSettings(), colour.value, null, showException);

    hideMapShapesModalPopup();
    setTimeout(function() { if (cimap && !cimap.IsReplaying()) { cimap.RefreshMap(); } }, 2000);
}

function OnShapeSelectedComplete(shape) {
    // All geocoding properties are strings
    $get(mapShape_label_ControlID).value = shape.Item;      // Shape label
    $get("_city").value = shape.City;
    $get("_town").value = shape.Town;
    $get("_roadOrRiver").value = shape.RoadOrRiver;
    $get("_area").value = shape.Area;
    $get("_province").value = shape.Province;
    $get("_country").value = shape.Country;
    $get("_centerLongitude").innerHTML = CoordinateToString(shape.CenterLongitude, false);    // Coordinate
    $get("_centerLatitude").innerHTML = CoordinateToString(shape.CenterLatitude, true);    // Coordinate
    var colour = $get(mapShapeItemColourControlID);

    var okButton = $get(mapShapePopupOKButtonControlID);
    okButton.disabled = !shape.CanUpdate;

    var deleteButton = $get(mapShapePopupDeleteButtonControlID);
    deleteButton.disabled = !shape.CanDelete;


    for (var i = 0; i < colour.length; i++) {
        if (shape.Colour.substring(1, shape.Colour.length).toUpperCase() ==
          colour[i].value.substring(1, colour[i].value.length).toUpperCase()) {
            colour.selectedIndex = i;
            colour.style.backgroundColor = colour.options[colour.selectedIndex].style.backgroundColor;
            colour.style.color = colour.options[colour.selectedIndex].style.color;
            break;
        }
    }

    $get("_radiusRow").style.display = "none";
    $get("_widthRow").style.display = "none";

    // NOTE: The specific properties for each shape type are not populated during a select
    switch (shape.ShapeType) {
        case CIRCLE_SHAPE_TYPE:
            {
                $get(mapShape_radius_ControlID).value = shape.Radius    // Radius in meters - 16bit int                     
                $get("_radiusRow").style.display = "";
            }
            break;
        case POLYGON_SHAPE_TYPE:
            {
            }
            break;
        case POLYLINE_SHAPE_TYPE:
            {

            }
            break;
        case ROUTE_SHAPE_TYPE:
            {
                $get("_widthRow").style.display = "";
                $get(mapShape_width_ControlID).value = shape.Width;   // Coordinate collection - first point != last point
            }
            break;
    }
    //alert("Shape Selected\r\n" + shapeType + " " + shape.geoCodingRecord.item);
    var modalPopupBehavior = $find('programmaticMapShapesPopup');
    modalPopupBehavior.show();
}

function hideMapShapesModalPopup() {
    mapShapeEventTypeSettingsList = null;
    var modalPopupBehavior = $find('programmaticMapShapesPopup');
    modalPopupBehavior.hide();
    cimap.ResetMouseTool();
}

function setDefaultValues() {
    $find(mapShapePopupItemTabControlID).set_activeTabIndex(0);
    $get(mapShape_label_ControlID).value = "";
    $get(mapShape_radius_ControlID).value = "50";
    $get(mapShape_width_ControlID).value = "200"

    var colour = $get(mapShapeItemColourControlID);
    for (var i = 0; i < colour.length; i++) {
        if ('FF0000' == colour[i].value.substring(1, colour[i].value.length).toUpperCase()) {
            colour.selectedIndex = i;
            colour.style.backgroundColor = colour.options[colour.selectedIndex].style.backgroundColor;
            colour.style.color = colour.options[colour.selectedIndex].style.color;
            break;
        }
    }
}

function loadGeoFenceData() {
    if (mapShapeEventTypeSettingsList != null)
        return;
    ShurWeb.WebServices.MapShapes.GetMapShapeEventTypeSettings(addEditMapShape.id, loadedGeoFenceData, showException);
}

function loadedGeoFenceData(result) {
    var mapShapeETSA = $find(mapShapeEventTypeSettingsAccordionControlID + '_AccordionExtender');
    mapShapeETSA.set_SelectedIndex(0);

    mapShapeEventTypeSettingsList = result.MapShapeEventTypeSettingsList;
    for (var i = 0; i < mapShapeEventTypeSettingsList.length; i++) {
        var eventTypeSettings = mapShapeEventTypeSettingsList[i];
        var eventTypeID = eventTypeSettings.EventTypeID;
        mapShapeUTCOffset = result.UTCOffset;
        for (var j = 0; j < MSE.MapShapeEvent.length; j++) {
            if (MSE.MapShapeEvent[j].EventTypeID == eventTypeID) {
                var eventControls = MSE.MapShapeEvent[j].EventControls;
                SetControlValue(eventControls, '_cbEnabled', eventTypeSettings.Enabled);
                FindClientControl(eventControls, '_cbEnabled').onclick = SetEventTypeControlsDisabledFromEvent;

                SetControlValue(eventControls, '_cbAll', eventTypeSettings.AllOwnerUsersAssets);
                FindClientControl(eventControls, '_cbAll').onclick = SetAssetListDisabled;

                SetControlValue(eventControls, '_cbMon', eventTypeSettings.TimeWindowWeekDays & 1);
                SetControlValue(eventControls, '_cbTue', eventTypeSettings.TimeWindowWeekDays & 2);
                SetControlValue(eventControls, '_cbWed', eventTypeSettings.TimeWindowWeekDays & 4);
                SetControlValue(eventControls, '_cbThu', eventTypeSettings.TimeWindowWeekDays & 8);
                SetControlValue(eventControls, '_cbFri', eventTypeSettings.TimeWindowWeekDays & 16);
                SetControlValue(eventControls, '_cbSat', eventTypeSettings.TimeWindowWeekDays & 32);
                SetControlValue(eventControls, '_cbSun', eventTypeSettings.TimeWindowWeekDays & 64);
                SetControlValue(eventControls, '_lbFromH', GetHourValue(eventTypeSettings.TimeWindowStartTime, mapShapeUTCOffset));
                SetControlValue(eventControls, '_lbFromM', GetMinutesValue(eventTypeSettings.TimeWindowStartTime));
                SetControlValue(eventControls, '_lbToH', GetHourValue(eventTypeSettings.TimeWindowEndTime - 1, mapShapeUTCOffset));
                SetControlValue(eventControls, '_lbToM', GetMinutesValue(eventTypeSettings.TimeWindowEndTime - 1));

                SetAssetListValues(eventControls, '_assetList', result.SimpleAssetList, eventTypeSettings);
                SetControlsDisabled(FindClientControl(eventControls, '_assetList'), eventTypeSettings.AllOwnerUsersAssets);
                SetEventTypeControlsDisabled(j, FindClientControl(eventControls, '_cbEnabled'));
            }
        }
    }
}

function getEventTypeSettings() {
    if (mapShapeEventTypeSettingsList != null) {
        for (var i = 0; i < mapShapeEventTypeSettingsList.length; i++) {
            var eventTypeSettings = mapShapeEventTypeSettingsList[i];
            var eventTypeID = eventTypeSettings.EventTypeID;
            for (var j = 0; j < MSE.MapShapeEvent.length; j++) {
                if (MSE.MapShapeEvent[j].EventTypeID == eventTypeID) {
                    var eventControls = MSE.MapShapeEvent[j].EventControls;
                    eventTypeSettings.Enabled = GetControlValue(eventControls, '_cbEnabled');
                    eventTypeSettings.AllOwnerUsersAssets = GetControlValue(eventControls, '_cbAll');
                    var timeWindowWeekDays = 0;
                    if (GetControlValue(eventControls, '_cbMon'))
                        timeWindowWeekDays += 1;
                    if (GetControlValue(eventControls, '_cbTue'))
                        timeWindowWeekDays += 2;
                    if (GetControlValue(eventControls, '_cbWed'))
                        timeWindowWeekDays += 4;
                    if (GetControlValue(eventControls, '_cbThu'))
                        timeWindowWeekDays += 8;
                    if (GetControlValue(eventControls, '_cbFri'))
                        timeWindowWeekDays += 16;
                    if (GetControlValue(eventControls, '_cbSat'))
                        timeWindowWeekDays += 32;
                    if (GetControlValue(eventControls, '_cbSun'))
                        timeWindowWeekDays += 64;
                    eventTypeSettings.TimeWindowWeekDays = timeWindowWeekDays;
                    eventTypeSettings.AssetIDs = GetControlValue(eventControls, '_assetList');
                    var timeWindowStartTime = new Date('1 Jan 2007');
                    timeWindowStartTime.setHours(GetControlValue(eventControls, '_lbFromH'));
                    timeWindowStartTime.setMinutes(GetControlValue(eventControls, '_lbFromM'));
                    eventTypeSettings.TimeWindowStartTime = (Date.parse(timeWindowStartTime) - Date.parse(new Date('1 Jan 2007'))) / (1000) - mapShapeUTCOffset * 3600;
                    // If the Start time value is smaller than 0, add 1 day to the start time
                    if (eventTypeSettings.TimeWindowStartTime < 0)
                        eventTypeSettings.TimeWindowStartTime = eventTypeSettings.TimeWindowStartTime + (24 * 60 * 60)

                    var timeWindowEndTime = new Date('1 Jan 2007');
                    timeWindowEndTime.setHours(GetControlValue(eventControls, '_lbToH'));
                    timeWindowEndTime.setMinutes(GetControlValue(eventControls, '_lbToM'));
                    timeWindowEndTime.setSeconds(59);
                    eventTypeSettings.TimeWindowEndTime = (Date.parse(timeWindowEndTime) - Date.parse(new Date('1 Jan 2007'))) / (1000) - mapShapeUTCOffset * 3600;
                    // If the End time value is smaller than 0, add 1 day to the end time
                    if (eventTypeSettings.TimeWindowEndTime < 0)
                        eventTypeSettings.TimeWindowEndTime = eventTypeSettings.TimeWindowEndTime + (24 * 60 * 60)
                }
            }
        }
    }
    return mapShapeEventTypeSettingsList;
}

function SetAssetListValues(EventControls, ControlServerID, AssetList, EventTypeSettings) {
    for (var i = 0; i < EventControls.length; i++) {
        if (EventControls[i].ServerID == ControlServerID) {
            var ctrl = $get(EventControls[i].ClientID);
            ctrl.innerHTML = '';
            for (var j = 0; j < AssetList.length; j++) {
                var span = document.createElement('span');
                var cb = document.createElement('input');
                cb.type = "checkbox";
                cb.id = EventTypeSettings.EventTypeID + '[' + AssetList[j].AssetID + ']';
                cb.checked = false;
                for (var a = 0; a < EventTypeSettings.AssetIDs.length; a++) {
                    if (EventTypeSettings.AssetIDs[a] == AssetList[j].AssetID) {
                        cb.checked = true;
                        cb.setAttribute('checked', true);
                        cb.attributes['checked'].value = true;
                        break;
                    }
                }
                var label = document.createElement('label');
                label.setAttribute('for', cb.id);
                label.attributes['for'].value = cb.id
                label.appendChild(document.createTextNode(AssetList[j].FullDescription));

                span.appendChild(cb);
                span.appendChild(label);
                span.appendChild(document.createElement('br'));
                span.setAttribute('class', 'cbalign');
                span.attributes['class'].value = 'cbalign';
                ctrl.appendChild(span);
            }
            break;
        }
    }
}

function GetAssetIDList(ParentControl) {
    var assetIDs = new Array();
    for (var i = 0; i < ParentControl.childNodes.length; i++) {
        var ctrl = FindCheckBox(ParentControl.childNodes[i]);
        if (ctrl.checked) {
            var assetID = ctrl.id;
            assetID = assetID.substr(assetID.indexOf('[') + 1, assetID.length - assetID.indexOf('[') - 2);
            assetIDs.push(assetID);
        }
    }
    return assetIDs;
}

function FindCheckBox(ParentControl) {
    for (var i = 0; i < ParentControl.childNodes.length; i++) {
        if (ParentControl.childNodes[i].type == 'checkbox')
            return ParentControl.childNodes[i];
        else if (ParentControl.childNodes[i].childNodes.length > 0)
            return FindCheckBox(ParentControl.childNodes[i]);
    }
}

function SetEventTypeControlsDisabledFromEvent(event) {
    var e = event || window.event;
    var element = e.srcElement || e.target;
    var eventTypeID = 0;

    for (var j = 0; j < MSE.MapShapeEvent.length; j++) {
        for (var i = 0; i < MSE.MapShapeEvent[j].EventControls.length; i++) {
            if (MSE.MapShapeEvent[j].EventControls[i].ClientID == element.id) {
                eventTypeID = j;
                break;
            }
        }
    }
    SetEventTypeControlsDisabled(eventTypeID, element);
}

function SetEventTypeControlsDisabled(eventTypeID, element) {
    for (var i = 0; i < MSE.MapShapeEvent[eventTypeID].EventControls.length; i++) {
        var eventControls = MSE.MapShapeEvent[eventTypeID].EventControls;
        if (eventControls[i].ClientID != element.id)
            SetControlsDisabled($get(eventControls[i].ClientID), !element.checked);

        if (eventControls[i].ServerID == '_assetList' && element.checked)
            SetControlsDisabled($get(eventControls[i].ClientID), FindClientControl(eventControls, "_cbAll").checked);
    }
}

function SetAssetListDisabled(event) {
    var e = event || window.event;
    var element = e.srcElement || e.target;

    for (var j = 0; j < MSE.MapShapeEvent.length; j++) {
        for (var i = 0; i < MSE.MapShapeEvent[j].EventControls.length; i++) {
            if (MSE.MapShapeEvent[j].EventControls[i].ClientID == element.id) {
                SetControlsDisabled(FindClientControl(MSE.MapShapeEvent[j].EventControls, "_assetList"), element.checked)
                break;
            }
        }
    }
}

function SetControlsDisabled(ParentControl, disabled) {
    if (ParentControl.type == 'checkbox' ||
      ParentControl.type == 'select-one')
        ParentControl.disabled = disabled;

    for (var i = 0; i < ParentControl.childNodes.length; i++) {
        if (ParentControl.childNodes[i].type == 'checkbox' ||
        ParentControl.childNodes[i].type == 'select-one')
            ParentControl.childNodes[i].disabled = disabled;
        else if (ParentControl.childNodes[i].childNodes.length > 0)
            SetControlsDisabled(ParentControl.childNodes[i], disabled);
    }
}


function SetControlValue(EventControls, ControlServerID, Value) {
    var ctrl = FindClientControl(EventControls, ControlServerID);
    if (ctrl == null)
        return;
    if (ctrl.type == 'checkbox')
        ctrl.checked = Value;
    else if (ctrl.type == 'select-one') {
        for (var j = 0; j < ctrl.options.length; j++) {
            ctrl.options[j].selected = ctrl.options[j].value == Value;
        }
    }
}

function GetControlValue(EventControls, ControlServerID) {
    var ctrl = FindClientControl(EventControls, ControlServerID);
    if (ctrl == null)
        return;

    if (ctrl.type == 'checkbox')
        return ctrl.checked;
    else if (ctrl.type == 'select-one')
        return ctrl.value;
    else if (ctrl.tagName == 'DIV')
        return GetAssetIDList(ctrl);

    return null;
}

function FindClientControl(EventControls, ControlServerID) {
    for (var i = 0; i < EventControls.length; i++) {
        if (EventControls[i].ServerID == ControlServerID)
            return $get(EventControls[i].ClientID);
    }
    return null;
}

function GetHourValue(SecondsSinceMidnight, UTCOffset) {
    var date = new Date('1 Jan 2000');
    date.setUTCSeconds(SecondsSinceMidnight + (3600 * UTCOffset));
    return date.getHours();
}

function GetMinutesValue(SecondsSinceMidnight) {
    var date = new Date('1 Jan 2000');
    date.setUTCSeconds(SecondsSinceMidnight);
    return date.getMinutes();
}

function showException(result) {
    window.status = result._message;
}

function eventControls(serverID, clientID) {
    this.ServerID = serverID;
    this.ClientID = clientID;
}

function mapShapeEvent(eventTypeID) {
    this.EventControls = new Array();
    this.EventTypeID = eventTypeID;
}

function mapShapeEvents() {
    this.MapShapeEvent = new Array();
}


// Add click handlers for buttons to show and hide modal popup on pageLoad
function pageLoad() {
    if (typeof (cimap) != "undefined") {
        cimap.onShapeSelected = ShapeSelected;
    }
}
