function makeTable(id, json) 
{
	json = eval(json);
	var tbody = $('#'+id);

	tbody.html('');

	jQuery.each(json, function(tr, tr_content) 
	{
		var dom_tr = $(document.createElement('tr'));
		jQuery.each(json[tr][0], function(opt, value) 
		{
			dom_tr.attr(opt, value);
		});

		jQuery.each(json[tr][1], function(opt, value) 
		{
			var dom_td = $(document.createElement('td'));
			jQuery.each(json[tr][1][opt], function(_opt, _value) 
			{
				if(_opt != 'html') {
					dom_td.attr(_opt, _value);
				} else {
					dom_td.html(_value);
				}
			});
			dom_tr.append(dom_td);
		});
		tbody.append(dom_tr);
	});
}

function getPage(tableID, numPage, maxPages, relativePath, addValue) 
{
	if (relativePath==undefined) {
		relativePath=0;
	} else if (typeof(rel_path[relativePath])=='undefined') {
		relativePath=0;
	}
	var strurl=rel_path[relativePath];
	strurl += '/ajax.php?frm_id=' + tableID;
	var datas='p='+numPage;
	if (addValue!=undefined) {
		datas += '&value=' + addValue;
	}
	$.ajax({
		url: strurl,
		data: datas,
		type: 'GET',
		error: function(responseText) 
		{ 
			alert(critical_error);
		},
		success: function(responseText) 
		{
			makeTable(tableID, responseText);
			if ( maxPages > 1) {
				makePagesLinks(tableID, maxPages, numPage, relativePath, addValue);
			}
		}
	});
}

function makePageLink(tableID, page, content, nbPages, relativePath, addValue) 
{
	var a = $(document.createElement('a'));
	a.html(content);
	a.attr('rel', page);
	a.attr('style', 'cursor: pointer;');
	a.click(function() 
	{
		var n = parseInt($(this).attr('rel'));
		getPage(tableID, n, nbPages, relativePath, addValue);
	});
	return a;
}

function makePagesLinks(tableID, nbPages, currentPage, relativePath, addValue) 
{
	var p = $('#' + tableID + '_pg_links');
	p.html('');
	p.attr('style', 'text-align: center;');

	p.append(makePageLink(tableID, 1, '|<', nbPages, relativePath, addValue));
	p.append('&nbsp;');
	p.append(makePageLink(tableID, Math.max(currentPage-1, 1), '<<', nbPages, relativePath, addValue));
	p.append('&nbsp;');

	if(nbPages > 15) {
		var start = Math.max(1, currentPage-3);
		var end   = Math.min(nbPages, currentPage+3);

		if(start == 1) {
			end = 7;
		} else {
			p.append('<a>...</a>&nbsp;');
		}

		if(end == nbPages) {
			start = nbPages-6;
		}
	} else {
		var start = 1;
		var end   = nbPages;
	}

	for(var u=start; u<=end; u++) {
		a=makePageLink(tableID, u, u, nbPages, relativePath, addValue);
		if(u == currentPage) {
			a.attr('class', 'current');
		}
		p.append(a);
		p.append('&nbsp;');
	}

	if(end != nbPages) {
		p.append('<a>...</a>&nbsp;');
	}

	p.append(makePageLink(tableID, Math.min( currentPage+1, nbPages), '>>', nbPages, relativePath, addValue));
	p.append('&nbsp;');
	p.append(makePageLink(tableID, nbPages, '>|', nbPages, relativePath, addValue));
}
