////////////////////////////////////////////////
// form.js
//
// created by Dave Fudge  3/13/07
//
// this file contains functions that will be useful
// when using AJAX type form submission and validation.
// it will detect and all all form input fields to a
// global javascript object.
//
// THE FORM SUBMISSION HERE DEPENDS ON DOJO!! make sure you include it
// prior to using this
//
////////////////////////////////////////////////

// the form parent object
var _f = {};
// the form parent object...
// NOTE
// at the moment, we're not actually using this because we haven't
// figured it out entirely yet.
var container;
// the form response object holder...
var _response       = {};
// the data directory
var data_dir        = "data";
// the form load return func
var return_function = {};
// required fields... this is for error checking
var required        = {};


// generate a random ID for our form
// this will eliminate overwriting results from the server
// in the event that we have two or more form submissions
// happening simultaneously.
function generate_id() { return "fid"+Math.floor(Math.random() * 10000001); }

// get all the form elements on a page
dojo.addOnLoad(get_form_elements);
function get_form_elements()
{
    // setup our form field vars
    var input_el  = document.getElementsByTagName("input");
    var select_el = document.getElementsByTagName("select");
    var ta_el     = document.getElementsByTagName("textarea");

    var elements  = new Array;
    var i, j;

    // allow the user to select which field types they want
    // by passing in args
    var args  = get_form_elements.arguments;
    var types = new Array;
    for( i=0; i<args.length; i++ ) { types.push(args[i]); }

    if( types.length > 0 )
    {
        // make a type array and loop thru it
        var selected_fields = types.split(",");
        for( i=0; i<selected_fields.length; i++ )
        {
            // we already have each type, so now we're just seeing which
            // types the user wants to have accessible
            switch( selected_fields[i] )
            {
                case "input":    elements.push(input_el);  break;
                case "select":   elements.push(select_el); break;
                case "textarea": elements.push(ta_el);     break;
            }
        }
    } // otherwise, add all elements
    else { elements.push(input_el); elements.push(select_el); elements.push(ta_el); }


// put the elements into our parent form object
for( i=0; i<elements.length; i++ ) { for( j=0; j<elements[i].length; j++ ) { _f[elements[i][j].id] = elements[i][j]; } }
}

// this function will submit the form object derived from the elements
// designated inside our "container"
function __submit()
{
    var args        = __submit.arguments;
    // we'll be passed in at least the page we're submitting to
    var pg          = args[0];
    var return_func = args[1];
    var form_id     = args[2];
    var formvars    = "";

    // get the form elements
    get_form_elements();
    // set the return function for this submission
    set_return_function(return_func,form_id);
    // first thing we have to do is some error checking...
    validate(pg,form_id);
}
function __submit_validated()
{
    var args     = __submit_validated.arguments;
    var response = args[0];
    var pg       = args[1];
    var form_id  = args[2];
    var formvars = "";

    // reset the required fields for the next case...
    reset_required_fields(form_id);

    // make sure we're supposed to continue
    if( !response ) { return false; }

    // loop thru our _f form object and set up the name/value pairs
    for( var el in _f )
    {
        // if the element doesn't exist... skip it
        if( !_f[el] ) { continue; }

        // check the type and the value
        // radio buttons and check boxes have to be "checked" in order to
        // make it thru
        if( _f[el].type )
        {
            if( (_f[el].type.toLowerCase() == "checkbox")
             || (_f[el].type.toLowerCase() == "radio")  ) { if( !_f[el].checked ) { continue; } }
        }

        // get the value and add it to our vars
        formvars += "&"+el+"="+escape(_f[el].value);
    }

    // now submit the form
    dojo.io.bind({
        url:         data_dir+"/"+pg,
        postContent: formvars,
        load:        function( type, data ) { __return(type,data,form_id); },
        mimetype:    "text/plain"
    });
}
// validate the "required" fields
// for validation, we'll send it to the server because
// we have much more sophisticated validation routines
// there.
// we're expecting to get the page we're submitting to
// passed in as an argument, we need to pass that thru to
// the submit_validated func
function validate()
{
    var args     = validate.arguments;
    var pg       = args[0];
    var form_id  = args[1];
    var formvars = "";

    // do we even HAVE required fields?
    if( !required[form_id] ) { __submit_validated(true,pg,form_id); }
    else
    {
        // we have a required array of objects with name/id pairs
        for( var i=0; i<required[form_id].length; i++ )
        {
            // the object in our array
            var o     = required[form_id][i];
            formvars += "&"+o.name+"|"+o.id+"="+_f[o.id].value;
        }

        // send it to the server for validation
        dojo.io.bind({
            url:         data_dir+"/validate.php",
            postContent: formvars,
            load:        function( type, data )
                         {
//alert(data);
                            var r        = eval("("+data+")");
                            var response = false;
                            if( r.errorcode != 0 )
                            {
//alert(r.error_message);
                                display_message(unescape(r.error_message));
                                dojo.byId(r.field.toLowerCase()+"_label").className = "error";
                                response = false;
                            }
                            else { response = true; }

                            __submit_validated(response,pg,form_id);
                         },
            mimetype:    "text/plain"
        });
    }
}
// this function deals with the return value
function __return()
{
    var args    = __return.arguments;
    var type    = args[0];
    var data    = args[1];
    var form_id = args[2];
//alert(data);
//alert(form_id);
    _response[form_id] = {};
    _response[form_id] = eval("("+data+")");
//alert(_response[form_id]);
    return_function[form_id]();
}
// this function will "reset" the form...
function __reset()
{
    // loop thru the _f form object and set all values to ""
    for( var i in _f ) { if( _f[i].type ) { if( _f[i].type.toLowerCase() == "button" ) { continue; } } _f[i].value = ""; }
}


// set the data directory where our submission files reside
function set_data_dir()
{
    var args = set_data_dir.arguments;
    data_dir = (args[0]) ? args[0] : "";
}
// set the form container object.  by default, this is set to "document"
function set_form_container()
{
    var args  = set_form_container.arguments;
    container = (args[0]) ? dojo.byId(args[0]) : document;
}
// set the "required" information fields
// fields must be passed in as "name=field_id"
function set_required_fields()
{
    var args    = set_required_fields.arguments;
    // the arguments for fields is args[0]!
    var form_id = args[args.length - 1];

    // our required fields will be sent in as arguments
    // by ID
    required[form_id] = new Array();
    for( var i=0; i<(args.length - 1); i++ )
    {
        var arr = args[i].split("=");
        var o   = {name:arr[0],id:arr[1]};
        required[form_id].push(o);
    }
}
function reset_required_fields()
{
    var args    = reset_required_fields.arguments;
    var form_id = args[0];

    required[form_id] = new Array();
}

// NOTE:
// when passing our argument into this function, you have to make
// sure that the passed in function is NOT evaluated.  this is the proper syntax:
// set_return_function( function() { my_func_name(); } );
//
// set the return function for our form when we load
function set_return_function()
{
    var args    = set_return_function.arguments;
    var func    = args[0];
    var form_id = args[1];

    // set the return function in our object
    return_function[form_id] = func;
}


// simple display stuff for any "fields"
function reset_field()
{
    var args = reset_field.arguments;
    var fld  = (args[0]) ? args[0] : false; // the field object
    var dv   = (args[1]) ? args[1] : "";    // default value

    // make sure we have an object
    if( !fld ) { return; }

    fld.value = (fld.value != "") ? fld.value : dv;
}
function clear_field()
{
    var args = clear_field.arguments;
    var fld  = (args[0]) ? args[0] : false; // the field object
    var dv   = (args[1]) ? args[1] : "";    // default value

    if( fld.value == dv ) { fld.value = ""; }
}