﻿function isFirefox() {
    return ( navigator.userAgent.indexOf("Firefox") > -1 );
}
function getBrowser() {
    var sBrowser = "";
    for (var sPropertyName in navigator) { 
        sBrowser += sPropertyName + ": " + navigator[sPropertyName] + "\n";
    }
    return sBrowser;
}

function formatDate(dt) {
    return (dt.getMonth() + 1).toString() + "/" + dt.getDate().toString() + "/" + dt.getFullYear().toString();
}

function formatMoney( Amount, iDecimals, sCurrencySymbol){
    if ( "" + sCurrencySymbol == "undefined" ){
        sCurrencySymbol = "$";
    }
    if ("" + iDecimals == "undefined") {
        iDecimals = 0;
    }
    return sCurrencySymbol + formatDecimal(Amount, iDecimals);
}

function formatPercent(Amount, iDecimals) {
    if ("" + iDecimals == "undefined") {
        iDecimals = 0;
    }
    return formatDecimal(Amount * 100,iDecimals) + "%";
}

function formatDecimal( Amount, iDecimals){
    var sAmount = cleanMoney( Amount.toString() ).toString();
    var sNewAmount="";
    var sDecimals="";
    var sNewDecimals = "";
    var iDecPointIndex = sAmount.indexOf(".") ;
    if ( iDecPointIndex > -1 ){
        sNewDecimals = sAmount.substring(iDecPointIndex+1,iDecPointIndex+1 + iDecimals);
        sAmount = sAmount.substring(0,iDecPointIndex);
    }
    if ( iDecimals > 0 && sNewDecimals.length < iDecimals ){
        for ( var i=sNewDecimals.length; i < iDecimals; i++ ){
            sNewDecimals += "0";
        }
    }
    
    // insert commas
    var iDigits = 0;
    for ( var b = sAmount.length -1; b >= 0; b--){
        if ( iDigits > 0 && iDigits % 3 == 0 ){
            sNewAmount = "," + sNewAmount;
        }
        sNewAmount = sAmount.substring(b,b+1) + sNewAmount;
        iDigits++;
    }
    if ( sNewDecimals != "" ){
        sNewAmount = sNewAmount + "." + sNewDecimals;
    }
    // clean up negatives
    sNewAmount = sNewAmount.replace(/-,/,"-");
    return sNewAmount;
}

function cleanMoney( sAmount, sCurrencySymbol ){
    if ( "" + sCurrencySymbol == "undefined" ){
        sCurrencySymbol = "$";
    }
    var sClean = sAmount.replace(sCurrencySymbol, "").replace(/,/g, "").replace(/k/g, "000").replace(/\(/g, "-").replace(/\)/g, "");
    sClean = parseFloat(sClean);
    if ( sClean.toString() == "NaN" ){
        sClean = 0;
    }
    
    return sClean;
}

function cleanPercent( sAmount ){
    var sClean = sAmount.replace(/\%/,"").replace(/,/,"");
    sClean = parseFloat(sClean);
    if ( sClean.toString() == "NaN" ){
        sClean = 0;
    }
    if ( sClean != 0 ){
        sClean = sClean/100;
    }
    return sClean;
}

function roundFloat(flNumber, iDecimalDigits) {
    // Thanks to http://forums.devarticles.com/javascript-development-22/javascript-to-round-to-2-decimal-places-36190.html
    var result = Math.round(flNumber * Math.pow(10, iDecimalDigits)) / Math.pow(10, iDecimalDigits);
    return result;

}


function getDropDownValue(sId, oSelect){
    if ( oSelect == null){
     oSelect = document.getElementById(sId);
    }
     if (oSelect == null && sId == "") {
         return;
     }
    if ( oSelect == null ){
        alert("getDropDownValue: " + sId + " not found!");
        return;
    }
    if ( oSelect.options.length == 0 ){
        return "";
    }
    if (oSelect.selectedIndex == -1) {
        return "";
    }
    return oSelect.options[oSelect.selectedIndex].value;
}

function getDropDownText(sId, oSelect){
    if ( oSelect == null){
     oSelect = document.getElementById(sId);
    }
    if ( oSelect == null ){
        alert("getDropDownValue: " + sId + " not found!");
        return;
    }
    return oSelect.options[oSelect.selectedIndex].text;
}


function getMultipleSelectValues(sId, oSelect) {
    // returns a string of the selected values separated by a semi-colon ;
    if ( oSelect == null){
     oSelect = document.getElementById(sId);
    }
     if (oSelect == null && sId == "") {
         return;
     }
    if ( oSelect == null ){
        alert("getMultipleSelectValue: " + sId + " not found!");
        return;
    }
    if ( oSelect.options.length == 0 ){
        return "";
    }
    if (oSelect.selectedIndex == -1) {
        return "";
    }
    var sOut = "";
    for (var i = 0; i < oSelect.options.length; i++) {
        if (oSelect.options[i].selected) {
            sOut += oSelect.options[i].value + ";";
        }
    }
    if (sOut.length > 1) {
        sOut = sOut.substring(0, sOut.length - 1); // take out last semi-colon
    }
    return sOut;
}
function getSelectedRadioValue(sName){
    var sValue = null;
    var oaRads = document.getElementsByName( sName );
    if ( oaRads.length > 0 ){
        for ( var i = 0; i < oaRads.length; i++ ){
            if ( oaRads[i].checked == true ){
                sValue = oaRads[i].value;
                break;
            }
        }
    }
    
    return sValue;
}

function cancelSubmit(e){
	if (e){
		try{
			e.preventDefault(); // for FireFox
		}
		catch(e){
			// continue
		}
	}
	return false;// works only with IE
}
function submitWithConfirm(sControlID){
    if ( sControlID ){
	    if ( confirm('Are you sure that you want to proceed? ' ) ) {
		    try{
			    document.forms[0].__EVENTTARGET.value = sControlID;
		    }
		    catch(f){
		        document.forms[0].submit();
		        //alert(f);
		    }
	    }
	    else{
    		
		    try{
			    document.forms[0].__EVENTTARGET.value = "";
		    }
		    catch(ex){
			    // keep going
			    //alert(ex);
		    }
    		
		    if ( document.all){
			    document.forms[0].attachEvent("onsubmit",cancelSubmit);
		    }
		    else{
			    document.forms[0].addEventListener("submit",cancelSubmit,false);
		    }
		    try { // for linkButton
		    document.getElementById(sControlID).href='#';
			    }
		    catch(e)
		    {
			    // not necessary
			    //alert(e);
		    }
		}
		return null;
	} // got controlid
	else{
	    alert('Control ID is NULL!!!');
	    return null;
	}
}

function requiredValueCheck(oInput, sSaveFunction){
    if ( oInput.value == ""
        || oInput.value == "0" ){
        oInput.focus();
        oInput.select();
            
    }
    else{
        if ( oInput.value != msCurValBuffer ){
            eval(sSaveFunction);
        }
    }
}

// *********** SELECT functions **********************************************************************
    function filterSelect(sFilter, oSELECT){
     // selects the next items of select (list or drop-down box) that matches the string passed in
     // can be called by on mouse-up or onchange events of a textbox
        sFilter = sFilter.toLowerCase();
        for ( i=0; i < oSELECT.options.length; i++ ){
            if ( oSELECT.options[i].text.toLowerCase().indexOf( sFilter ) == 0 ){
                oSELECT.selectedIndex = i;
                break;
            }
        }
        
    }

    function filterFillSelectFromArray(sFilter, oSELECT, saItems){
     // Filters a the items of select (list or drop-down box) by the string passed in
     // can be called by on mouse-up or onchange events of a textbox
        if ( oSELECT == null || saItems == null )
        {
            return;
        }
        sFilter = sFilter.toLowerCase();
        clearAllSelectOptions(oSELECT)
        for ( i=0; i < saItems.length-1; i++ ){
            if ( saItems[i][1].toLowerCase().indexOf( sFilter ) > -1 || sFilter == "" ){
                oSELECT.options[oSELECT.options.length] = new Option(saItems[i][1], saItems[i][0]);
            }
        }
        if (oSELECT.options.length > 0 ){
            oSELECT.selectedIndex = 0;
        }        
    }
    
    function fillSelectFromArray(oSELECT, saItems, sSelectText, bExactMatch){
     // fills a Select with the items in the array and selects the one where the text matches sSelectText
     // The text comparison is not case SensiTivE!
        if ( oSELECT == null || saItems == null )
        {
            return;
        }
        clearAllSelectOptions(oSELECT)
        var iSelValue="";
        var iSelIdx = -1;
        if (bExactMatch == true) {
            for (i = 0; i < saItems.length - 1; i++) {
                if ( (saItems[i][1] == sSelectText || saItems[i][0] == sSelectText) && iSelIdx == -1) {
                    iSelIdx = i;
                    iSelValue = saItems[i][0];
                }
                oSELECT.options[oSELECT.options.length] = new Option(saItems[i][1], saItems[i][0]);
            }        
        }
        else {
            for (i = 0; i < saItems.length - 1; i++) {
                if (saItems[i][1].toLowerCase().indexOf(sSelectText.toLowerCase()) > -1) {
                    iSelIdx = i;
                    iSelValue = saItems[i][0];
                }
                oSELECT.options[oSELECT.options.length] = new Option(saItems[i][1], saItems[i][0]);
            }
        } // exact match 
        
        oSELECT.selectedIndex = iSelIdx;
        return iSelValue;
    }
    
    function clearAllSelectOptions(oSELECT){
        for ( i= oSELECT.options.length - 1; i >= 0; i-- ){
            oSELECT.remove(i);
        }
    }
    
    function selectOptionByValue(oSELECT, value){
        for ( i=0; i < oSELECT.options.length; i++ ){
            if ( oSELECT.options[i].value == value ){
                oSELECT.selectedIndex = i;
                break;
            }
        }
    }
    
    function selectOptionByText(oSELECT, text){
        for ( i=0; i < oSELECT.options.length; i++ ){
            if ( oSELECT.options[i].text == text ){
                oSELECT.selectedIndex = i;
                break;
            }
        }
    }
    
    function moveOption(oOriginSelect, oDestinationSelect){
        var iSelIdx = oOriginSelect.selectedIndex;
        if ( iSelIdx > -1 ){
            var origOption = oOriginSelect.options[iSelIdx];
            // add destination
            oDestinationSelect.options[oDestinationSelect.options.length] = new Option(origOption.text, origOption.value);
            // delete origin
            oOriginSelect.remove(iSelIdx);
        }
    }
    function moveOptions(oOriginSelect, oDestinationSelect){
            for ( i=oOriginSelect.options.length-1; i>=0; i--){
                if ( oOriginSelect.options[i].selected ){
                    var origOption = oOriginSelect.options[i];
                    // add destination
                    oDestinationSelect.options[oDestinationSelect.options.length] = new Option(origOption.text, origOption.value);
                    // delete origin
                    oOriginSelect.remove(i);
                }
            }
        }
    
    function selectAllOptions(oSELECT){
        for ( i=0; i < oSELECT.options.length; i++ ){
            oSELECT.options[i].selected = true;
        }
    }

    function selectOptionByValue(oSELECT, sValue) {
        if (oSELECT == null) { return; }
        for (i = 0; i < oSELECT.options.length; i++) {
            if (oSELECT.options[i].value == sValue) {
                oSELECT.options[i].selected = true;
                return;
            }
        }
    }
    
    
    function removeOptionByValue( sSelectId, sValue ){
        var oSelect = document.getElementById(sSelectId);
        for ( var i = oSelect.options.length - 1; i >= 0; i-- ){
            if ( oSelect.options[i].value == sValue ){
                oSelect.options.remove(i);
                return;
            }
        }
    }

    function removeAllOptions( sSelectId ){
        var oSelect = document.getElementById(sSelectId);
        for ( var i = oSelect.options.length - 1; i >= 0; i-- ){
            oSelect.options.remove(i);
        }
    }
    
// *********** Array from String *************************************************************************     
    
    function getTwoDimArray(sData){
        var saData = sData.split("|| "); //1~One|| 2~two|| 3~three
        for ( i = 0; i < saData.length; i++ ){
            saData[i] = saData[i].split("~");
        }
        return saData;
    }
// **************************************************

function parseHiddenValueFromDropDownText( sSelectId ){
    var sText = "";
    try{
        var oSelect = document.getElementById(sSelectId);
        if ( oSelect ){
            sText = oSelect.options[oSelect.selectedIndex].text;
            // find beginning of long string
            var iIdx = sText.indexOf(" . . . . . . . . . .");
            if ( iIdx == -1 ){
                alert("This policy is not available for viewing.\n\nIf it should be, please contact LexLink support.");
                return "";
            }
            sText = sText.substring(iIdx, sText.length );
            sText = sText.replace(/\s\.\s\./g,"");
        }
        else{
            alert(sSelectId + " not found!");
        }
    }
    catch(e){
        sText = e.message;
    }
    return sText

}

function textCounter(sender, iMaxLength) {
    var sExemptions = ",8,37,38,39,40,46,";
    var iCurrLength = sender.value.length;
    var sKeyCode = "" + window.event.keyCode;
    if (sExemptions.indexOf("," + sKeyCode + ",") > -1) {
        return;
    }
    window.status = " " + formatDecimal(iCurrLength, 0) + " out of " + formatDecimal(iMaxLength,0);
    if (iCurrLength > iMaxLength) {
        alert("You have used up all the text space available for " + sender.name + " (" + iMaxLength + ")\n\nYour input is going to be truncated.");
        sender.value = sender.value.substring(0, iMaxLength - 1);
        sender.select();
        return;
    }
    sender.title = iMaxLength - iCurrLength + " spaces left.";
}

function overwriteCtrlValueWithConfirm(oControl, sValue, sPromptName) {
    var sCurrentValue = oControl.value;
    var sPrompt = "Would you like to overwrite the current value of " 
                    + sPromptName + " (" + sCurrentValue 
                    + ")\nwith this new value: " + sValue + "?";
    if (sCurrentValue != "" && sCurrentValue != sValue ) {
        if (confirm(sPrompt) == false) {
            return false;
        }
    }

    oControl.value = sValue;
    return true;
}

function positionCursor(sId) {
    var obj = document.getElementById(sId);
    if (obj == null) {
        alert(sId + " does not exist.\n\n(positionCursor(" + sId + "))");
        return;
    }
    try {
        var sVal = obj.value;
        var range = obj.createTextRange();
        range.move("sentence", 1);
        range.select();
    }
    catch (e) {
        window.status = e;
    }
}


function doCalendarSetup(sTextBoxID, sImgID) {
    Calendar.setup(
            {
                inputField: sTextBoxID,
                ifFormat: "%m/%d/%Y",
                button: sImgID,
                align: "T1",
                electric: false // only update field when calendar is closing
            }
        );
        }

function disableControl(sControlID, sStatusDivID) 
{
    var divStatus = document.getElementById(sStatusDivID);
    var oControl = document.getElementById(sControlID);
    if (oControl != null) {
        oControl.disabled = true;
    }
    else {
        if ( divStatus != null )
        {
            divStatus.innerHTML = "<br/>" + sControlID + " not found.<br/>";
        }
    }
}

function simpleDateTest(sDate) {
    var today = new Date();
    var sErrorDefault = "Please provide a date in the format mm/dd/yyyy, such as " + formatDate(today);
    var iaMonthsDays = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var saMonthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    var sError = "";
    var saUSDate = sDate.toString().split(/\//);

    if (saUSDate.length <= 2) {
        sError = sErrorDefault;
    }
    else {
        // month and day check
        var iMonth = parseInt(saUSDate[0].substring(0, 1) == "0" ? saUSDate[0].substring(1, 2) : saUSDate[0]);
        
        if (iMonth.toString() == "NaN") {
            sError = sErrorDefault;
        }
        else {
            var iDay = parseInt(saUSDate[1].substring(0, 1) == "0" ? saUSDate[1].substring(1, 2) : saUSDate[1]);
            if (iDay.toString() == "NaN") {
                sError = sErrorDefault;
            }
            else {
                if (iMonth <= 12 && iMonth >= 1) {
                    if (iDay > iaMonthsDays[iMonth - 1]) {
                        sError = saMonthNames[iMonth - 1] + " does not have " + iDay.toString() + " days.";
                    }
                }
                else {
                    sError = iMonth.toString() + " cannot be converted into a valid month.";
                }
            }
        }

        // year check
        var iYear = parseInt(saUSDate[2]);
        if (iYear.toString() == "NaN") {
            sError == sErrorDefault;
        }
        else {
            if (iYear > today.getFullYear() + 2
                || iYear < today.getFullYear() - 110) {
                sError = "\"" + sDate + "\" is outside the acceptable date range.";
                }
        }
        
    }

    if (sError != "") {
        alert(sError);
    }
    
    return ( sError == "" );
}