﻿
// Common javascript functions
//

//////////////////////////////////////////////////////////////////////////////
// General functions

function CMN_AppRootUrl() {
    /// <summary>
    /// Gets the relative url of the application root, with a trailing slash.
    /// It comes from a hidden field which is created by the master page.
    /// </summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>7/29/2008</created>

    return document.getElementById("hdnAppRootUrl").value;
}

function CMN_SetValue(elementId, val) {
    /// <summary>
    /// Sets the value property of a DOM element and returns false.
    /// </summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>5/5/2009</created>

    $get(elementId).value = val;
    return false;
}


//////////////////////////////////////////////////////////////////////////////
// Formatting and validation functions

function CMN_ReformatTextBoxNumber(objTextbox, decimalPlaces, formatString) {
    /// <summary>
    /// If the text box contains a number, reformats the number according to the format string.
    /// Use in the onblur event:
    /// [asp:TextBox ID="..." runat="server" onblur="CMN_ReformatTextBoxNumber(this, 2, 'CSP');" /]
    /// </summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>7/29/2008</created>

    var sVal = CMN_UnformatNumber(objTextbox.value);

    if (!isNaN(sVal)) {
        objTextbox.value = CMN_FormatNumber(sVal, decimalPlaces, formatString);
    }
}

function CMN_FormatNumber(num, decimalPlaces, formatString) {
    /// <summary>
    /// Formats a number with the specified number of decimal places and in the specified format.
    /// This method is much faster than String.format().
    /// </summary>
    /// <param name="decimalPlaces" type="int">
    /// Number of decimal places, or null/-1 will just remove trailing zeros.
    /// </param>
    /// <param name="formatString" type="string">
    /// "N"   =>  -1234.56      "C"   =>  -$1234.56      "P"   =>  -1234.56%
    /// "NS"  => -1,234.56      "CS"  => -$1,234.56      "PS"  => -1,234.56%
    /// "NP"  =>  (1234.56)     "CP"  =>  ($1234.56)     "PP"  =>  (1234.56%)
    /// "NSP" => (1,234.56)     "CSP" => ($1,234.56)     "PSP" => (1,234.56%)
    /// Percentages are *not* multiplied by 100.
    /// </param>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>10/14/2008</created>

    var isNegative = (num < 0);

    var sNum;
    if (decimalPlaces >= 0) {
        sNum = Math.abs(num).toFixed(decimalPlaces);
    }
    else {
        // Converting to a number and then to a string formats the number
        sNum = String(Math.abs(num));
    }

    var prefix = "";
    var suffix = "";

    // Add a currency symbol or percent sign
    switch (formatString.charAt(0)) {
        case "N":
            break;
        case "C":
            prefix = "$ ";
            break;
        case "P":
            suffix = " %";
            break;
    }

    // Add commas if requested
    if (formatString.charAt(1) == "S" || formatString.charAt(2) == "S")  // "S" as the second or third letter
    {
        sNum = CMN_private_addSeparators(sNum);
    }

    // Add negative notation if required and put everything together
    if (isNegative) {
        if (formatString.charAt(1) == "P" || formatString.charAt(2) == "P")  // "P" as the second or third letter
        {
            sNum = "(" + prefix + sNum + suffix + ")";
        }
        else {
            sNum = "-" + prefix + sNum + suffix;
        }
    }
    else {
        sNum = prefix + sNum + suffix;
    }

    return sNum;
}

function CMN_UnformatNumber(val) {
    /// <summary>
    /// Removes formatting from a number (stored in a string variable).
    /// </summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>9/9/2008</created>

    var sval = new String(val);

    // Remove '$' ',' ' '
    //
    sval = sval.replace(/[$, ]/gi, "");

    // If it's surrounded by parentheses, replace them with a minus sign in front
    //
    sval = sval.replace(/^\((.*)\)$/, "-$1");

    if (isNaN(sval) || sval == "") {
        // If it's not a number, give up and return NaN (not a number)
        return NaN;
    }
    else {
        return Number(sval);
    }
}

function CMN_private_addSeparators(num) {
    /// <summary>
    /// Adds commas to a number.
    /// </summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>10/14/2008</created>

    sNum = String(num);

    var decimalPos = sNum.indexOf(".");
    var sIntegerPart = sNum;
    var sFractionPart = "";

    if (decimalPos != -1) {
        sIntegerPart = sNum.substring(0, decimalPos);
        sFractionPart = "." + sNum.substring(decimalPos + 1, sNum.length);
    }

    var re = /(\d+)(\d{3})/;
    while (re.test(sIntegerPart)) {
        sIntegerPart = sIntegerPart.replace(re, '$1,$2');
    }

    return sIntegerPart + sFractionPart;
}

/// <summary>
/// Determines whether the string is a valid currency format
/// </summary>
/// <param name="strMoney">The string to be validated</param>
/// <param name="allowEmpty">Whether empty string is allowed</param>
/// <param name="stripCharacters">Whether to strip out ('$', ',', ' ')</param>
/// <returns>Input string in valid money format, empty if not possible</returns>
function CMN_isValidCurrency(strMoney, allowEmpty, stripCharacters) {

    //if we're allowed to strip out characters
    if (stripCharacters) {
        // Remove surrounding parentheses, plus '$' ',' ' '
        strMoney = strMoney.replace(/^\((.*)\)$/, "$1");
        strMoney = strMoney.replace(/[$, ]/gi, "");
    }

    //no string specified
    if (strMoney == "") {
        return allowEmpty;
    }
    // string specified -- is it valid?
    else {
        return new RegExp("^-?[0-9]*[.]?[0-9]{0,2}$").test(strMoney);
    }
}

/// <summary>
/// Determines whether the string is a valid integer format
/// </summary>
/// <param name="strMoney">The string to be validated</param>
/// <param name="allowEmpty">Whether empty string is allowed</param>
/// <param name="stripCharacters">Whether to strip out ('$', ',', ' ')</param>
/// <returns>Input string in valid money format, empty if not possible</returns>
function CMN_isValidInteger(strInteger, allowEmpty, stripCharacters) {

    var nInteger;

    // First check for empty string
    //
    if (stripCharacters) {
        strInteger = strInteger.trim();
    }

    if (strInteger == "") {
        // Empty string
        return allowEmpty;
    }
    else {
        // It's not an empty string.
        // If we're allowed to strip out characters, do so now and convert to a number.
        //
        if (stripCharacters) {
            nInteger = CMN_UnformatNumber(strInteger);
        }

        if (isNaN(nInteger)) {
            // It's not a number at all.
            return false;
        }
        else {
            // It's a number. Convert back to a string and check whether it's in the right format.
            strInteger = new String(nInteger);
            return new RegExp("^-?[0-9]+$").test(strInteger);
        }
    }
}

/// <summary>
/// Determines whether the string is a valid decimal format
/// </summary>
/// <param name="strDecimal">The string to be validated</param>
/// <param name="allowEmpty">Whether empty string is allowed</param>
/// <param name="stripCharacters">Whether to strip out ('$', ',', ' ', '%')</param>
/// <param name="decimalPlaces">How many decimal places to allow (-1 = unlimited)</param>
/// <returns>Input string in valid money format, empty if not possible</returns>
function CMN_isValidDecimal(strDecimal, allowEmpty, stripCharacters, decimalPlaces) {

    //if we're allowed to strip out characters
    if (stripCharacters) {
        // Remove surrounding parentheses, plus '$' ',' ' '
        strMoney = strMoney.replace(/^\((.*)\)$/, "$1");
        strMoney = strMoney.replace(/[$%, ]/gi, "");
    }

    //no string specified
    if (strMoney == "") {
        return allowEmpty;
    }
    // string specified -- is it valid?
    else if (decimalPlaces > 0) {
        return new RegExp("^-?[0-9]*[.]?[0-9]{0," + decimalPlaces + "}$").test(strMoney);
    }
    else {
        return new RegExp("^-?[0-9]*[.]?[0-9]$").test(strMoney);
    }
}

//////////////////////////////////////////////////////////////////////////////
// Functions to open windows

function CMN_openWindow(url, windowName, width, height, top, left) {
    /// <summary>Opens a URL in a new window.</summary>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>7/29/2008</created>

    paramStr = "";
    if (Number(width) > 0) { paramStr += ",width=" + width; }
    if (Number(width) > 0) { paramStr += ",height=" + height; }
    if (Number(width) > 0) { paramStr += ",top=" + top; }
    if (Number(width) > 0) { paramStr += ",left=" + left; }
    paramStr += ",scrollbars=no,resizable=no";

    var newWindow = window.open(url, windowName, paramStr);

    if (newWindow.focus) {
        newWindow.focus();
    }

    return newWindow;
}

function CMN_openReportStatus(reportRequestId) {
    /// <summary>Opens a window to monitor the status of a report request.</summary>
    /// <param name="reportRequestId" type="int">The request id of the report to monitor.</param>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>11/24/2008</created>

    var url = CMN_AppRootUrl() + 'Reports/ReportStatus.aspx?reqid=' + reportRequestId;

    return CMN_openWindow(url, "", 400, 275, 20, 20);
}

function CMN_openReportPdf(reportRequestId) {
    /// <summary>Opens the report PDF in a new window</summary>
    /// <param name="reportRequestId" type="int">The request id of the report to display.</param>
    /// <creator>Michael Deutsch (Data-Rite)</creator>
    /// <created>11/24/2008</created>

    var url = CMN_AppRootUrl() + 'Reports/ViewPdf.aspx?reqid=' + reportRequestId;

    return CMN_openWindow(url, "", 900, 700, 20, 20);
}
