
SortableTable.prototype = new Object();
SortableTable.prototype.constructor = SortableTable;
SortableTable.mTables = new Array();

SortableTable.SortByColumn = function( index, col )
{
	if ( !(SortableTable.mTables && SortableTable.mTables.length && index < SortableTable.mTables.length) ) { return; }
	var t = SortableTable.mTables[index];
	if ( t )
	{
		t.SortByColumn( col );
	}
};

function SortableTable( divName, cols, data, bJavascriptSort, cookieName )
{
	this.mIndex = SortableTable.mTables.push( this ) - 1;

	if ( bJavascriptSort === undefined ) { bJavascriptSort = true; }
	
	this.mbJavascriptSort = bJavascriptSort ? true : false;	
	this.mbNumbered = false;
	this.mSortDir = 1;
	this.mSortBy = -1;
	this.mColumns = cols;
	this.mData = data;
	this.mContainerDivName = divName;
	
	this.mCookieSortBy = cookieName;
	
	if ( !this.mCookieSortBy && divName )
	{
		this.mCookieSortBy = 'SRT'+divName+window.location.pathname.toUpperCase();
		this.mCookieSortBy = this.mCookieSortBy.substr(0,30);
		this.mCookieSortBy = this.mCookieSortBy.replace( /\W/g, '-' );
	}

	if ( this.mCookieSortBy )
	{
		var t = CookieGet( this.mCookieSortBy );
		if ( t != '' )
		{
			t = ConvertToInt( t );
			this.mSortDir = t<0 ? -1 : 1;
			t = Math.abs(t)-1;
			if ( 0<=t && t<this.mColumns.length ) // with customizeable columns, make sure the cookie doesn't index beyond the size
			{
				this.mSortBy = t;
			}
			else
			{
				CookieSet( this.mCookieSortBy, 0 );
				this.mSortDir = 1;
			}
		}
	}
//	DebugOutput( this.mCookieSortBy );
}

SortableTable.prototype.SetSelected = function( vals, bOn )
{
	for( var i=0; i<this.mData.length; i++ )
	{
		var row = this.mData[i];
		if ( row )
		{
			for( var j=0; j<row.length; ++j )
			{
				for ( var k = 0; k < vals.length; ++k ) // REVISIT -- optimize?
				{
					if ( vals[k] && row[j].k == vals[k] )
					{
						vals[k] = undefined;
						row.mbSelected = bOn;
						break;
					}
				}
			}
		}
    }	
};

SortableTable.prototype.SortByColumn = function( n )
{
	if (n<0 || n>=this.mColumns.length) return;
    
	if ( this.mSortBy == n )
	{
		this.mSortDir = -this.mSortDir; // flip it
	}
	else
	{
		this.mSortBy = n;
		this.mSortDir = this.mColumns[n].sort_dir;
		if (!this.mSortDir) this.mSortDir = 1;
	}
    
	if ( this.mCookieSortBy && this.mSortBy>=0 ) // update cookie if the sorting has been set
	{
		var cc = this.mSortDir<0 ? -1 : 1;
		cc *= Math.abs(this.mSortBy+1);
		CookieSet( this.mCookieSortBy, cc );
	}
    
	this.Render();
}

SortableTable.prototype.Render = function ()
{
	if ( !(this.mColumns && this.mData) ) { return; }

	if ( !this.mContainerDiv && this.mContainerDivName )
	{
		this.mContainerDiv = GetElement( this.mContainerDivName );
	}	
    var o = this.mContainerDiv;
    if (!o) return;

	o.innerHTML = '';    
	var rows = new Array();

	//--- Header ---//
    var rowspan = '';
    for( var i=0; i<this.mColumns.length; i++ )
    {
		var col = this.mColumns[i];
		if ( !col ) { continue; }
		
		if (col && col.header)
		{
			rowspan = ' rowspan=2';
			var colspan = 1;
			if (col.header == '=')
			{
				colspan = 0;
	    	}
		    else
		    {
				for( var j=i+1; j<this.mColumns.length; j++ )
				{
		    		if (this.mColumns[j].header != '=') break;
		    		colspan++;
				}
	    	}
	    	
			this.mColumns[i].colspan = colspan;
		}
	
		if ( col && col.default_sort && this.mSortBy<0 )
		{
			this.mSortBy = i;
			if ( col.sort_dir )
			{
				this.mSortDir = col.sort_dir;
			}
		}
    }

	var t = this.mbNumbered ? '<TH'+rowspan+' id=first_col style="width:20px; max-width:50px;">#</TH>' : '';
	var t2 = '';
	
	var td_style = new Array();
	var td_class = new Array();
	for( var i=0; i<this.mColumns.length; i++ )
	{
		var col = this.mColumns[i];
		if ( !col ) { continue; }
		
		var style = '';
		if (col.align) style += 'text-align: '+col.align+';';
//		if (col.width) style += 'width: '+col.width+'px; min-width: '+col.width+'px;';
		if (col.width) style += 'min-width: '+col.width+'px;';
		if (style) style = ' style="'+style+'"';
		td_style[i] = style;
		
		var cl = '';
		if (col.cls) {cl = (' class="' + col.cls + '"');}
		td_class[i] = cl;

		var sort_lbl = this.mSortDir>0 ? '&darr;' : '&uarr;';
		var left_sort = '';
		var right_sort = '';
		
		if (sort_lbl)
		{
			left_sort 	= '<TD style="padding: 0px 0px 4px 2px; vertical-align:bottom; visibility:hidden;">'+sort_lbl+'</TD>';
			right_sort 	= '<TD style="padding: 0px 0px 4px 2px; vertical-align:bottom; visibility:'+(i==this.mSortBy?'visible':'hidden')+';">'+sort_lbl+'</TD>';
		}

		var col_href = col.href;	
		var col_title = col.no_sort ? col.title
				   : '<A href="'+(col_href?(col.href+'"'):('javascript:void(0)" onclick="SortableTable.SortByColumn('+this.mIndex+','+i+')"'))+' onmouseover="UI_ShowPopup(true, \'Click to sort the table by this column\', undefined, event)"><B>'+col.title+'</B></A>';
		if (col.help)
		{
			col_title = '<TABLE border=0 cellpadding=0 cellspacing=0 style="margin:0px;"><TR><TD style="vertical-align:bottom;padding-bottom:0px;">'+col_title+'</TD>';
			col_title +='<TD style="text-align:left;vertical-align:bottom;padding-bottom:0px;"><IMG src="/img/question.png" class=question onMouseOver="UI_ShowPopup(true,\''+col.help+'\',undefined,event)"'+(col.help_link?'onclick="RedirectImmediate(\''+col.help_link+'\');"':'')+'></TD></TR></TABLE>';
		}
	
		col_title = '<TABLE border=0 cellpadding=0 cellspacing=0 class=no_border><TR>' + left_sort + '<TD>' + col_title + '</TD>' + right_sort + '</TR></TABLE>';

		style = '';
//		if (col.width) style += 'width: '+col.width+'px; min-width: '+col.width+'px;';
		if (col.width) style += 'min-width: '+col.width+'px;';
		if (style) style = ' style="'+style+'"';

		var col_id = t ? ((i<this.mColumns.length-1)?'':' id=last_col') : ' id=first_col';
		if (rowspan && col.header)
		{
	    	if (col.colspan>0) t += '<TH colspan='+col.colspan+col_id+' style="text-align: center;">'+col.header+'</TH>\n';
	    	t2 += '<TH'+col_id+style+'>'+col_title+'</TH>\n';
		}
		else
		{
	    	t += '<TH'+col_id+style+rowspan+'>'+col_title+'</TH>\n';
		}
    }
 	rows.push( '<TR>' + t + '</TR>\n' );
    if (t2) rows.push( '<TR>' + t2 + '</TR>\n' );
    
    //--- Rows ---//
	for( var i=0; i<this.mData.length; i++ )
	{
		var row = this.mData[i];
		for( var j=0; j<row.length; ++j )
		{
			if (row[j].e!=undefined) row[j].t = unescape(row[j].e);
			if (row[j].k==undefined) row[j].k = row[j].t;
    	}
    }

	var self = this;
	if (this.mSortBy>=0 && this.mbJavascriptSort) this.mData.sort( function(a,b){ return self.CompareData(a,b); } );

	var odd = 1;
	for( var i=0; i<this.mData.length; i++ )
	{
		var row = this.mData[i];
		
		var cl = row.mbSelected?'selected_list':(odd?'odd_list':'even_list');
		t = this.mbNumbered?('<TD id=first_col style="text-align:right;">'+(i+1)+'.</TD>'):'';
		odd = !odd;

		for( var j=0; j<row.length; j++ )
		{
			var row_id = t ? ((j<row.length-1)?'':' id=last_col') : ' id=first_col';
			var tag = row[j].t;
			t += '<TD'+row_id+td_class[j]+td_style[j]+'>'+tag+'</TD>';
		}

		t = '<TR class='+cl+'>' +t+ '</TR>';
		rows.push( t );
	}
    
    if (this.mData.length==0)
	{
		var num_cols = this.mColumns.length+1;
		rows.push( '<TR class=odd_list><TD colspan='+num_cols+'>&hellip; none found &hellip;</TD></TR>' );
    }
    
    var cname = 'list';
    if ( this.mTableClassName )
    {
    	cname = this.mTableClassName;
    }
	o.innerHTML = '<TABLE class='+cname+' cellpadding=0 cellspacing=0 border=0>' + rows.join('') + '</TABLE>';
};

SortableTable.prototype.CompareData = function( a, b )
{
	if (a[this.mSortBy].k>b[this.mSortBy].k) return -this.mSortDir;
	if (a[this.mSortBy].k<b[this.mSortBy].k) return this.mSortDir;
    return 0;
}

/*
function ctflag(c)
{
    c = c.toLowerCase();
    if (!c || c=='zz') return '';
    return '<img src="/img/flags/'+c+'.gif" style="border: 0px; width: 18px; height: 12px; padding: 0px 6px 0px 2px; vertical-align: middle;">';
}

function uid(u,ps)
{
    var golden_pawn = ps>0 && ps<=3 ? '<a href="/premium.pl" title="premium subscriber"><img class=img-ps src="/img/pm'+ps+'.gif"></a>' : '';
    var os = '';
    if ((typeof req_online_status)=='function')
    {
	os = '<img class=img-onl'+
		( !req_online_status( u ) ? ' style="display: none;"' : '' )+
		' src="/img/online.gif" id="onlsts-'+u+'" title="player is currently online">';
    }
    return os+'<a href="/stats.pl?'+u+'" onMouseOver="gk_mnst(event,\''+u+'\')">'+u+'</a>'+golden_pawn;
}

function rcol(c)
{
    if (!c) return '';
    var c = c.toUpperCase();
    var col = 'color: #666666; background-color: #ffffff;';
    if (c!='W')
    {
	c = 'B';
	col = 'color: #aaaaaa; background-color: #000000;';
    }
    return '<div style="'+col+' width: 14px; margin: auto; text-align: center;"><b class=sml>'+c+'</b></div>';
}
*/
