//
// Copyright 2004-2005 by Pixta, Inc.,
// 926A Diablo Ave., No. 542, Novato, CA 94947 U.S.A.
// All rights reserved.
//
// This software is the confidential and proprietary information
// of Pixta, Inc.
//
// util.js 
//
// General-purpose, useful Javascript routines
//
// Notes:
//

// Return the first index of 'val' in 'array', or -1 if it is not there
function arr_index(array, val)
{
    len = array.length;
    for (i = 0; i < len; i++)
    {
        if (array[i] == val)
            return i;
    }
    
    // nada
    return -1;
}    

// Return true if 'val' is in 'array', false otherwise
function arr_contains(array, val)
{
    index = arr_index(array, val);
        
    return (index >= 0) ? true : false;
}

// Select or deselect the given value in the given list of options
function setOption(options, val, state)
{
    len = options.length;
    for (i = 0; i < len; i++)
    {
        if (options[i].value == val)
        {
            options[i].selected = state;
            break;
        }
    }
}    

// escape() and unescape() are deprecated as of Javascript v1.5, but 
// encodeURI()/encodeURIComponent() and decodeURI()/decodeURIComponent()
// don't arrive on the scene until v1.5, either.
// In particular, IE < 5.5 does not support JS v1.5.
// Gotta love web development.
//
// _JSVersion is set in the <script> tag immediately before this 
// file is included.
//
function encodeString(str)
{
    if (_JSVersion < 1.5)
        return escape(str);
    else
        return encodeURIComponent(str);    
}

function decodeString(str)
{
    if (_JSVersion < 1.5)
        return unescape(str);
    else
        return decodeURIComponent(str);    
}

// Format a floating point number with the requested number of decimal places
function format_number(num, num_places)
{
    var dec_part, frac_part;

    // Don't mess with non-numeric input
    // Beware of silent conversions from null/'' => 0, hence the '===' operator!
    if (num === null || num === '' || isNaN(num))
        return num;
    
    // Make sure this is reasonable
    if (!num_places || isNaN(num_places))
        num_places = 0;

    // See if the JS v1.5 function is available
    if (num.toFixed)
        return num.toFixed(num_places);

    // No, do it the hard way
    dec_part = Math.floor(num);
    
    if (num_places == 0)
        return dec_part;
    
    // Get fractional part, convert to int of right size, jam two parts together
    frac_part = num - dec_part;
    frac_part = Math.round(frac_part * Math.pow(10, num_places));

    // Special case for the right number of trailing zeroes
    if (frac_part == 0)
    {
        frac_part = '';
        for (var i = 0; i < num_places; i++)
            frac_part += '0';
    }
    
    num = dec_part + '.' + frac_part;
    
    return num;
}    


