
	/*
	(c) wolftools 2009
	last updated: 04 may 2009
	ascii wolf: sunnyspot.org
                                                                oo"$o
                                                              oo"   $
                                                          oo$$     $"
                                                        o$" "      $$oo
                                                        "           "$$
                                                     ooo$"$o        o$
                                                  o$""             o$
                                                 o"      oo        $
                                                $$ooooo$""         $o
                                                ""$"              $$$
                                                 $                "$
                                              oo""                $$o
                                           o$""                  o$$$
                                    ooooo$""                     $$
                            ooo$"""""                           o$$
                       oo$"""                                   o$
                     o$"                                        o
                   o"                                          o$
                 o$"                                           $
               o$"          o                                 o$
             oo$"           $                      o          $
            $$              $o             $       $         $
           $"               $            o$       $"        $
          $                 $  o         $"      $"         $
         $       oo        $"  """$ooooo o$     $"  ooo     $
        $       o$"$o     $$ o     o      $    o$  "" $      $
       $"      $$" o$    o$ $o   o$      o$    $       $     $
      $"      $$"  o"   $" o$  o$"        $    $        $    "o
     $"     o$$   o$  o$" o$" o$          $"   $         "o   $o
    $"     o$"  $""  o$  o$   $$          "$  "$          "$   $
    $    o$"    $   $"    "$   $o          $   $            "o  $
    $oo""       $o "$      "$o  $oo        "$  $o            $o  $o
     "          $o $"        $o   $$$      "$  $              "o  ""oo
                "o "$         "$"$$$"       $o  $o             $o    $$o
                "$  "$                      $o   "o             "$o$$$$"
                 $   "$$                    "o   o$$
                 $$o$$$$"                    ""$""""
	
	This package is part of a grid package I wrote which will create an editable datagrid from an ordinary table.
	Make sure that the table being referenced contains no 'TH' elements, as the function will interpret the top
	and side headings for you through the last two function parameters of the main function.
	
	The input boxes will be created with names created from the original table cell's IDs. If no ID is present,
	a default name will be created and assigned based on its position in the grid.
	
	Three style classes will be added to the editable grid for you:
		'wolftools_divGridContainer',
		'wolftools_tableGridData' and
		'wolftools_tableGridHeadings'
	
	Setting an explicit width and / or height for the 'wolftools_divGridContainer' class will result in automatic overflow
	of the contained editable grid. It's also recommended that in order to secure a fixed column width, you should set the
	width of the input boxes, NOT the table cells, explicitly in your style sheet.
	
	*/
	
	/*
	* Create editable grid function.
	*
	* This is the main function, the one which will create an editable grid from an 'average' HTML table.
	*
	* @param String The ID of the table we're trying to turn into an editable grid
	* @param boolean Flag indicating whether or not the table's first row should be treated as column headings [optional; default - true]
	* @param boolean Flag indicating whether or not the table's first column should be treated as row headings [optional; default - false]
	* @param boolean Flag indicating whether or not the grid should be editable [optional; default - true]
	* @param boolean Flag indicating whether or not to create checkboxes for a user to select rows from the result set [optional; default - false]
	*/
	var wolftools_timeout_id = 0;
	function wolftools_createEditableGrid(table_id, contains_top_headings, contains_side_headings, editable, selectable)
	{
		// check to see if we have a table to work with...
		if ($(table_id))
		{
			var table = $(table_id);
			
			// variable validation...
			if (contains_top_headings !== true && contains_top_headings !== false)
				contains_top_headings = true;
			if (contains_side_headings !== true && contains_side_headings !== false)
				contains_side_headings = false;
			if (editable !== true && editable !== false)
				editable = true;
			if (selectable !== true && selectable !== false)
				selectable = false;
			
			// check to see if the container already exists, else create it...
			// most cases it will be added, as a unique container is required for each grid...
			if (!$('divGridContainer_'+ table_id))
				table.ancestors()[0].insert({top: "<div class='wolftools_divGridContainer' id='wolftools_divGridContainer_"+ table_id +"'></div>"});
			
			var div_container = $('wolftools_divGridContainer_'+ table_id);
			div_container.setStyle(
			{
				'overflow':'auto',
				'position':'relative'
			});
			
			// time to format the table in order to add it to the div container...
			// some variables...
			var row_counter = 0;
			var col_counter = 0;
			var side_heading_html = "";
			
			// placeholder for side headings...
			if (contains_side_headings)
			{
				side_heading_html += "<table cellspacing='0' cellpadding='0' class='wolftools_tableGridHeadings wolftools_tableGridData'";
				side_heading_html += " id='wolftools_tableGridHeadingsSide_"+ table_id +"'>";
			}
			
			// time to loop through the rows...
			var tr_children = table.getElementsBySelector('tr');
			for (var tr_index=0; tr_index<tr_children.length; tr_index++)
			{
				// get the row's cells...
				var tr_item = tr_children[tr_index];
				var td_children = tr_item.descendants();
				
				// some variables...
				var is_top_heading = (contains_top_headings && tr_index == 0);
				
				// grab the top row as a floating heading row, if necessary of course...
				if (is_top_heading)
				{
					var heading_html = "";
					heading_html += "<table cellspacing='0' cellpadding='0' class='wolftools_tableGridHeadings wolftools_tableGridData'";
					heading_html += " id='wolftools_tableGridHeadingsTop_"+ table_id +"'>";
					heading_html += "<tr>";
					for (var td_index=0; td_index<td_children.length; td_index++)
					{
						var td_item = td_children[td_index];
						if (selectable)
						{
							if ((contains_side_headings && td_index == 1) || (!contains_side_headings && td_index == 0))
								heading_html += "<td><input type='checkbox' style='width:auto; margin:0px 15px 0px 15px' /></td>";
						}
						var current_value = td_item.innerHTML;
						heading_html += "<td><input type='text' value='"+ current_value +"' readonly /></td>";
					}
					heading_html += "</tr>";
					heading_html += "</table>";
					div_container.insert(heading_html);
					$('wolftools_tableGridHeadingsTop_'+ table_id).setStyle(
					{
						'position':'absolute',
						'top':'0px',
						'left':'0px'
					});
				}
				
				col_counter = 0;
				for (var td_index=0; td_index<td_children.length; td_index++)
				{
					var td_item = td_children[td_index];
					var current_value = td_item.innerHTML;
					var is_side_heading = (contains_side_headings && td_index == 0);
					
					// update the side heading placeholder if necessary...
					if (is_side_heading)
					{
						side_heading_html += "<tr>";
						side_heading_html += "<td><input type='text' value='"+ current_value +"' readonly /></td>";
						side_heading_html += "</tr>";
					}
					
					if (selectable)
					{
						if ((contains_side_headings && td_index == 1) || (!contains_side_headings && td_index == 0))
							td_item.ancestors()[0].insert({top: "<td><input type='checkbox' style='width:auto; margin:0px 15px 0px 15px' /></td>"});
					}
					
					var input_name = td_item.id;
					if (input_name == "")
						input_name = "r"+ row_counter +"c"+ col_counter;
					td_item.innerHTML = "<input type='text' name='"+ input_name +"' value='"+ current_value +"'"+
							(is_top_heading || is_side_heading || !editable ? " readonly" : "")+" />";
					col_counter++;
				}
				row_counter++;
			}
			
			// finish off the side heading placeholder...
			if (contains_side_headings)
			{
				side_heading_html += "</table>";
				div_container.insert(side_heading_html);
				$('wolftools_tableGridHeadingsSide_'+ table_id).css(
				{
					'position':'absolute',
					'top':'0px',
					'left':'0px'
				});
			}
			
			// done formatting, add it to the container...
			div_container.insert("<table cellspacing='0' cellpadding='0' class='wolftools_tableGridData "+
				table.className +"'>" + table.innerHTML + "</table>");
			// remove the old table...
			table.remove();
			
			// create the animation interval if we're dealing with headings...
			if (contains_top_headings || contains_side_headings)
				wolftools_reposition_headings(contains_top_headings, contains_side_headings, table_id, div_container);
		}
	}
	
	function wolftools_reposition_headings(contains_top_headings, contains_side_headings, table_id, div_container)
	{
		wolftools_timeout_id = setTimeout(function()
		{
			if (contains_top_headings)
				$('wolftools_tableGridHeadingsTop_'+ table_id).setStyle({'top' : div_container.scrollTop+'px'});
			if (contains_side_headings)
				$('wolftools_tableGridHeadingsSide_'+ table_id).setStyle({'left' : div_container.scrollLeft+'px'});
			if ($('wolftools_tableGridHeadingsTop_'+ table_id) || $('wolftools_tableGridHeadingsSide_'+ table_id))
				wolftools_reposition_headings(contains_top_headings, contains_side_headings, table_id, div_container);
		}, 200);
	}
	
	function wolftools_clearTimeout()
	{
		clearTimeout(wolftools_timeout_id);
	}
	
	/*
	* Get grid data function.
	*
	* This function will return the contents of a particular datagrid for processing. It will
	* return the results in a well-formatted JSON object, which may be iterated through using jQuery's 'each()'
	* function, for example.
	*
	* @param String The ID of the original table we've now turned into an editable datagrid
	* @return Object JSON object containing the data in the datagrid
	*/
	function wolftools_getGridData(original_table_id)
	{
		var ret = {};
		if ($('#wolftools_divGridContainer_'+ original_table_id)[0])
		{
			var div_container = $('#wolftools_divGridContainer_'+ original_table_id);
			var editables = div_container.find('input');
			editables.each(function(input_index, input_item)
			{
				var key = $(input_item).attr('name');
				var val = $(input_item).attr('value');
				if (key != "")
					ret[key] = val;
			});
		}
		return ret;
	}