function insertSorters(myCP, color_id) {	
	var cpid = $(myCP).attr('id');
	$('td.SUBHEADER', myCP)
	//this is to filter only the first column header row
	.filter(function() {
		if ($(this).attr("colspan") == '50')
			return false;
		else {
			//text align the col-headers
			$(this).css('text-align', 'center');
			
			var parent_row = $(this).parents('tr');
			var prev_row = parent_row.prev();
			while (!prev_row.is(':first-child')) {
				if (prev_row.children('td.ODD').length > 0)
					return false;
				else	
					prev_row = prev_row.prev();
			}
			return true;
		}								
	})
	.wrapInner("<div class='col-header-wrapper'></div>")	
	.append(
		"<div class='sorters'>" + 
		"<img class='sorter-up' src='images/up-arr.png'></img>" +
		"<img class= 'sorter-down' src='images/down-arr.png'></img>" + 
		"</div>"
	);	
	
	$('.sorter-up, .sorter-down', myCP).each(function() {
		parent_tr = $(this).parents('tr')[0];
		parent_td = $(this).parents('td')[0];
		cells = $('td', parent_tr);
		count = cells.length;
		for(x=1; x <= count; x++) {
			if ($(parent_td).is(':nth-child(' + x + ')')) {
				index = x;
				break;
			}	
		}
		if ($(this).hasClass('sorter-up'))
			$(this).attr({
				'id': cpid + '-up-' + index,
				'title': 'sort ascending'
			});			
		else
			$(this).attr({
				'id': cpid + '-down-' + index,
				'title': 'sort descending'	
			});				
	});
	
	$('.sorter-up, .sorter-down', myCP).click(function() {
		myparams = $(this).attr('id').split('-');
		tab_id = myparams[0].replace('cp', '');
		sort_order = myparams[1]; 
		sort_column = myparams[2];
		$(myCP).load('index.php/user/sortReport/' 
		+ tab_id + '/' + sort_column + '/' + sort_order, 
			function() {
				insertSorters(this, color_id);
				tidyUpReport(this);
			
				//color the rows
				$("TD.SUBHEADER", myCP).addClass("SUBHEADER" + color_id);
				$("TD.FOOTER", myCP).addClass("FOOTER" + color_id);
				$("TD.FIELDS", myCP).addClass("FIELDS" + color_id);				
			}
		);
		
	});
}

function tidyUpReport(myCP) {
	$("td.ODD, td.FIELDS", myCP)
	.filter(function() {
		text = $(this).text();
		if (text.length < 5)
			return true;
		else
			return false;		
	})
	.css('text-align', 'center');
}
