﻿///<reference path="global.js />
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//                                                  Device Maintenance
//
var NO_DM_UNITS = "<label class='whiteType'>There are currently no Hard Wired units associated with this account. This feature is only supported on Hard Wired units.  Please contact your dealer for more information.</label>";
var NO_DM_ALERTS = "No Alerts have been entered for this device. Click on the Add button to create a new alert.<br/><br/>" +
                "<label class='whiteType12'>Initial Miles</label> - Enter the Initial Miles of when you put your equipment into your service.<br/><br/>" +
                "<label class='whiteType12'>Current Miles</label> - Enter the Current Miles or the current odometer reading for today.<br/><br/>" +
                "<label class='whiteType12'>Initial Hours</label> - Enter the Initial Hours of when you put your equipment into your service.<br/><br/>" +
                "<label class='whiteType12'>Current Hours</label> - Enter the Current Hours or how many hours the equipment has been operating.<br/><br/>";
var DM_Status = {"NoAlerts":0, "Current":1, "Warning":2, "Overdue":3};
var DM_STATUS_NO_Alerts = "No Alerts";
var DM_STATUS_CURRENT = "Current";
var DM_STATUS_WARNING = "Warning";
var DM_STATUS_OVERDUE = "Overdue";
var DM_UNIT_MILE = "MILE";
var DM_UNIT_KLM = "KLMR";
var PASSWORDS_MATCH = "Passwords match.";
var PASSWORDS_DO_NOT_MATCH = "Passwords DO NOT match.";
var LOGIN = "Login";
var UPDATE_PASSWORD = "Update Device Maintenance Password";
var DEVICE_MAINTENANCE_TYPE = 'F'; 
var AT = "@";

var ERROR_NOT_LOGGED_IN = "You must be logged in to use this feature.";
var ERROT_INVALID_ENTRY = "Invalid entry.";
var ERROR_INVALID_NAME = "Please enter a name";
var ERROR_INVALID_LAST_MAIN_DATE = "Last Performed date is invalid. Please enter a valid date and time in the format MM/DD/YYYY. Ex.(01/01/2012)";
var ERROR_INVALID_ALERT_WARNING_PERFORMED = " Performed At, Warn At, and Alert At must be a positive number.";
var ERROR_WARNING_LESS_THAN_ALERT = "Warn At value must be less than Alert At value.";
var ERROR_INVALID_SMS = "Please enter a valid SMS Number including area code using only numbers.";
var ERROR_INVALID_EMAIL = "Please enter a valid e-mail.";
var ERROR_UPDATING_PASSWORD = "Error updating password. Please try again.";
var ERROR_PASSWORD_DO_NOT_MATCH = "Error updating password. Passwords do not match.";

var divFleetMgmtID = "divFleetMgmt";
var tbInitMilesID = "tbInitMiles";
var tbCurrMilesID = "tbCurrMiles";
var tbInitHoursID = "tbInitHours";
var tbCurrHoursID = "tbCurrHours";
var DeviceMaintenanceBackID = "DeviceMaintenanceBack";
var DeviceMaintenanceSaveID = "DeviceMaintenanceSave";
var DeviceMaintenanceEditID = "DeviceMaintenanceEdit";
var DeviceMaintenanceAddID = "DeviceMaintenanceAdd";
var DeviceMaintenanceDeleteID = "DeviceMaintenanceDelete";
var DeviceMaintenanceLoginID = "DeviceMaintenanceLogin";
var DeviceMaintenanceChangePasswordID = "DeviceMaintenanceChangePassword";

var currentFMDeviceID = 0;
var currentFMInitMiles = 0;
var currentFMCurrMiles = 0;
var currentFMInitHours = 0;
var currentFMCurrHours = 0;
var currentFMDeviceName = "N/A";
var DeviceMaintenanceLoggedIn = false;
var DeviceMaintenanceDiv = "";
var deviceMaintenanceIsVisiable = false;
var sdmTimeoutID = -1;
var DMAlertDetailList = new Array();
var currDMAlertDetail = null;

function DMAlertDetail(id, vehicleID, name, unit, alertValue, warnValue, lastMainValue, lastMainDate, enabled, emailEnabled, email, smsEnabled, smsNumber, smsCarrier, status) {
    this.id = id;
    this.vehicleID = vehicleID;
    this.name = name;
    this.unit = unit;
    this.alertValue = alertValue;
    this.warnValue = warnValue;
    this.lastMainValue = lastMainValue;
    this.lastMainDate = lastMainDate;
    this.enabled = enabled;
    this.emailEnabled = emailEnabled;
    this.email = email;
    this.smsEnabled = smsEnabled;
    this.smsNumber = smsNumber;
    this.smsCarrier = smsCarrier;
    this.status = status;
    this.isValid = false;
    this.HasChanged = function (that){
        if(this.id != that.id) return true;
        if(this.vehicleID != that.vehicleID) return true;
        if(this.name != that.name) return true;
        if(this.unit != that.unit) return true;
        if(this.alertValue != that.alertValue) return true;
        if(this.warnValue != that.warnValue) return true;
        if(this.lastMainValue != that.lastMainValue) return true;
        if(! this.lastMainDate.equalsTo(that.lastMainDate)) return true;
        if(this.enabled != that.enabled) return true;
        if(this.emailEnabled != that.emailEnabled) return true;
        if(this.email != that.email) return true;
        if(this.smsEnabled != that.smsEnabled) return true;
        if(this.smsNumber != that.smsNumber) return true;
        if(this.smsCarrier != that.smsCarrier) return true;
        return false;
    }

}
function DMStatus(number, name) {
    this.number = number;
    this.name = name;
}
function GetStatus(number) {
    switch (number) {
        case DM_Status.NoAlerts: return new DMStatus(DM_Status.NoAlerts, DM_STATUS_NO_Alerts); break;
        case DM_Status.Current: return new DMStatus(DM_Status.Current, DM_STATUS_CURRENT); break;
        case DM_Status.Warning: return new DMStatus(DM_Status.Warning, DM_STATUS_WARNING); break;
        default: return new DMStatus(DM_Status.Overdue, DM_STATUS_OVERDUE);
    }
}
function GetCurrentValue(unit){
    if (unit == DM_UNIT_MILE)
        return currentFMCurrMiles;
    else if (unit == DM_UNIT_KLM)
        return MilesToKilometers(currentFMCurrMiles);
    else
        return currentFMCurrHours;
}
function CalculateStatus(lastMainValue, alertValue, warnValue, unit) {
    if (unit == DM_UNIT_KLM) {
        lastMainValue = MilesToKilometers(lastMainValue);
        alertValue = MilesToKilometers(alertValue);
        warnValue = MilesToKilometers(warnValue);
    }
    return CalculateConvertedStatus(lastMainValue, alertValue, warnValue, unit);
}
function CalculateConvertedStatus(lastMainValue, alertValue, warnValue, unit) {
    var currvalue = GetCurrentValue(unit);
    
    if (currvalue - lastMainValue >= alertValue)
        return GetStatus(DM_Status.Overdue);
    else if (currvalue - lastMainValue >= warnValue)
        return GetStatus(DM_Status.Warning);
    else
        return GetStatus(DM_Status.Current);
}

function OpenFleetMgmt() {
    if (m_bLoggedIn && !(m_demoUser || demo2_user)) {
        showAlertDevices();
        fadein(divFleetMgmtID);
        if(!DeviceMaintenanceLoggedIn){
            editDeviceMaintenanceDetail(false);
        }
        HandleNoPassword();
    }
    else {
        AlertMessage(ERROR_NOT_LOGGED_IN);
    }
}

function HideFleetMgmt() {
    fadeout(divFleetMgmtID);
    deviceMaintenanceIsVisiable = false;
}

function showAlertDevices() {
    // pull all vehicels that are valid for fleetmanagement
    DeviceMaintenanceDiv = "divFleetMgmtList";
    var results = DAL.GetFMVehicles(m_CurrentUser);
    var div = document.getElementById("divFleetMgmtList");
    var status;
    ShowItem("divDeviceMgmt", true);
    ShowItem("divFleetMgmtAlerts", false);
    ShowItem("divFleetMgmtAlertDetail", false);
    ShowItem("divFleetMgmtPassword", false);
    ShowFMButtons(false, false, false, false, false, true);
    deviceMaintenanceIsVisiable = false;
    // if at least one vehicle has fleet management
    if (results != null && results.value != null) {
        results = results.value;
        if (results.Rows.length > 0) {
            div.innerHTML = "<hr>";
            for (var x = 0; x < results.Rows.length; x++) {
                status = GetStatus(results.Rows[x].Status);
                div.innerHTML += "<div onclick=\"showThisDeviceAlerts('" + results.Rows[x].Serial + "','"
                              + results.Rows[x].VehicleName + "'); \" style=\" position:relative; cursor:pointer;\"><label class=\"whiteType\">"
                              + results.Rows[x].VehicleName + "</label>"
                              + "<img title=\"" + status.name + "\" alt=\"" + status.name + "\" src=\"images/FleetMgmt/Status" + status.number + ".png\" style=\"position:absolute; right:0px;padding-top:2px;\"  />"
                              + "<hr></div>";
            }
        } else {
            div.innerHTML = NO_DM_UNITS;
        }
    } else {// Else display generic message 
        div.innerHTML = NO_DM_UNITS;
    }
}
function showDeviceAlerts() {
    showThisDeviceAlerts(currentFMDeviceID, currentFMDeviceName);
}
function showThisDeviceAlerts(devID, devName) {
    DeviceMaintenanceDiv = "divFleetMgmtAlertsList";
    if (devID != null && devName != null) {
        currentFMDeviceName = devName;
        currentFMDeviceID = parseInt(devID);
    }

    currentFMInitMiles = 0;
    currentFMCurrMiles = 0;
    currentFMInitHours = 0;
    currentFMCurrHours = 0;
    deviceMaintenanceIsVisiable = true;
    var results = DAL.GetAlertDetail(m_CurrentUser, currentFMDeviceID);
    var div = document.getElementById("divFleetMgmtAlertsList");

    document.getElementById(DeviceMaintenanceBackID).onclick = showAlertDevices;
    document.getElementById(DeviceMaintenanceSaveID).onclick = saveDeviceMaintenance;
    ShowItem("divDeviceMgmt", false);
    ShowItem("divFleetMgmtAlerts", true);
    ShowItem("divFleetMgmtAlertDetail", false);
    ShowItem("divFleetMgmtPassword", false);
    ShowFMButtons(true, false, true, true, false, true);
    editDeviceMaintenance(false);

    document.getElementById("lblFMDeviceName").innerHTML = "ALERTS FOR " + devName;

    // loop thru results and display in Device Alerts window
    if (results != null && results.value != null) {
        results = results.value;
        if (results.Rows.length > 0) {


            div.innerHTML = "<hr>";
            DMAlertDetailList = new Array();

            var lastMainValue, alertValue, warnValue, unit, name, status, currvalue;
            for (var x = 0; x < results.Rows.length; x++) {
               lastMainValue = results.Rows[x].lastMainVal;
               alertValue = results.Rows[x].alertValue;
               warnValue = alertValue - results.Rows[x].warnValue;
               unit =  results.Rows[x].unit;
               name =  results.Rows[x].name;

               status = CalculateStatus(lastMainValue, alertValue, warnValue, unit);

               DMAlertDetailList.push(new DMAlertDetail(results.Rows[x].id, devID, name, unit, alertValue, warnValue, 
                                                        lastMainValue, new Date(results.Rows[x].lastMainDate), results.Rows[x].enabled, results.Rows[x].emailEnabled, results.Rows[x].email, 
                                                        results.Rows[x].smsEnabled, results.Rows[x].smsNumber, results.Rows[x].smsCarrier, status)
                                                       );
                div.innerHTML += "<div onclick=\"showDeviceAlertDetail(" + x + ");\" style=\" position:relative; cursor:pointer;\"><label class=\"whiteType\">"
                              + name + "</label>"
                              + "<img title=\"" + status.name + "\" alt=\"" + status.name + "\" src=\"images/FleetMgmt/Status" + status.number + ".png\" style=\"position:absolute; right:0px;padding-top:2px;\"  />"
                              + "<hr></div>";
            }
        } else {
            div.innerHTML = NO_DM_ALERTS;
        }
    } else {
        div.innerHTML = NO_DM_ALERTS;
    }

}
function ShowDeviceMaintenance() {
    if (deviceMaintenanceIsVisiable) {
        currentFMInitMiles = 0;
        currentFMCurrMiles = 0;
        currentFMInitHours = 0;
        currentFMCurrHours = 0;
        var results = DAL.GetDeviceMaintenance(currentFMDeviceID);
        if (results != null && results.value != null) {
            results = results.value;
            if (results.Rows.length > 0) {
                currentFMInitMiles = results.Rows[0].InitMiles;
                currentFMCurrMiles = results.Rows[0].CurrMiles;
                currentFMInitHours = results.Rows[0].InitHours;
                currentFMCurrHours = results.Rows[0].CurrHours;
            }
        }
        document.getElementById(tbInitMilesID).value = NumberAlterPrecision(currentFMInitMiles, 2, false);
        document.getElementById(tbCurrMilesID).value = NumberAlterPrecision(currentFMCurrMiles, 2, false);
        document.getElementById(tbInitHoursID).value = NumberAlterPrecision(currentFMInitHours, 2, false);
        document.getElementById(tbCurrHoursID).value = NumberAlterPrecision(currentFMCurrHours, 2, false);
        clearTimeout(sdmTimeoutID);
        sdmTimeoutID = setTimeout(ShowDeviceMaintenance, 10000);
    } else {
        clearTimeout(sdmTimeoutID);
        sdmTimeoutID = -1;
    }
}
function saveDeviceMaintenance() {
    currentFMInitMiles = GetFloatFromTextbox(tbInitMilesID);
    currentFMCurrMiles = GetFloatFromTextbox(tbCurrMilesID);
    currentFMInitHours = GetFloatFromTextbox(tbInitHoursID);
    currentFMCurrHours = GetFloatFromTextbox(tbCurrHoursID);
    if (DeviceMaintenanceIsValid(currentFMInitMiles, currentFMCurrMiles, currentFMInitHours, currentFMCurrHours)) {
        DAL.SaveDeviceMaintenance(currentFMDeviceID, currentFMInitMiles, currentFMCurrMiles, currentFMInitHours, currentFMCurrHours);
        editDeviceMaintenance(false);
    } else {
        AlertMessage(ERROR_INVALID_ENTRY);
    }
}
function editDeviceMaintenance(edit) {
    deviceMaintenanceIsVisiable = !edit;
    ShowDeviceMaintenance();
    document.getElementById(tbInitMilesID).disabled = !edit;
    document.getElementById(tbCurrMilesID).disabled = !edit;
    document.getElementById(tbInitHoursID).disabled = !edit;
    document.getElementById(tbCurrHoursID).disabled = !edit;
    if (DeviceMaintenanceLoggedIn) {
        ShowItem(DeviceMaintenanceSaveID, edit);
        ShowItem(DeviceMaintenanceEditID, !edit);
    }
}

function showAlertCategories() {
    var sessionID = document.getElementById("SESSIONKEY").getAttribute("value");
    // Fill in already created alert Categories divFMAlertOpts
    var divFMAlertOpts = document.getElementById("divFMAlertOpts");
    divFMAlertOpts.options.length = 0;
    var results = Feed.SFMCtg(sessionID);
    for (var i = 0; i < divFMAlertOpts.Rows.length; i++) {
        results.options[i] = new Option(results.Rows[i].Name, results.Rows[i].TZKey);
        if (results.Rows[i].Name == "(GMT-06:00) Central Standard Time (US & Canada)") {
            SetIndexTo = ddlTimeZone.options.length - 1;
        }
    }
}

function showDeviceAlertDetail(index) { //
    // show detail screen and fill with device details retrieved in showDeviceAlerts
    DeviceMaintenanceDiv = "divFleetMgmtAlertDetail";
    clearFMAlertDetails();
    deviceMaintenanceIsVisiable = false;
    ShowFMButtons(true, true, false, false, true, true);


    currDMAlertDetail = DMAlertDetailList[index];

    document.getElementById('FMDeviceName').innerHTML = "Alert For " + currentFMDeviceName;
    document.getElementById('FMAlertID').value = currDMAlertDetail.id;

    document.getElementById('txtFMCatName').value = currDMAlertDetail.name;

    // Fill in Type (hours, miles, date) and change display units 
    var selCalType = document.getElementById('selCalType');
    for (var i = 0; i < selCalType.options.length; i++) {
        if (selCalType.options[i].value == currDMAlertDetail.unit) {
            selCalType.options[i].selected = true;
            document.getElementById('lbCalcType').innerHTML = selCalType.options[i].text;
            document.getElementById('lbCalcType2').innerHTML = selCalType.options[i].text;
            document.getElementById('lbCalcType3').innerHTML = selCalType.options[i].text;
            break;
        }
    }

    if (currDMAlertDetail.unit == DM_UNIT_KLM) {
        ConvertAlertValues(currDMAlertDetail.lastMainValue, currDMAlertDetail.alertValue, currDMAlertDetail.warnValue, currDMAlertDetail.unit);
    } else {
        document.getElementById('txtFMAlertValue').value = NumberAlterPrecision(currDMAlertDetail.alertValue, 2, true);
        document.getElementById('txtFMWarningValue').value = NumberAlterPrecision(currDMAlertDetail.warnValue, 2, true);
        document.getElementById('txtLastValue').value = NumberAlterPrecision(currDMAlertDetail.lastMainValue, 2, true);
    }

    document.getElementById('txtLastDate').value = FormatDate(currDMAlertDetail.lastMainDate);

    // Fill in SMS and Email options txtEmail ckFMEmail
    document.getElementById('ckFMEmail').checked = currDMAlertDetail.emailEnabled;
    document.getElementById('txtFMEmail').value = currDMAlertDetail.email;
    //txtFMPhone  selFMProvider  ckFMSMS
    document.getElementById('ckFMSMS').checked = currDMAlertDetail.smsEnabled;
    document.getElementById('txtFMPhone').value = currDMAlertDetail.smsNumber;

    var selFMProvider = document.getElementById('selFMProvider');
    //document.getElementById('selFMProvider').value = phone.substring(phone.indexOf("@") + 1);
    for (var i = 0; i < selFMProvider.options.length - 1; i++) {
        if (selFMProvider.options[i].value == currDMAlertDetail.smsCarrier) {
            selFMProvider.options[i].selected = true;
            break;
        }
    }
    document.getElementById('ckFMEnabled').checked = currDMAlertDetail.enabled;
    changeFMUnit();
    refreshAlertValues();
}
function saveAlertFMAlertDetails() {
    var changeStatusTo = -1;

    var DMADid = GetIntFromTextbox('FMAlertID');
    var DMADunit = GetSelectedValue('selCalType');
    var DMADsmsCarrier = GetSelectedValue('selFMProvider');
    var DMADenabled = isChecked('ckFMEnabled');


    //User text field.
    var DMADname = GetValueFromTextbox('txtFMCatName');
    var DMADlastMainDate = GetValueFromTextbox('txtLastDate');
    var DMADlastMainValue = GetValueFromTextbox('txtLastValue').replace(/,/g, '');
    var DMADwarnValue = GetValueFromTextbox('txtFMWarningValue').replace(/,/g, '');
    var DMADalertValue = GetValueFromTextbox('txtFMAlertValue').replace(/,/g, '');
    var DMADsmsEnabled = isChecked('ckFMSMS');
    var DMADsmsNumber = GetValueFromTextbox('txtFMPhone');
    var DMADemailEnabled = isChecked('ckFMEmail');
    var DMADemail = GetValueFromTextbox('txtFMEmail');

    if (!DeviceMaintenanceDetailIsValid(DMADname, DMADlastMainDate, DMADlastMainValue, DMADwarnValue, DMADalertValue, DMADsmsEnabled, DMADsmsNumber, DMADemailEnabled, DMADemail)) {
        return false;
    }
    
    var saveDMAlertDetail = new DMAlertDetail();
    saveDMAlertDetail.id = DMADid;
    saveDMAlertDetail.vehicleID = currentFMDeviceID;
    saveDMAlertDetail.name = DMADname;
    saveDMAlertDetail.unit = DMADunit;
    saveDMAlertDetail.alertValue = parseFloat(DMADalertValue);
    saveDMAlertDetail.warnValue = parseFloat(DMADwarnValue);
    saveDMAlertDetail.lastMainValue = parseFloat(DMADlastMainValue);
    saveDMAlertDetail.lastMainDate = new Date(DMADlastMainDate);
    saveDMAlertDetail.enabled = DMADenabled;
    saveDMAlertDetail.emailEnabled = DMADemailEnabled;
    saveDMAlertDetail.email = DMADemail;
    saveDMAlertDetail.smsEnabled = DMADsmsEnabled;
    saveDMAlertDetail.smsNumber = DMADsmsNumber;
    saveDMAlertDetail.smsCarrier = DMADsmsCarrier;
    saveDMAlertDetail.status = CalculateConvertedStatus(saveDMAlertDetail.lastMainValue, saveDMAlertDetail.alertValue, saveDMAlertDetail.warnValue, saveDMAlertDetail.unit);

    var smsFull = saveDMAlertDetail.smsNumber + AT + saveDMAlertDetail.smsCarrier;


    if (saveDMAlertDetail.unit == DM_UNIT_KLM) {
        saveDMAlertDetail.alertValue = KilometersToMiles(saveDMAlertDetail.alertValue);
        saveDMAlertDetail.warnValue = KilometersToMiles(saveDMAlertDetail.warnValue);
        saveDMAlertDetail.lastMainValue = KilometersToMiles(saveDMAlertDetail.lastMainValue);
    }
    if(currDMAlertDetail != null && currDMAlertDetail.status.number > saveDMAlertDetail.status.number){
        changeStatusTo = saveDMAlertDetail.status;
    }
    if (currDMAlertDetail == null || currDMAlertDetail.HasChanged(saveDMAlertDetail)) {
            saveDMAlertDetail.warnValue = saveDMAlertDetail.alertValue - saveDMAlertDetail.warnValue; //Database stores warning as value before alert.
            DAL.SaveFMAlert(saveDMAlertDetail.id, saveDMAlertDetail.emailEnabled, saveDMAlertDetail.email, saveDMAlertDetail.smsEnabled, smsFull, saveDMAlertDetail.smsNumber, saveDMAlertDetail.smsCarrier,
                        DEVICE_MAINTENANCE_TYPE, m_CurrentUser, saveDMAlertDetail.name, saveDMAlertDetail.vehicleID, saveDMAlertDetail.alertValue, saveDMAlertDetail.lastMainValue, saveDMAlertDetail.lastMainDate,
                        saveDMAlertDetail.warnValue, saveDMAlertDetail.unit, saveDMAlertDetail.enabled, changeStatusTo.number);
            showDeviceAlerts();
    } else {
        showDeviceAlerts();
    }
}

function DeviceMaintenanceDetailIsValid(DMADname, DMADlastMainDate, DMADlastMainValue, DMADwarnValue, DMADalertValue, DMADsmsEnabled, DMADsmsNumber, DMADemailEnabled, DMADemail) {
    if (String.IsNullOrEmpty(DMADname)) {
        AlertMessage(ERROR_INVALID_NAME);
        return false;
    }
    if (!DateIsValid(DMADlastMainDate)) {
        AlertMessage(ERROR_INVALID_LAST_MAIN_DATE);
        return false;
    }
    if (!(UnsignedDoubleIsValid(DMADlastMainValue) && UnsignedDoubleIsValid(DMADwarnValue) && UnsignedDoubleIsValid(DMADalertValue))) {
        AlertMessage(ERROR_INVALID_ALERT_WARNING_PERFORMED);
        return false;
    }
    if (parseFloat(DMADwarnValue) > parseFloat(DMADalertValue)) {
        AlertMessage(ERROR_WARNING_LESS_THAN_ALERT);
        return false;
    }
    if (DMADsmsEnabled) {
        if (!SMSNumberIsValid(DMADsmsNumber)) {
            AlertMessage(ERROR_INVALID_SMS);
            return false;
        }
    }
    if (DMADemailEnabled) {
        if (!EmailIsValid(DMADemail)) {
            AlertMessage(ERROR_INVALID_EMAIL);
            return false;
        }
    }
    return true;
}
function editDeviceMaintenanceDetail(edit) {
    Disable('txtFMCatName',!edit);
    Disable('selCalType',!edit);
    Disable('txtFMAlertValue',!edit);
    Disable('txtFMWarningValue',!edit);
    Disable('txtLastValue',!edit);
    Disable('txtLastDate',!edit);
    Disable('ckFMEnabled',!edit);
    Disable('ckFMEmail',!edit);
    Disable('txtFMEmail',!edit);
    Disable('ckFMSMS',!edit);
    Disable('txtFMPhone',!edit);
    Disable('selFMProvider',!edit);
}
function addAlertFMAlertDetails() {
    clearFMAlertDetails();
    ShowFMButtons(true, true, false, false, false, true);
}
function deleteAlertFMAlertDetails() {
    var FMAlertID = GetIntFromTextbox('FMAlertID');
    if (FMAlertID != -1) {
        DAL.DeleteFMAlert(FMAlertID);
    }
    showDeviceAlerts();
}
function clearFMAlertDetails() {
    currDMAlertDetail = null;
    document.getElementById(DeviceMaintenanceBackID).onclick = showDeviceAlerts;
    document.getElementById(DeviceMaintenanceSaveID).onclick = saveAlertFMAlertDetails;
    ShowItem("divDeviceMgmt", false);
    ShowItem("divFleetMgmtAlerts", false);
    ShowItem("divFleetMgmtAlertDetail", true);
    ShowItem("divFleetMgmtPassword", false);

    document.getElementById('FMAlertID').value = 0;
    // SMS and EMAIL
    document.getElementById('ckFMEmail').checked = false;
    document.getElementById('txtFMEmail').value = "";

    document.getElementById('ckFMSMS').checked = false;
    document.getElementById('txtFMPhone').value = "";
    document.getElementById('selFMProvider').value = "txt.att.net";

    // Name
    document.getElementById('txtFMCatName').value = "";
    //document.getElementById('txtFMCatDesc').value="";

    document.getElementById('txtFMAlertValue').value = 0;
    // Last Maintanence Fields
    document.getElementById('txtLastDate').value = FormatDate(new Date());
    document.getElementById('txtLastValue').value = 0;
    // Warning Value
    document.getElementById('txtFMWarningValue').value = 0;

    // Unit (hours, miles, date) 
    document.getElementById('selCalType').value = DM_UNIT_MILE;

    // Enabled
    document.getElementById('ckFMEnabled').checked = true;

    updateAlertValues(0, 0, 0, DM_UNIT_MILE);
    changeFMUnit();
}
function changeFMUnit() {
    var display = GetSelectedText('selCalType');
    document.getElementById('lbCalcType').innerHTML = display;
    document.getElementById('lbCalcType2').innerHTML = display;
    document.getElementById('lbCalcType3').innerHTML = display;
    refreshAlertValues();
}
function refreshAlertValues() {
    var DMADlastMainValue = GetValueFromTextbox('txtLastValue').replace(/,/g, '');
    var DMADwarnValue = GetValueFromTextbox('txtFMWarningValue').replace(/,/g, '');
    var DMADalertValue = GetValueFromTextbox('txtFMAlertValue').replace(/,/g, '');

    var DMADunit = GetSelectedValue('selCalType');
    updateAlertValues(DMADlastMainValue, DMADalertValue, DMADwarnValue, DMADunit);
}

function ConvertAlertValues(lastMainValue, alertValue, warnValue, unit) {
    if (unit == DM_UNIT_MILE) {
        document.getElementById('txtLastValue').value = NumberAlterPrecision(KilometersToMiles(lastMainValue), 2, true);
        document.getElementById('txtFMAlertValue').value = NumberAlterPrecision(KilometersToMiles(alertValue), 2, true);
        document.getElementById('txtFMWarningValue').value = NumberAlterPrecision(KilometersToMiles(warnValue), 2, true);
    } else if (unit == DM_UNIT_KLM) {
        document.getElementById('txtLastValue').value = NumberAlterPrecision(MilesToKilometers(lastMainValue), 2, true);
        document.getElementById('txtFMAlertValue').value = NumberAlterPrecision(MilesToKilometers(alertValue), 2, true);
        document.getElementById('txtFMWarningValue').value = NumberAlterPrecision(MilesToKilometers(warnValue), 2, true);
    }
}
function updateAlertValues(lastMainValue, alertValue, warnValue, unit) {
    lastMainValue = parseFloat(lastMainValue);
    alertValue = parseFloat(alertValue);
    warnValue = parseFloat(warnValue);

    var status = CalculateConvertedStatus(lastMainValue, alertValue, warnValue, unit);
    var displayUnit = GetSelectedText('selCalType');

    document.getElementById('CurrentValue').innerHTML = NumberAlterPrecision(GetCurrentValue(unit), 2, true, true) + " " + displayUnit;
    document.getElementById('NextWarningTime').innerHTML = NumberAlterPrecision((lastMainValue + warnValue), 2, true, true) + " " + displayUnit;
    document.getElementById('NextAlertTime').innerHTML = NumberAlterPrecision(lastMainValue + alertValue, 2, true, true) + " " + displayUnit;
    document.getElementById('CurrentStatus').innerHTML = "<img title=\"" + status.name + "\" alt=\"" + status.name + "\" src=\"images/FleetMgmt/Status" + status.number + ".png\" />   " + status.name;

    document.getElementById('NextWarningTime2').innerHTML = NumberAlterPrecision((lastMainValue + warnValue), 2, true) + " " + displayUnit;
    document.getElementById('NextAlertTime2').innerHTML = NumberAlterPrecision(lastMainValue + alertValue, 2, true) + " " + displayUnit;
}

function ShowFMButtons(back, save, add, edit, deleteB, changePassword) {
    ShowItem(DeviceMaintenanceBackID, back);
    if (DeviceMaintenanceLoggedIn) {
        ShowItem(DeviceMaintenanceSaveID, save);
        ShowItem(DeviceMaintenanceEditID, edit);
        ShowItem(DeviceMaintenanceAddID, add);
        ShowItem(DeviceMaintenanceDeleteID, deleteB);
        ShowItem(DeviceMaintenanceLoginID, false);
        ShowItem(DeviceMaintenanceChangePasswordID, changePassword);
    } else {
        ShowItem(DeviceMaintenanceSaveID, false);
        ShowItem(DeviceMaintenanceEditID, false);
        ShowItem(DeviceMaintenanceAddID, false);
        ShowItem(DeviceMaintenanceDeleteID, false);
        ShowItem(DeviceMaintenanceChangePasswordID, false);
        ShowItem(DeviceMaintenanceLoginID, changePassword);
    }
}

function DeviceMaintenanceIsValid(currentFMInitMiles, currentFMCurrMiles, currentFMInitHours, currentFMCurrHours) {
    return (UnsignedDoubleIsValid(currentFMInitMiles) && UnsignedDoubleIsValid(currentFMCurrMiles) && UnsignedDoubleIsValid(currentFMInitHours) && UnsignedDoubleIsValid(currentFMCurrHours));
}
function HandleNoPassword() {
    var isBlank = DAL.DeviceMaintenanceLogin(m_CurrentUser, "").value;
    if (isBlank) {
        LoginUser();
        ShowFleetMgmtPassword(true);
        ShowItemInherit("FMPasswordWelcome", true);
        ShowItemInherit("FMSuggestedItems", true);
        ShowItemInherit("FMLegend", true);
    }
}
function LoginUser() {
    var password = document.getElementById("FMPassword").value;
    DeviceMaintenanceLoggedIn = DAL.DeviceMaintenanceLogin(m_CurrentUser, password).value;
    if (!DeviceMaintenanceLoggedIn) {
        AlertMessage("Incorrect Password.");
    } else {
        HideFleetMgmtPassword();
        editDeviceMaintenanceDetail(true);
    }
        document.getElementById("FMPassword").value = "";
}
function UpdatePassword() {
    var password = PasswordsMatch();
    if (password != null) {
        var rtn = DAL.DeviceMaintenanceUpdatePassword(m_CurrentUser, password);
        if (rtn.value == 1) {
            HideFleetMgmtPassword();

            ShowItemInherit(DeviceMaintenanceChangePasswordID, true);
        } else {
            AlertMessage(ERROR_UPDATING_PASSWORD);
            document.getElementById("FMPassword").value = "";
        }
    } else {
        AlertMessage(ERROR_PASSWORD_DO_NOT_MATCH);
    }
}

function PasswordsMatch() {
    var password = GetValueFromTextbox("FMPassword");
    var password2 = GetValueFromTextbox("FMRePassword");

    if (password == password2) {
        document.getElementById("LblFMPasswordMsg").innerHTML = PASSWORDS_MATCH;
        return password;
    } else {
        document.getElementById("LblFMPasswordMsg").innerHTML = PASSWORDS_DO_NOT_MATCH;
        return null;
    }
}
function ShowFleetMgmtPassword(update) {
    DeviceMaintenanceDiv = "divFleetMgmtPassword";
    ShowItemInherit("divDeviceMgmt", false);
    ShowItemInherit("divFleetMgmtAlerts", false);
    ShowItemInherit("divFleetMgmtAlertDetail", false);
    ShowItemInherit("divFleetMgmtPassword", true);
    ShowItemInherit("FMPassword", true);
    ShowFMButtons(true, false, false, false, false, false);
    document.getElementById(DeviceMaintenanceBackID).onclick = HideFleetMgmtPassword;
    if (update) {
        document.getElementById("FMPasswordTitle").innerHTML = UPDATE_PASSWORD;
        ShowItemInherit("LblFMRePassword", true);
        ShowItemInherit("FMRePassword", true);
        ShowItemInherit("LblFMPasswordMsg", true);
    } else {
        document.getElementById("FMPasswordTitle").innerHTML = LOGIN;
        ShowItemInherit("LblFMRePassword", false);
        ShowItemInherit("FMRePassword", false);
        ShowItemInherit("LblFMPasswordMsg", false);
    }
    ShowItemInherit("FMPasswordLogin", !update);
    ShowItemInherit("FMPasswordSave", update);
    document.getElementById("FMPassword").value = "";
    deviceMaintenanceIsVisiable = false;
    document.getElementById("LblFMPasswordMsg").innerHTML = PASSWORDS_MATCH;
    SetFocus("FMPassword");
}
function HideFleetMgmtPassword() {
    document.getElementById("FMPassword").value = "";
    document.getElementById("FMRePassword").value = "";
    ShowItemInherit("FMPassword", false);
    ShowItemInherit("FMRePassword", false);
    document.getElementById("FMPasswordTitle").innerHTML = PASSWORDS_MATCH;
    showAlertDevices();
}
