/*******************************************************************************
* Miscellaneous.js
*
* @package mopus
* @author Preston McMurry (prestonm3@mcmurry.com)
* @version 4.0 , 2012-12-14
* @copyright (C) Copyright 2012 by McMurry
*
*******************************************************************************/

/***************************************************************************
* ValidateWrapper()
*
* @param object form
* @param varchar strButton
* @param boolean confirm_delete
* @return boolean True if valid, otherwise false
***************************************************************************/
function ValidateWrapper( varForm, strButton, confirm_delete ) {

    var strURL = "";

    if ( strButton == "Save" ) {

        if ( validate( varForm ) == true ) {
            varForm.elements['Submit'].value = "Submit";
        } else {
            return false;
        }

    } else if ( strButton == "Delete" ) {

        if ( confirm_delete === undefined ) {
            confirm_delete = false;
        }

        var do_delete = true;

        if ( confirm_delete ) {
            do_delete = confirm_delete_popup();
        }

        if ( do_delete ) {
            varForm.elements['Action'].value = "Delete";
            varForm.elements['Submit'].value = "Submit";
            varForm.submit();
        } else {
            return false;
        }
    }
}

/***************************************************************************
* confirm_delete_popup()
*
* @param varchar strMsg
***************************************************************************/
function confirm_delete_popup( strMsg ) {

    if ( strMsg ) {
        strMsg += "\n\r";
    } else {
        strMsg = "";
    }

    strMsg += "Click 'OK' to delete.";

    return( confirm( strMsg ) );
}

/***************************************************************************
* reset()
*
***************************************************************************/
function reset() {
    /*
    ** Click the hidden input where type="reset".
    */
    document.getElementById('Reset').click();
}

/***************************************************************************
* TestURL()
*
* @param object ctrl
***************************************************************************/
function TestURL( elID ) {

    var URL;

    URL = trim( document.getElementById( elID ).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
*
* @param object form
***************************************************************************/
function trimall( varForm ) {
    var el;

    for ( el=0; el<varForm.elements.length; el++ ) {

        if ( ( varForm.elements[el].type == "password" )
        ||   ( varForm.elements[el].type == "text" )
        ||   ( varForm.elements[el].type == "textarea" ) ) {
            varForm.elements[el].value = trim( varForm.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 ) {

    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;
}

/***************************************************************************
* 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;
}

/***************************************************************************
* limitText()
*
* @param ctrl limitField
* @param ctrl limitCount
* @param int limitNum
*
* http://www.mediacollege.com/internet/javascript/form/limit-characters.html
***************************************************************************/
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}


