//
// check email syntax
//
function is_email_syntax_ok(email)
{
    email = email.toLowerCase();
    email = email.replace(/^\s+|\s+$/g,"");
    
    match = email.match(/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/);
    return (match != null);
}

//
// Toggle checkbox value.
//
function toggleCb(idName)
{
    var status = $('#'+idName).attr('checked');
    $('#'+idName).attr('checked', !status);
}

//
// Cookies.
//
// http://www.quirksmode.org/js/cookies.html
//
function _create_cookie(name,value,days,isSecure) 
{
    if (days) 
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else 
    {
        var expires = "";
    }
    
    (isSecure) ?
        document.cookie = name+"="+value+expires+"; secure" :
        document.cookie = name+"="+value+expires+"; path=/";
}

function create_cookie(name, value, days) 
{
    var isSecure = false;
    _create_cookie(name,value,days, isSecure) 
}

function create_secured_cookie(name,value,days) 
{
    var isSecure = true;
    _create_cookie(name,value,days, isSecure) 
}

function read_cookie(name) 
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) 
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) 
            return c.substring(nameEQ.length,c.length);
    }
    
    return null;
}

function erase_cookie(name) 
{
    create_cookie(name,"",-1);
}

function erase_secured_cookie(name) 
{
    create_secured_cookie(name,"",-1);
}

//
// Strip whitespace from the beginning 
// and end of a string
// 
function trim(str)
{
    return str.replace(/^\s+|\s+$/g,'');
}

// 
// Make sure that textBox contains 
// a numeric value.
// 
function force_numeric_value(textBox)
{
    var val;
    
    if (textBox.value == '-')
    {
        return;
    }

    while (textBox.value.length > 0 && isNaN(textBox.value))
    {
        textBox.value = textBox.value.substring(0, textBox.value.length - 1);
    }

    textBox.value = trim(textBox.value);
}

// 
// Realtime hour-field validation.
// 
// NOTE: also automatically appends a 
// dash between hour and minute.
// 
function validate_hour(textBox)
{
    var val = textBox.value;
    var length = val.length;
    
    //
    // case blank string - return.
    //
    if (val.length == 0)
    {
        return;
    }
    
    //    
    // Error - first digit is not 0-2.
    //
    if (!val.match(/^[0,1,2]/))
    {
        textBox.value = '';
        return;
    }                
    
    //    
    // Error - second character is not a digit.
    //
    if (!val.match(/^\d\d.*/))
    {
        textBox.value = val.substring(0,1);
        return;
    }                
    
    //    
    // Error - hours number is above 23.
    //
    if ((length >= 2) && (parseInt(val.substr(0,2)) > 23) )
    {
        textBox.value = val.substr(0,1);
        return;
    }                
    
    //    
    // Case dd: - return
    //
    if (val.match(/^\d\d:$/))
    {
        return;
    }                

    //    
    // Error - not ddd
    //
    if ((length == 3) && (!val.match(/\d\d\d/)))
    {
        textBox.value = val.substr(0,2);
        return;
    }                

    //    
    // Append ':'
    //
    if ((length == 3) && (val.substr(2,1) != ":") )
    {
        textBox.value = val.substr(0,2) + ':' + val.substr(2,1);
        
        val = textBox.value;
        length = val.length;
    }          
    
    //    
    // Error - minutes first digit is not in
    // the range 0-5.
    //
    if ((length > 3) &&(parseInt(val.substr(3,1)) > 5))
    {
        textBox.value = val.substr(0,2);
        return;
    }                

    //    
    // Error - not dd:dd
    //
    if ((length == 5) && (!val.match(/\d\d:\d\d/)))
    {
        textBox.value = val.substr(0,4);
        return;
    }                

    return;      
    
}

// 
// Realtime numeric value validation.
// 
function validate_number(textBox)
{
    var val = textBox.value;
    var length = val.length;
    
    if (!val.match(/^[\d\.]*$/))
    {
        textBox.value = val.substr(0,length-1);
    }                

    return;
}

//
// Is input string a JSON.
//
function isJson(inStr)
{
    var filtered = inStr;
    filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
    filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
    filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
    
    return (/^[\],:{}\s]*$/.test(filtered));
}

//
// Converts json string into a json object.
//
function evalJson(jsonStr)
{
    if (!isJson(jsonStr))
    {
        //alert("Not JSON: " + jsonStr);
        return false;
    }
    
    else
    {
        return eval("(" + jsonStr + ")");
    }
}

//
// Is input json string contains an error 
// messaage.
//
function is_json_error(jsonStr)
{
    var json = evalJson(jsonStr);

    return (json.error != undefined);
}

//
// Parses error message from input json sting.
//
function get_json_error(jsonStr)
{
    var json = eval("(" + jsonStr + ")");
    var errMsg = json.error;
    
    if (errMsg == undefined)
    {
        alert ('Input is not json at get_json_error()');
    }
    
    return errMsg;
}   

//
// Table hover.
//
function tblHover()
{
    $("table.regular tr:odd").addClass("odd");
    $("table.regular tr:even").addClass("even");
    
    $("table.regular tr").hover
    (
        function()
        {
             $(this).addClass("hover");
        },

        function()
        {
            $(this).removeClass("hover");
        }
    );
}

//
// Is input string combined of input
// character group only.
//
function _is_valid_chars(inStr, validChars)
{
    var isNumeric = true;
    var chr;

    for (i = 0; i < inStr.length && isNumeric == true; i++) 
    { 
        chr = inStr.charAt(i); 
        
        if (validChars.indexOf(chr) == -1) 
        {
            isNumeric = false;
        }
    }

    return isNumeric;
}


function is_numeric(inStr)
{
    var validChars = "0123456789.-";
    return _is_valid_chars(inStr, validChars);
}


//
// Clear field
//
// Clears the field contents, unless its
// current value is different from the original 
// default value.
//
function ClearField(fldId, orgVal)
{
    if (fldId.value == orgVal)
    {
        fldId.value = '';
    }
}

//
// Does the opposite of clear-field().
//
function ResetField(fldId, orgVal)
{
    var val = fldId.value;
    val = val.replace( /^\s+/g, "" );
    
    if (val == '')
    {
        fldId.value = orgVal;
    }
}

//
// Delay.
//
function delay(millSec)
{
    var date = new Date();
    var curDate = null;

    do 
    { 
        curDate = new Date(); 
    }
    
    while (curDate-date < millSec);
} 
