/* 
 * Copyright 2015, Air Hawkes Bay Ltd
 */

/**
 * Created 4/06/2015 at 1:52:49 PM
 * 
 * Description of tablewithactions
 * Javascript for the tablewithactions widget.
 * 
 * @author Stefan Taber <staber@airhb.co.nz>
 * @copyright 2015 Air Hawkes Bay Ltd
 * @version 0.0.1
**/
        
$(function() 
{
    
    // Add function to ebs namespace to deal with turning tables into objects.
    window.ebs.tablewithactions_objectify = function(jquery_table_object) {
        
        var return_object = {};
        
        return_object.name = jquery_table_object.data('name');
        
        jquery_table_object.find('tr').filter('[data-id]').each(function() 
        {
            var id = $(this).data('id');
            return_object[id] = {};
            $(this).find('input, select, textarea').each(function() 
            {
                return_object[id][$(this).attr('name')] = $(this).val();
            });
            $(this).find('input:checkbox').each(function()
            {
                return_object[id][$(this).attr('name')] = $(this).prop('checked');
                console.log(return_object[id][$(this).attr('name')]);
            });
        });
        return return_object;
    };
    
    
    // Add an object to the ebs namespace, that will contain all original rows that
    // have been marked as _edited.  This allows for reverting to original.
    window.ebs.tablewithactions_updaterows = {};
    
    
    // Deal with the default action buttons being pressed. 
    $('[data-widget="tablewithactions"] button').on('click', function() 
    {
        
        var row = $(this).parents('tr').first();
        var template = $(this).parents('table').first().find('[data-template]');
        var id = $(row).attr('data-id');
        
        // Insert a copy after the current row and mark it with info.
        // id is _new + a random number.
        if($(this).data('context') === 'duplicate')
        {
            var new_row = $($(row).clone(true)).insertBefore(row);
            
            $(new_row).attr('class', '');
            $(new_row).addClass('info');
            $(new_row).attr('data-id', String(Math.random()).replace(".", "") + '_new');
            $(new_row).find('input, select').each(function() 
            {
                $(this).removeAttr('disabled');
            });
        }
        
        // Mark with the "danger" class that this row is to be removed.
        if($(this).data('context') === 'remove')
        {
            if($(row).hasClass('danger'))
            {
                $(row).removeClass('danger');
                $(row).attr('data-id', id.replace('_delete', ''));
            }
            else
            {   
                $(row).filter('.info, .success').each(function() 
                {
                    $(this).remove();
                });
                $(row).filter(':not(.info, .success)').each(function() 
                {
                    $(this).addClass('danger');
                    $(this).attr('data-id', id += '_delete');
                });
            }
        }
        
        // Insert a copy of the current row, mark it with success, and go through
        // and remove all the data, and provide inputs for new data.
        // id is _new + a random number.
        if($(this).data('context') === 'add')
        {
            var new_row = $($(template).clone(true)).insertBefore(row);
            $(new_row).removeAttr('data-template');
            $(new_row).attr('class', '');
            $(new_row).addClass('success');
            $(new_row).show();
            $(new_row).attr('data-id', String(Math.random()).replace(".", "") + '_new');
            $(new_row).find('input, select').each(function() 
            {
                $(this).removeAttr('disabled');
                $(this).val('');
            });
        }
        
        // Switch the displayed data to input fields.
        if($(this).data('context') === 'edit')
        {
            // Only turn white (actual existing objects) yellow.
            $(row).filter(':not(.info, .success)').attr('class', '');
            $(row).filter(':not(.info, .success)').addClass('warning');
            
            // Get the current id of the row.
            var id = $(row).attr('data-id');
            
            // If the row is NEITHER a new row or marked as edited already, edit the row,
            // and store an original version in the editedrows object.
            if(id.indexOf('_update') + id.indexOf('_new') === -2)
            {
                id = id.replace('_delete', '');
                $(row).attr('data-id', id.replace('_delete', ''));
                window.ebs.tablewithactions_updaterows[id] = $(row).clone(true);
                
                $(row).attr('data-id', id += '_update');
                $(row).find('input, select').each(function() 
                {
                    $(this).removeAttr('disabled');
                });
            }
            
            // Or restore from the backups if it's marked as edited...
            else if(id.indexOf('_update') !== -1)
            {
                id = id.replace('_update', '');
                id = id.replace('_delete', '');
                
                var new_row = $(window.ebs.tablewithactions_updaterows[id]).replaceAll(row);
                $(new_row).attr('class', '');
            }
            
        }
    });
});