addEvent(window, "load", sortables_init);

var isIE = navigator.userAgent.indexOf("MSIE") != -1;

var rates = new Array();
rates["$"] = 1;
rates["£"] = 2.0;
rates["€"] = 1.55;

function NumberCompare(a, b)
{
	return parseFloat(a)-parseFloat(b);
}

function StringCompare(a, b) 
{
	a = a.replace(/&/gm, "");
	b = b.replace(/&/gm, "");
	
	a = a.toLowerCase();
	b = b.toLowerCase();
	
	if (a < b)
		return -1;
	else if (a > b)
		return 1;
	else
		return 0;
}
	
function GameCompare(a, b)
{
	a = a.toLowerCase();
	b = b.toLowerCase();
	
	if (a.indexOf("blackjack") != -1)
		a = "blackjack" + a;
	else if(a.indexOf("poker") != -1 || a.indexOf("pai go") != -1)
		a = "poker" + a;
		
	if (b.indexOf("blackjack") != -1)
		b = "blackjack" + b;
	else if(b.indexOf("poker") != -1 || b.indexOf("pai gow") != -1)
		b = "poker" + b;
	
	return StringCompare(a, b);
}

function RiskCompare(a, b)
{
	order = new Array();
	order["none"] = 1;
	order["low"] = 2;
	order["low/high"] = 3;
	order["med"] = 4;
	order["medium"] = 4;
	order["high"] = 5;
	order["veryhigh"] = 6;

	a = a.toLowerCase();
	b = b.toLowerCase();
	
	a = a.replace(/\s/g, "");
	b = b.replace(/\s/g, "");
	
	return NumberCompare(order[a], order[b]);
}

function RankCompare(a, b)
{
	function Parse(entry)
	{
		if ((entry.indexOf("NA") != -1) || (entry.indexOf("na") != -1))
			return new Array(9999999, 0);
			
		var re = new RegExp("([0-9]+)([a-z]?)");
		entry = entry.toLowerCase();
		matches = re.exec(entry);
		return new Array(parseFloat(matches[1]), matches[2]);
	}
	
	a = Parse(a);
	b = Parse(b);
	
	if (a[0] < b[0])
		return -1;
	else if (a[0] > b[0])
		return 1;
	else
	{
		if (!a[1])
			return 1;
			
		if (!b[1])
			return -1;
		
		if (a[1] < b[1])
			return -1;
		else if (a[1] > b[1])
			return 1;
		
		return 0;
	}
}

function BonusEVCompare(a, b)
{
	function Parse(entry)
	{
		//entry = "+$50 or +$100";
		if (entry.indexOf("Negative") >= 0 || entry.indexOf("negative") >= 0)
			return -1;

		if (entry.indexOf("None") >= 0 || entry.indexOf("none") >= 0)
			return 0;

		if (entry.indexOf("No Bonus") >= 0 || entry.indexOf("no bonus") >= 0)
			return 0;

		if (entry.indexOf("Varies") >= 0 || entry.indexOf("varies") >= 0)
			return 1;

		if (entry.indexOf("Unlimited") >= 0 || entry.indexOf("unlimited") >= 0)
			return 9999;

		
		re = /(\+\d+)\s*([£$€])\s*(\(.*\))?\s*x\s*(\d+)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value = rates[matches[2]]*parseFloat(matches[1]) * parseFloat(matches[4]);
				
			//alert(entry);
			//alert(value);
			return value;
		}

		re = /\+([£$€])\s*(\d+)\s*(\(.*\))?\s*x\s*(\d+)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value = rates[matches[1]]*parseFloat(matches[2]) * parseFloat(matches[4]);
				
			//alert(entry);
			//alert(value);
			return value;
		}
		
		re = /\+(\d+)([£$€])\s*(\(.*\))?\s*((or)|,)\s*\+?\s*(\d+)([£$€])\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[2]]*parseFloat(matches[1]);
			var value_r = rates[matches[7]]*parseFloat(matches[6]);
			
			var value;
			if (value_l > value_r)
				value = value_l;
			else
				value = value_r;
				
			//alert(entry);
			//alert(value);
			return value;
		}		

		re = /\+([£$€])(\d+)\s*(\(.*\))?\s*((or)|,)\s*\+?\s*([£$€])(\d+)\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[1]]*parseFloat(matches[2]);
			var value_r = rates[matches[6]]*parseFloat(matches[7]);
			
			var value;
			if (value_l > value_r)
				value = value_l;
			else
				value = value_r;
			
			//alert(entry);
			//alert(value);
			return value;
		}		

		re = /(\+\d+)([£$€])\s*(\(.*\))?\s*(\??)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			value = rates[matches[2]]*parseFloat(matches[1]);
			
			//alert(entry);
			//alert(value);
			return value;
		}

		re = /\+([£$€])(\d+)\s*(\(.*\))?\s*(\??)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			value = rates[matches[1]]*parseFloat(matches[2]);
			
			//alert(entry);
			//alert(value);
			return value;
		}
		
		return 0;
	}
	
	a = Parse(a);
	b = Parse(b);		
	
	return -NumberCompare(a, b);
}

function MaxBonusCompare(a, b)
{
	function Parse(entry)
	{
		if (entry.indexOf("%") != -1)
			return 9999999;
		
		if (entry.indexOf("None") >= 0 || entry.indexOf("none") >= 0)
			return 0;

		var matches;
		
		re = /(\d+)([£$€])\s*(\(.*\))?\s*x\s*(\d+)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value = rates[matches[2]]*parseFloat(matches[1]) * parseFloat(matches[4]);
				
			//alert(entry);
			//alert(value);
			return value;
		}
		
		re = /([£$€])(\d+)\s*(\(.*\))?\s*x\s*(\d+)/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value = rates[matches[1]]*parseFloat(matches[2]) * parseFloat(matches[4]);
				
			//alert(entry);
			//alert(value);
			return value;
		}

		re = /(\d+)([£$€])\s*(\(.*\))?\s*((or)|,|\/|(to))\s*(\d+)([£$€])\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[2]]*parseFloat(matches[1]);
			var value_r = rates[matches[8]]*parseFloat(matches[7]);
			
			var value;
			if (value_l > value_r)
				value = value_l;
			else
				value = value_r;
				
			//alert(entry);
			//alert(value);
			return value;
		}

		re = /([£$€])(\d+)\s*(\(.*\))?\s*((or)|,|\/|(to))\s*([£$€])(\d+)\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[1]]*parseFloat(matches[2]);
			var value_r = rates[matches[7]]*parseFloat(matches[8]);
			
			var value;
			if (value_l > value_r)
				value = value_l;
			else
				value = value_r;
				
			//alert(entry);
			//alert(value);
			return value;
		}

		re = /(\d+)([£$€])\s*(\(.*\))?\s*\+\s*(\d+)([£$€])\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[2]]*parseFloat(matches[1]);
			var value_r = rates[matches[5]]*parseFloat(matches[4]);
			
			var value = value_l + value_r;
				
			//alert(entry);
			//alert(value);
			return value;
		}
		
		re = /([£$€])(\d+)\s*(\(.*\))?\s*\+\s*([£$€])(\d+)\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			var value_l = rates[matches[1]]*parseFloat(matches[2]);
			var value_r = rates[matches[4]]*parseFloat(matches[5]);
			
			var value = value_l + value_r;
				
			//alert(entry);
			//alert(value);
			return value;
		}
		
		re = /([£$€])(\d+)\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			value = rates[matches[1]]*parseFloat(matches[2]);
			//alert(matches);
			//alert(value);
			return value;
		}

		re = /(\d+)([£$€])\s*(\(.*\))?/mi;
		matches = entry.match(re);
		
		if (matches)
		{
			value = rates[matches[2]]*parseFloat(matches[1]);
			//alert(matches);
			//alert(value);
			return value;
		}

		return 0;
	}
	
	a = Parse(a);
	b = Parse(b);		
	return -NumberCompare(a, b);
}

function WagerCompare(a, b)
{
	function Parse(entry)
	{
		if ((entry.indexOf("None") != -1) || (entry.indexOf("none") != -1))
			return new Array("", -1, "");

		if (entry.indexOf("Bets") >= 0)
			return new Array("", 0.5, "");
			
		re = /[(]?([0-9]+)(\+)?\s*[*]?\s*xB\s*(\/|or)?\s*([0-9]*)/m;
		var matches = entry.match(re);
		if ((matches[2]) &&(matches[2] != ""))
			matches[1] = parseFloat(matches[1])+0.1
		return matches;
	}
	
	a = Parse(a);
	b = Parse(b);		
	
	var r = NumberCompare(a[1], b[1]);
	if (r == 0)
	{
		if ((a[4]) && a[4] != "" && (b[4]) && b[4] != "")
			r = NumberCompare(a[4], b[4]);
		else if ((a[4]) && a[4] != "")
			r = 1;
		else
			r = -1;
	}
	return r; 
}

function BonusPercentCompare(a, b)
{
	function Parse(entry)
	{
		if ((entry.indexOf("None") != -1) || (entry.indexOf("none") != -1))
			return 0;

		if (entry.indexOf("Varies") >= 0 || entry.indexOf("varies") >= 0 || entry.indexOf("NA") >= 0)
			return 99999999;

		if(entry.search(/no\s*deposit/mi) != -1)
			return 99999999;

		re = /[(]?([0-9]+)[%]?\s*(to|-|or)?\s*([0-9]+)?[%]?/m;
		var matches = entry.match(re);
		
		var value;
		if (matches[3] && matches[3] != "")
		{
			value = parseFloat(matches[3])-1/parseFloat(matches[1]);
		}
		else
			value = parseFloat(matches[1]);
		
		if (entry.indexOf("Loss") >= 0)
			value -= 0.1;
			
		return value;
	}
	
	a = Parse(a);
	b = Parse(b);		
		
	return -NumberCompare(a, b);
}

var comparers = new Array();
comparers["casino"] = StringCompare; // OK
comparers["casinos/group"] = StringCompare; // OK
comparers["software"] = StringCompare; // OK
comparers["group"] = StringCompare; // OK
comparers["type"] = StringCompare; // OK
comparers["game"] = GameCompare; // OK
comparers["us?"] = StringCompare; // OK
comparers["usa?"] = StringCompare; // OK
comparers["notes"] = StringCompare; // OK
comparers["risk"] = RiskCompare; // OK
comparers["time"] = RiskCompare; // OK
comparers["rank"] = RankCompare; // OK
comparers["bonusev"] = BonusEVCompare; // OK
comparers["bonusev(nobigbet)"] = BonusEVCompare; // OK
comparers["bonusev(withbigbet)"] = BonusEVCompare; // OK
comparers["bonusev"] = BonusEVCompare; // OK
comparers["maxbonus"] = MaxBonusCompare; // OK
comparers["wager"] = WagerCompare; // OK
comparers["frwager"] = WagerCompare; // OK
comparers["bonus%"] = BonusPercentCompare; // OK
comparers["link"] = StringCompare; // OK
comparers["summary"] = StringCompare; // OK
comparers["houseedge"] = StringCompare; // OK
comparers["decks"] = StringCompare; // OK
comparers["soft17"] = StringCompare; // OK
comparers["peekforbj"] = StringCompare; // OK
comparers["double"] = StringCompare; // OK
comparers["doubleaftersplit"] = StringCompare; // OK
comparers["resplit"] = StringCompare; // OK
comparers["resplitaces"] = StringCompare; // OK
comparers["hitsplitaces"] = StringCompare; // OK
comparers["surrender"] = StringCompare; // OK
comparers["gameversion"] = GameCompare; // OK
comparers["handsperhour"] = BonusPercentCompare; // OK
comparers["handsperminute"] = BonusPercentCompare; // OK
comparers["hourstoplay1000hands"] = BonusPercentCompare; // OK


function sortables_init() {
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName)
		return;
    
	tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            ts_makeSortable(thisTbl);
   			stripe(thisTbl,1);
        }
		else if( ((' '+thisTbl.className+' ').indexOf("zebra") != -1) && (thisTbl.id))
		{
			stripe(thisTbl,0);
		}
    }
}

function ts_makeSortable(table) {
	if (table.rows && table.rows.length > 0) {
			var firstRow = table.rows[0];
	}
	if (!firstRow)
	{
		return;
	}
	
	table.setAttribute('sorted', 0);
	table.setAttribute('sortcolumn', 0);
	
	// We have a first row: assume it's the header, and make its contents clickable links
	//alert( firstRow.childNodes.length );
	var j = 0;
	for (var i=0;i<firstRow.childNodes.length;i++) {
		var cell = firstRow.childNodes[i];
		var txt = ts_getInnerText(cell);
		if( cell.className != "noclick" )
		{
			if(cell.tagName)
			{
				var cmpName = txt.toLowerCase();
				cmpName = cmpName.replace(/\s/g, "");
				cell.innerHTML = "<a href=\"javascript:void(0)\" class=\"sortheader\" onclick=\"SortTable('"+table.id+"', "+j+", comparers['"+cmpName+"'])\">"+txt+"<span class=\"sortarrow\"></span></a>";
				j++;
			}
		}
	}
}

function ts_getInnerText(el) {
	if (typeof( el ) == "string")
	{
		return el;
	}
	if (typeof( el ) == "undefined")
	{
		return el;
	}
	if (el.innerText)
	{
		return el.innerText;	//Not needed but it is faster
	}
	var str = "";
	//alert("passed default returns");

	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function SortTable(tableId, column, compare)
{
	var table = document.getElementById(tableId);
	if (!table)
		return;

	if (table.rows.length <= 1)
    	return;
	
	var sorted = table.getAttribute('sorted');
	var prevCol = table.getAttribute('sortcolumn');
	var txt = ts_getInnerText(table.rows[0].cells[prevCol]);
	var cmpName = txt.toLowerCase();
	cmpName = cmpName.replace(/\s/g, "");
	var prevCmp = comparers[cmpName];
	table.setAttribute('sorted', 1);
	if (prevCol != column)
		table.setAttribute('sortcolumn', column);
	
	// Remove sortarrow classname for each span
	var ascending;
    var span = table.rows[0].cells[column].childNodes[0].childNodes[1];

	for(var i=0; i < table.rows[0].cells.length; i++)
		if (i != column)
		{
			table.rows[0].cells[i].style.background = "#000080";
			table.rows[0].cells[i].childNodes[0].style.fontStyle = "normal";
			table.rows[0].cells[i].childNodes[0].childNodes[1].className = "";
			table.rows[0].cells[i].childNodes[0].childNodes[1].setAttribute("sortdir", "");
		}

	var cell = table.rows[0].cells[column];
	cell.style.background = "#0000bb";
	var a = cell.childNodes[0];
	a.style.fontStyle = "italic";
	
	span.className = "sortarrow";
	if (span.getAttribute("sortdir") == 'down') {
        ascending = false;
		span.setAttribute('sortdir','up');
    } else {
		ascending = true;
		span.setAttribute('sortdir','down');
    }
	
	rows = new Array();
	var k = 0;
	for(var i=1; i < table.rows.length; i++)
		if ((table.rows[i].tagName == "tr") || (table.rows[i].tagName == "TR"))
		{
			rows[k] = table.rows[i];
			k++;
		}
	k--;
	
	rows.sort(
				function(a, b) 
				{ 
					var v1 = ts_getInnerText(a.cells[column])
					var v2 = ts_getInnerText(b.cells[column])
					
					var r;
					try
					{
						r = compare(v1, v2);
					}
					catch(e)
					{
						r = 0;
					}
					if((r == 0) && ((!sorted) || (!isIE)))
					{
						try
						{
							var w1 = ts_getInnerText(a.cells[prevCol]);
							var w2 = ts_getInnerText(b.cells[prevCol]);
							r = prevCmp(w1, w2);
						}
						catch(e)
						{
							r = 0;
						}
					}
					
					if (!ascending)
						r = -r;
					return r;					
				}
			);
	
	var l = rows.length;
	for(var i=1; i < l; i++)
		table.tBodies[0].appendChild(rows[i]);
		
	stripe(table, 1);
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}