/**
* Creates an element and returns it
*/
function CreateElement(elementName, className, attributes, text, html)
{
	var element = $(document.createElement(elementName));
	if (className) { element.addClass(className); }
	if (attributes) { element.attr(attributes); }
	if (html != null)
	{
		var children = $.isArray(html) ? html : [ html ];
		$.each(children, function (key, value) { element.append(value); });
	}
	else if (text != null) { element.text(text); }
	return element;
}

/**
* Creates the table row with a cell data and returns it
*/
function CreateTableRow(className, attributes, text, html)
{
	return CreateTableCell(CreateElement('tr'), className, attributes, text, html);
}

/**
* Creates the table cell, appends it to the row and returns the latter
*/
function CreateTableCell(row, className, attributes, text, html)
{
	return $(row).append(CreateElement('td', className, attributes, text, html));
}

// Initializing table rows per page options
var rowsPerPageOptions = new Array(20, 50, 200);

/**
* Initializes the table footer
*/
function InitializeTableFoot(data, foot, title, navPageFunc, rowsPerPageID)
{
	var tableRow, tableCell;
	var page = parseInt(data['page']);
	var rowsPerPage = parseInt(data['rowsperpage']);
	var totalCount = parseInt(data['totalcount']);
	var skip = rowsPerPage * (page - 1);
	var rowsFrom = totalCount > 0 ? skip + 1 : 0;
	var rowsTo = (page * rowsPerPage < totalCount) ? page * rowsPerPage : totalCount;
	
	var columnCount = 0;
	// Calculating the column count
  $(foot).siblings('thead').children().eq(0).children().each(function () {
    var colSpan = $(this).attr('colSpan');
    if (colSpan) { columnCount += parseInt(colSpan); } else { columnCount++; }
  });

	// Removing old data
	$(foot).empty();
	
	// Generating the row count per page options
	var rowsPerPageSelect = null;
	if (rowsPerPageID)
	{
	    rowsPerPageSelect = CreateElement('select', null, { name: rowsPerPageID, id: rowsPerPageID, title: 'Rows per page' })
                        .change(function () { navPageFunc(1); });
	    
        for (var key in rowsPerPageOptions) {
            var optionValue = rowsPerPageOptions[key];
            rowsPerPageSelect.append(CreateElement('option', null,
                { value: optionValue, selected: rowsPerPage == optionValue }, optionValue));
        }
	}

	// Creating the new table row and adding Count column
	tableRow = CreateTableRow(null, { colSpan: columnCount - 1, noWrap:  true }, null,
		[ title + ': ' + rowsFrom + '-' + rowsTo + ' of ' + totalCount + '&nbsp;&nbsp;&nbsp;',
      rowsPerPageSelect ]);

	// Adding Navigation column
	tableCell = CreateElement('td', 'tdNav', { noWrap: true }, null, '&nbsp;');
	
  // Adding Previous Page link
	if (page > 1)
	{
		tableCell.append(CreateElement('a', null, { href: '#' }, 'Prev')
		                .click(function () { navPageFunc(page - 1); return false; }));
	}
	
	// Adding link separator
	tableCell.append(' ');
	
  // Adding Next Page link
	if (rowsPerPage * page < totalCount)
	{
		tableCell.append(CreateElement('a', null, { href: '#' }, 'Next')
		                .click(function () { navPageFunc(page + 1); return false; }));
	}

	// Adding the new row to the table's foot
	$(foot).append(tableRow.append(tableCell));
}

/**
* Initializes the table footer
*/
function InitializeTableHead(data, head, title, callback)
{
	var sortSymbol = {'1':'&#8593;', '-1':'&#8595;', '':''};
	var tableRow;
	var sortOrder = parseInt(data['sort']['order']);
	var sortDirection = parseInt(data['sort']['direction']);
	var columns = data['columns'];

	// Removing old data
	$(head).empty();

	tableRow = CreateElement('tr');

	$(head).append(tableRow);

	for (var i in columns) {
		var tableCell = CreateElement('td', null, null, null, "");
		var sort = '';
		if (sortOrder==i) {
			sort = sortSymbol[sortDirection] + '&nbsp;';
		}
		var tableCellLink = CreateElement('a', null, { href: '#', title: 'Order by ' + columns[i]}, null, sort + columns[i]);
		tableCellLink.click(
			(function c(arg){ return function cp(){ callback(arg); return false; }; })(i)  // it needs to avoid referencing problem
		);
		tableCell.append(tableCellLink);
		tableRow.append(tableCell);
	}

	
}

