﻿function getTableTBody(table)
{
	if(table.tagName != "TABLE") return table;

	for(var index = 0; index < table.childNodes.length; index++)
	{
		if(table.childNodes[index] != null && table.childNodes[index].tagName == "TBODY")
		{
			return table.childNodes[index];
		}
	}
	
	var newTBody = document.createElement("TBODY");
	table.appendChild(newTBody);
	
	return newTBody;
}

function addTemplateElementAttribute(parentElement, attributeName, attributeValue)
{
	if(attributeName == 'style')
	{
		if(parentElement.style)
		{
			parentElement.style.cssText = attributeValue;
		}
	}
	else if(attributeName == 'onclick')
	{
		parentElement.onclick = function anon() {eval(attributeValue);};
	}
	else if(attributeName == 'oncontextmenu')
	{
		parentElement.oncontextmenu = function anon() {eval(attributeValue);};
	}
	else if(attributeName == 'nowrap')
	{
		parentElement.nowrap = true;
	}
	else if(attributeName == 'class')
	{
		parentElement.className = attributeValue;
	}
	else
	{
		parentElement.setAttribute(attributeName, attributeValue);
		//var attr = document.createAttribute(attributeName);
		//attr.value = attributeValue;
		//control.attributes.setNamedItem(attr);
	}
}

function createChildElement(parentElement, childTag)
{
	var childElement;

	if((parentElement.tagName == 'TABLE' || parentElement.tagName == 'TBODY') && childTag == 'tr')
	{
	    if(parentElement.rows.length == 0)
		    childElement = parentElement.insertRow(0);
		else
		    childElement = parentElement.insertRow(-1);
	}
	else if(parentElement.tagName == 'TR' && childTag == 'td')
	{
	    if(parentElement.cells.length == 0)
	        childElement = parentElement.insertCell(0);
	    else
	        childElement = parentElement.insertCell(-1);
	}
	else
	{
		childElement = document.createElement(childTag);
	}
	
	return childElement;
}

function appendChildElement(parentElement, childElement)
{
	if((parentElement.tagName == 'TABLE' || parentElement.tagName == 'TBODY') && childElement.tagName == 'TR')
	{
		return;
	}
	else if(parentElement.tagName == 'TR' && childElement.tagName == 'TD')
	{
		return;
	}
	else
	{
		parentElement.appendChild(childElement);
	}
}