/*
 *  Copyright 2010 Genius.com, Inc
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); 
 *  you may not use this file except in compliance with the License. 
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software 
 *  distributed under the License is distributed on an "AS IS" BASIS, 
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 *  See the License for the specific language governing permissions and 
 *  limitations under the License. 
 */

// Set up namespace.
if (typeof(GeniusScript) != 'undefined')
{
    GeniusScript.transformer = {};

    /**
     * will update the hidden field for a checkbox
     * @param {Object/EventObject} the browser event object
     * @private
     */
    GeniusScript.transformer.updateCheckboxHiddenField = function(eventObj)
    {
        var checkbox = eventObj.target;
        
        var hiddenInputField = document.getElementById(checkbox.id + "_fake");
        hiddenInputField.value = GeniusScript.core.getCheckboxValueAsString(checkbox);
    }
    
    /**
     * will transform all known checkboxes to hidden input fields
     */
    GeniusScript.transformer.transformCheckboxes = function()
    {
        var booleanFields = GeniusScript.Configuration.booleanFields;
        var booleanFieldsLength = booleanFields.length;
        var formEl = GeniusScript.main.getFormEl();
        
        /*
         * loop through each item, and transform the checkboxes to
         * hidden input fields
         */
        for (var i = 0; i < booleanFieldsLength; i++)
        {
            var tempEl = document.createElement('input');
            tempEl.type = 'hidden';
            var origEl = document.getElementById(booleanFields[i]);
            var fieldName = origEl.name;
            origEl.name = fieldName + "_ignore";
            tempEl.name = fieldName;
            tempEl.id = booleanFields[i] + "_fake";
            formEl.appendChild(tempEl);
            //set value, if previously set
            tempEl.value = GeniusScript.core.getCheckboxValueAsString(origEl);
            GeniusScript.$(origEl).bind('change', GeniusScript.transformer.updateCheckboxHiddenField);
            GeniusScript.$(origEl).bind('click', GeniusScript.transformer.updateCheckboxHiddenField);
        }
    }
}
