/*******************************************************************************
* Miscellaneous.js
*
* @package nascla
* @author Preston McMurry (prestonm3@mcmurry.com)
* @version 1.0
* @copyright (C) Copyright 2009 by McMurry, Inc.
*
*******************************************************************************/

/***************************************************************************
* ValidateWrapper()
*
* @param varchar strButton
* @return boolean True if valid, otherwise false
***************************************************************************/
function ValidateWrapper( strButton ) {

    var strURL = "";

    if ( strButton == "Save" ) {

        if ( validate() == true ) {
            document.MainForm.elements['Submit'].value = "Submit";
        } else {
            return false;
        }

    } else if ( strButton == "Delete" ) {

        document.MainForm.elements['Action'].value = "Delete";
        document.MainForm.elements['Submit'].value = "Submit";
        document.MainForm.submit();

    }
}

/***************************************************************************
* ConfirmDelete()
*
***************************************************************************/
function ConfirmDelete( strButton, strMsg ) {

    if ( strMsg ) {
        strMsg += "\n\r";
    } else {
        strMsg = "";
    }

    strMsg += "Click 'OK' to delete.";

    if ( !confirm( strMsg ) ) {
        return false;
    }

    return ValidateWrapper( strButton );
}

/***************************************************************************
* reset()
*
***************************************************************************/
function reset() {
    /*
    ** Click the hidden input where type="reset".
    */
    document.getElementById('Reset').click();
}

/***************************************************************************
* TestURL()
*
* @param object ctrl
***************************************************************************/
function TestURL( elName ) {

    var URL;

    URL = trim( document.MainForm.elements[elName].value );

    if ( URL == "" ) {
        return false;
    }

    window.open( URL, "CheckURL", 'status,resizable,scrollbars,width=600,height=480,left=200,top=200')
}

/***************************************************************************
* trimall()
*
* Only trim elements which may contain text. Trimming other elements may
* cause undesirable side effects that take many wasted hours to figure out.
* (For instance, trimming a multiple select control, lops off all but the
* first selected row.)
*
* These are javascript elements:
*
*    button          =
*    checkbox        =
*    file            =
*    hidden          =
*    image           =
*    password        = trim
*    radio           =
*    reset           =
*    select-one      =
*    select-multiple =
*    submit          =
*    text            = trim
*    textarea        = trim
***************************************************************************/
function trimall() {
    var el;

    for ( el=0; el<document.MainForm.elements.length; el++ ) {

        if ( ( document.MainForm.elements[el].type == "password" )
        ||   ( document.MainForm.elements[el].type == "text" )
        ||   ( document.MainForm.elements[el].type == "textarea" ) ) {
            document.MainForm.elements[el].value = trim( document.MainForm.elements[el].value );
        }
    }
}

/***************************************************************************
* trim()
*
* @param var trimMe
* @return var str
***************************************************************************/
function trim( trimMe )
{
    str = new String( trimMe );

    return str.replace( /^\s*|\s*$/g, "" );
}

/***************************************************************************
* isInt()
*
* @param var str
* @param boolean ignoreBlank The value may true, false or non-existant
* @return bool true/false
***************************************************************************/
function isInt() {

    str = arguments[0];

    /*
    ** If a second argument is not passed in, default it to false. (Treat
    ** blank as "not an integer".
    */
    if ( !(ignoreBlank = arguments[1]) ) {
        ignoreBlank = false;
    }

    if ( ignoreBlank
    &&   str == "" ) {
        /*
        ** String is blank/empty string and should be treated as an integer.
        */
        return true;
    }

    var i = parseInt (str);

    if (isNaN (i))
        return false;

    i = i . toString ();

    if (i != str)
        return false;

    return true;
}

/***************************************************************************
* GetFilename()
*
* @param string PathFile
* @return string strFilename
***************************************************************************/
function GetFilename( strPathFile ) {
    var strFilename = '';
    var slash = '/';

    if (strPathFile.match(/\\/)) {
         slash = '\\';
    }

    strFilename = strPathFile.substring( strPathFile.lastIndexOf( slash ) + 1 )

    return strFilename;
}

/***************************************************************************
* GetFileExtension()
*
* @param object ctrl
* @return var varExt
*
* It does not matter how long the file extension is.
***************************************************************************/
function GetFileExtension( ctrl )
{
    // Get the extension without the dot.
    var strFilename = new String( ctrl.value );
    var varExt      = strFilename.substr( (strFilename.lastIndexOf( "." )+1) ).toLowerCase();

    return varExt;
}

/***************************************************************************
* IsValidEMail()
*
* @param object ctrl
* @return boolean True if the e-mail is valid, otherwise false
*
* Note: Got new / better validation code from http://www.smartwebby.com/DHTML/email_validation.asp
***************************************************************************/
function IsValidEMail( ctrl ) {

    /*
    ** old code ...
    **
    var strEMail = new String( ctrl.value );

    var expEMail = new RegExp( "^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+", "i" );

    var RetVal = expEMail.test( strEMail );

    return( RetVal );
    **
    */

    var at   = "@";
    var dot  = ".";
    var str  = String( ctrl.value );
    var lat  = str.indexOf( at );
    var lstr = str.length;
    var ldot = str.indexOf( dot );

    if ( str.indexOf( at ) == -1 ) {
       return false;
    }

    if ( str.indexOf( at ) == -1 || str.indexOf( at ) == 0 || str.indexOf( at ) == lstr ) {
       return false;
    }

    if ( str.indexOf( dot ) == -1 || str.indexOf( dot ) == 0 || str.indexOf( dot ) == lstr ) {
       return false;
    }

     if ( str.indexOf( at,(lat+1) ) != -1 ) {
       return false;
     }

     if ( str.substring( lat-1, lat ) == dot || str.substring( lat+1, lat+2 ) == dot ) {
       return false;
     }

     if ( str.indexOf( dot,(lat+2) ) == -1 ) {
       return false;
     }

     if ( str.indexOf(" ") != -1 ) {
       return false;
     }

     return true;
}

/***************************************************************************
* GetStateList()
*
***************************************************************************/
function GetStateList() {

    var ctlCountry = document.MainForm.elements['ctry_code'];
    ctry_code = ctlCountry.options[ctlCountry.selectedIndex].value;
    var arrState = arrCountryState[ctry_code];
    var ctlState = document.MainForm.elements['sel_state_code'];
    state_code = document.MainForm.elements['state_code'].value;

    ctlState.options.length = 0;
    var i = 0;

    for ( recState in arrState ) {

        ctlState.options[i] = new Option( arrState[recState], recState );

        if ( recState == state_code ) {
            ctlState.options[i].selected = true;
        }

        i++;
    }
}

/***************************************************************************
* SetStateCode()
*
***************************************************************************/
function SetStateCode() {

    document.MainForm.elements['state_code'].value = document.MainForm.elements['sel_state_code'].value;
}

/***************************************************************************
* setCheckedValue()
*
* @param object radioObj Radio button control
* @param object newValue Input text control
***************************************************************************/
function setCheckedValue( radioObj, newValue ) {

    if ( !radioObj )
        return;

    var radioLength = radioObj.length;

    if ( radioLength == undefined ) {

        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }

    for ( var i=0; i<radioLength; i++ ) {

        radioObj[i].checked = false;

        if ( radioObj[i].value == newValue.toString() ) {

            radioObj[i].checked = true;
        }
    }
}

/***************************************************************************
* range_check()
*
* @param object ctrl Input text control
* @param var minv Minimum value in range
* @param var maxv maximum value in range
* @return boolean True if value is within range, otherwise false
***************************************************************************/
function range_check( ctrl, minv, maxv ) {

    is_int = isInt( ctrl.value, ignoreBlank=true );

    if ( !is_int
    || ( is_int && ctrl.value != "" && ( ctrl.value < minv || ctrl.value > maxv ) ) ) {

            alert( "Field must be an integer between " + minv + " and " + maxv + "." );
            ctrl.focus();
            return false;
    }

    return true;
}

/***************************************************************************
* yes_no_check()
*
* @param object ctrlYesNo
* @param object ctrlNum
*
* If control A must be set to yes for control B to have a value, this
* function will set control B's value to blank.
***************************************************************************/
function yes_no_check( ctrlYesNo, ctrlNum ) {

    if ( ( get_radio_val( ctrlYesNo ) != "y" )
    &&   ( get_radio_val( ctrlNum ) != "" ) ) {

        i = get_checked_index( ctrlNum );

        ctrlNum[i].checked = "";
    }
}

/***************************************************************************
* get_radio_val()
*
* @param object ctrl Radio button control
* @return var value of radio control
***************************************************************************/
function get_radio_val( ctrl ) {

    i = get_checked_index( ctrl );

    if ( i >= 0 ) {
        return ctrl[i].value;
    }

    return "";
}

/***************************************************************************
* get_checked_index()
*
* @param object ctrl Checkbox control
* @return var index of checked box in group
***************************************************************************/
function get_checked_index( ctrl ) {

    for ( i=0; i<ctrl.length; i++ ) {

        if ( ctrl[i].checked ) {

            return i;
        }
    }

    return -1;
}

/***************************************************************************
* valid_date()
*
* @param var intYear
* @param var intMonth
* @param var intDay
* @return boolean True if values are a valid date, otherwise false
***************************************************************************/
function valid_date( varYear, varMonth, varDay ) {

    var intYear  = parseInt( varYear );
    var intMonth = parseInt( varMonth );
    var intDay   = parseInt( varDay );

    switch ( intMonth ) {

        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:

            if ( intDay > 31 ) {
                return false;
            }
            break;

        case 4:
        case 6:
        case 9:
        case 11:

            if ( intDay > 30 ) {
                return false;
            }
            break;

        case 2:

            if ( intYear % 4 != 0 ) {
                leap_year = false;
            } else if ( intYear % 400 == 0 ) {
                leap_year = true;
            } else if ( intYear % 100 == 0 ) {
                leap_year = false;
            } else {
                leap_year = true;
            }

            if ( ( !leap_year && ( intDay > 28 ) )
            ||   ( leap_year && ( intDay > 29 ) ) ) {
                return false;
            }
            break;
    }

    return true;
}

/***************************************************************************
* get_page_name()
*
* @param var varURL
* @return var PageName
*
* Note: See menu.js
***************************************************************************/
function get_page_name( varURL ) {

    var arrURL = varURL.split( '/' );

    return ( arrURL.length < 2 ) ? varURL : arrURL[arrURL.length-2].toLowerCase() + arrURL[arrURL.length-1].toLowerCase();
}

/***************************************************************************
* set_active_menu()
*
* @param array arrMenu
* @param var PageName
*
* Note: See menu.js
***************************************************************************/
function set_active_menu( arrMenu, PageName ) {

    for ( var idx=0; idx < arrMenu.length; idx++ ) {

        if ( get_page_name( arrMenu[idx].href ) == PageName ) {

            if ( arrMenu[idx].parentNode.tagName != "DIV" ) {

                arrMenu[idx].className = "current";
                arrMenu[idx].parentNode.className = "current";
                break;
            }
        }
    }
}

/***************************************************************************
* textToPassword()
*
* @return boolean True if valid, otherwise false
*
* Note: Change input type="text" to type="password"
***************************************************************************/
function textToPassword( elem ) {

    var eData={v:elem.value, t:elem.type, s:elem.size, n:elem.name},
        newElem, newType=(eData.t=='password'?'text':'password');

    try {

        newElem=document.createElement("<input type='"+newType+"' name='"+eData.n+"' value='"+eData.v+"' size='"+eData.s+"'>");

    } catch(e) {

        newElem=document.createElement('input');
        newElem.name=eData.n;
        newElem.name=eData.n;
        newElem.type=newType;
        newElem.size=eData.s;
        newElem.value=eData.v;
    }

    elem.parentNode.replaceChild(newElem, elem);

    newElem.focus();

    return newElem.type;
}

/***************************************************************************
* limitText()
*
* @param ctrl limitField
* @param ctrl limitCount
* @param int limitNum
*
* http://www.mediacollege.com/internet/javascript/form/limit-characters.html
***************************************************************************/
//function limitText(limitField, limitCount, limitNum) {
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
/*
    } else {
        limitCount.value = limitNum - limitField.value.length;
*/
    }
}