/*
    Form Logic Controller.
    (C) 2005 James Davies (formlogic@foomatic.net)
    
    Shows/Hides fields based on condition of other fields, using a simple ruleset.
    
    exmample:
    
    <form id='myForm'>
        <input type="checkbox" name="hasEmail" /> <label for='hasEmail'>Has Email?</label>
        <imput name="email" id="field-email"/>
    
        <input type="checkbox" name="hasPhone" /> <label for='hasPhone'>Has Phone #?</label>
        <imput name="phone" id="field-phone"/>
                    
    </form>
    
    <script>
            var rules = {
                'field-email': ["isChecked( hasEmail )"], 
                'field-phone': ["isChecked( hasPhone )"]
            }
                 
            var myForm = document.getElementById('myForm');
            var formLogic = new FormLogic( myForm, rules );
    </script>
    
    
    Will cause the fields 'email' and 'phone' to show only if the corrosponding 
    checkboxes are checked. 
    
*/


isIE = document.all ? true : false;

function isChecked( object )
{
    return object.checked ? true : false; 
}

function isChosen( object )
{
    
    return value(object) ? true : false;
}

function get(id)
{
    return document.getElementById( id );
}

function value( object )
{
    var length;
    try 
    {
        length = object.length;
    } 
    catch( e )
    {
        length = null;
    }
         
    if( length )
         for( x=0; x< length; x++ )
         {
             if( object[x].selected || object[x].checked )
                 return object[x].value;
         }
    
    return object.value; 
}

function isIn( value, list )
{
    for( key=0; key<list.length; key++)
        if(list[key] == value)
             return true;
        
    
    return false;
}

function valueIsIn( object, list )
{
    return isIn( value( object ), list )
}


function FormLogic(form, rules)
{
    //var form = document.getElementById(form_id);        
    
    this.update = function()
    {
        for(element in rules)
        {
            conditions = rules[element];
            var object = document.getElementById(element);
            if(!object) 
                continue;
            for( i=0;i<conditions.length; i++ )
            {     
                    var condition = conditions[i];
                    with(form){
                        result = eval(condition); 
                        object.style.display = result ? "" : 'none'; 
                    }
                        
            }
            
        }
        
        if( cb_afterUpdate ) cb_afterUpdate( form );
        
        
    }
    
    
    
    
    for(i=0;i<form.elements.length;i++){
        var o = form.elements[i];        
        if(isIE){
            if( !o.onpropertychange )
                o.onpropertychange = this.update;
        }else{
            if( !o.onchange )
                o.onchange = this.update;
        }
    }
            
    this.update();
}
