﻿// Formats a json date value into a string dd-mm-yyyy hh:mm am/pm (12 hours time format)
function FormatJsonDate(jsonDateToFormat, trueToAppendTime) {
    var formattedDate = new Date(parseInt(jsonDateToFormat.substr(6)));
    var formattedDateAsString = "";

    formattedDateAsString = CompleteWithZeros(formattedDate.getDate()) + "-" + CompleteWithZeros((formattedDate.getMonth()) + 1) + "-" + formattedDate.getYear();
    if (trueToAppendTime) {
        formattedDateAsString = formattedDateAsString + " " + FormatMilitaryHourToMeridian(formattedDate);
    }

    return formattedDateAsString;
}

// Completes a specified number with left zeros if its value is less than 10
function CompleteWithZeros(valueToComplete) {
    var formattedValue = valueToComplete;
    if (valueToComplete < 10) {
        formattedValue = "0" + valueToComplete;
    }
    return formattedValue;
}

// Formats a specified time in 24 hours format to a 12 hours format
function FormatMilitaryHourToMeridian(dateToFormat) {
    var formattedTime = "";
    var retHours;
    var ampm = " PM";
    var hours = dateToFormat.getHours();
    var minutes = dateToFormat.getMinutes();

    if (hours >= 0 && hours <= 11) {
        ampm = " AM";
        retHours = hours;
    }
    else {
        retHours = hours - 12;
    }
    if (retHours < 0) {
        retHours = retHours * (-1);
    }
    if (retHours == 0) {
        retHours = 12;
    }

    formattedTime = CompleteWithZeros(retHours) + ":" + CompleteWithZeros(minutes) + ampm;
    return formattedTime;
}

// Function that works like the MaxLength but in multiline text controls (textarea)
function CharactersCountLeft(field, count, max) {
    if (field.value.length > max)
        field.value = field.value.substring(0, max);
    else
        count.value = max - field.value.length;
}

//Set the date and time values for the corresponding controls
function SetDateTimeToControls(dateTimeAmPmString, txtDate, dropDownHours, dropDownMinutes, dropDownMeridiam) {
    var dateTimeAmPmArray = dateTimeAmPmString.split(" ");
    var selectedDate = dateTimeAmPmArray[0].replace("-", "/").replace("-", "/");
    var time = dateTimeAmPmArray[1];
    var amPm = dateTimeAmPmArray[2];
    var startTimeSplit = time.split(":");
    var startHour = startTimeSplit[0] * 1;
    var startMinute = startTimeSplit[1] * 1;

    var selectedHour = startHour;
    var selectedMinute = "";
    var selectedMeridiam = amPm;

    if (startMinute == 0) {
        selectedMinute = "00";
    }
    else {
        selectedMinute = "30";
    }

    txtDate.val(selectedDate);
    dropDownHours.val(CompleteWithZeros(selectedHour));
    dropDownMinutes.val(selectedMinute);
    dropDownMeridiam.val(selectedMeridiam);

}

//Convert a string aussie date to a date object
function ConvertAussieStringDateToUTCDate(aussieStringDate, stringTime) {
    //Input format: dd/mm/yyyy, hh:mm am-pm
    var newDateString = "";
    var dateValues = aussieStringDate.split("/");
    var year = dateValues[2] * 1;
    var month = dateValues[1] - 1;
    var day = dateValues[0] * 1;
    var hours = 0;
    var minutes = 0;
    var seconds = 0;
    var milliSeconds = 0;

    if (stringTime != null && stringTime != "") {
        var timeValuesAll = stringTime.split(" ");
        var timeValues = timeValuesAll[0].split(":");
        hours = timeValues[0] * 1;
        minutes = timeValues[1] * 1;
        var amPm = timeValuesAll[1];

        if (amPm != null && amPm != undefined) {
            switch (amPm.toUpperCase()) {
                case "AM":
                    if (hours == 12) {
                        hours = 0;
                    }
                    break;
                case "PM":
                    if (hours < 12) {
                        hours = hours + 12;
                    }
                    break;
            }
        }
    }


    //Output format: javascript Date object with no time offset (GMT +0)
    return Date.UTC(year, month, day, hours, minutes, seconds, milliSeconds);
}

function ConvertDateObjectToInternationalStringDate(dateObject) {
    //Input format: javascript Date object
    var returnDateString = "";
    var year = dateObject.getYear();
    var month = dateObject.getMonth() + 1;
    var day = dateObject.getDate();
    var hours = dateObject.getHours();
    var minutes = dateObject.getMinutes();
    var seconds = dateObject.getSeconds();

    returnDateString = year + "-" + CompleteWithZeros(month) + "-" + CompleteWithZeros(day) + " " + CompleteWithZeros(hours) + ":" + CompleteWithZeros(minutes) + ":" + CompleteWithZeros(seconds);

    return returnDateString;
}

function Convert12hTimeStringTo24hTimeString(meridiamTimeString) {
    //Input format: hh:mm am-pm (12 hours format)
    var hours = 0;
    var minutes = 0;
    var returnTimeString = "";
    var timeValuesAll = meridiamTimeString.split(" ");
    var timeValues = timeValuesAll[0].split(":");
    hours = timeValues[0] * 1;
    minutes = timeValues[1] * 1;
    var amPm = timeValuesAll[1];

    switch (amPm.toUpperCase()) {
        case "AM":
            if (hours == 12) {
                hours = 0;
            }
            break;
        case "PM":
            if (hours < 12) {
                hours = hours + 12;
            }
            break;
    }

    returnTimeString = CompleteWithZeros(hours) + ":" + CompleteWithZeros(minutes);
    return returnTimeString;
}

// Adds the trim() function to the string object, to remove blank spaces
String.prototype.trim = function () { return this.replace(/^([\s\t\n]|\&nbsp\;)+|([\s\t\n]|\&nbsp\;)+$/g, ''); }

//Removes potentialy dangerous characters
function RemoveTheHTMLFromTextBox(obj) {

    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    var isValidKey = false;

    // Allow special keys that do not affect the text entered and are useful for the user.
    switch (charCode) {
        case 8:     // Backspace
        case 9:     // Tab
        case 13:    // Enter
        case 36:    // Home Key
        case 37:    // Left arrow key
        case 38:    // Up arrow key
        case 39:    // Right arrow key
        case 40:    // Down arrow key
        case 46:    // Delete
            isValidKey = true;
            break;
        default:
            break;
    }

    if (!isValidKey) {
        var inputValue = obj.val();
        obj.val(obj.val()
            .replace(/“/g, "")          //Removes “
            .replace(/”/g, "")          //Removes ”
            .replace(/"/g, "")          //Removes "
            .replace(/</g, "")          //Removes <
            .replace(/>/g, "")          //Removes >
            .replace(/\'/g, "")         //Removes '
            .replace(/\\/g, "")         //Removes \
            .replace(/\&amp;/g, "")     //Removes &amp;
            .replace(/\&AMP;/g, "")     //Removes &AMP;
            .replace(/&/g, "and"));     //Removes &
    }
}

// Replaces double quotes in a string
function ReplaceDoubleQuotes(valToReplace) {
    return valToReplace.replace(/"/g, "'")
                        .replace(/“/g, "")
                        .replace(/”/g, "");
}

// Allows only the keys needed for numeric values to be entered in a text field.
// Call this function on the onkeydown event for the text control.
function AllowNumbersOnly(e) {

    var e = event || evt; // for trans-browser compatibility
    var charCode = e.which || e.keyCode;
    var isValidKey = false;

    switch (charCode) {
        case 8:     // Backspace
        case 9:     // Tab
        case 13:    // Enter
        case 36:    // Home Key
        case 37:    // Left arrow key
        case 38:    // Up arrow key
        case 39:    // Rigth arrow key
        case 40:    // Down arrow key
        case 46:    // Delete

        case 48:    // Keyboard 0
        case 49:    // Keyboard 1
        case 50:    // Keyboard 2
        case 51:    // Keyboard 3
        case 52:    // Keyboard 4
        case 53:    // Keyboard 5
        case 54:    // Keyboard 6
        case 55:    // Keyboard 7
        case 56:    // Keyboard 8
        case 57:    // Keyboard 9


        case 96:    // Numeric keypad 0
        case 97:    // Numeric keypad 1
        case 98:    // Numeric keypad 2
        case 99:    // Numeric keypad 3
        case 100:   // Numeric keypad 4
        case 101:   // Numeric keypad 5
        case 102:   // Numeric keypad 6
        case 103:   // Numeric keypad 7
        case 104:   // Numeric keypad 8
        case 105:   // Numeric keypad 9

        case 109:   // Numeric keypad -
        case 110:   // Numeric keypad .

        case 188:   // Keyboard ,
        case 190:    // Keyboard .
            isValidKey = true;
            break;
        default:
            break;
    }

    if (e.shiftKey || e.shiftLeft) {
        isValidKey = false;
    }

    return isValidKey;

} 

// Shows a confirmation message prior of a delete action
function ShowDeleteConfirmationMessage() {
    return confirm('Are you sure you want to delete this record?\r\n\r\nThis action cannot be undone and you may be deleting all other references associated with this record.')
}

// Shows a confirmation message prior of a change password operation
function ShowChangePasswordConfirmationMessage() {
    return confirm("Are you sure you want to change the password?\r\n\r\nThis action cannot be undone.");
}

// Shows a confirmation message prior of a change password operation
function ShowResubmitConfirmationMessage() {
    return confirm("Are you sure you want to resubmit this information for approval?\r\n\r\nThis action cannot be undone.");
}

// Function to download a specified file
function DownloadFile(fileId) {
    window.location.href = "DownloadDocument.aspx?docId=" + fileId;
}

// Replaces a &amp; character for &
function ReplaceHtmlAmpersand(arrayToReplace) {
    for (var i = 0; i <= arrayToReplace.length-1; i++) {
        arrayToReplace[i] = arrayToReplace[i].replace(/&amp;/g, '&');
    }
    return arrayToReplace;
}
