//declare constants   
var COMP_TYPE_RATING	= 0;
var COMP_TYPE_STRING	= 1;
var COMP_TYPE_NUMERIC	= 2;
var COMP_TYPE_DATE	= 3;
var COMP_OP_EQ			= 0;
var COMP_OP_LT			= 1;
var COMP_OP_GT			= 2;
var SORT_ORDER_ASC		= 0;
var SORT_ORDER_DESC		= 1;
//constants for topmenu color change
var COLOUR_TOPMENU_ACTIVE       = "#77052e";
var COLOUR_TOPMENU_INACTIVE     = "#2c3f53";


var RATINGS	= new Array(
	"AAA+",
	"AAA",
	"AAA-",
	"AA+",
	"AA",
	"AA-",
	"A+",
	"A",
	"A-",
	"BBB+",
	"BBB",
	"BBB-",
	"BB+",
	"BB",
	"BB-",
	"B+",
	"B",
	"B-",
	"CCC+",
	"CCC",
	"CCC-",
	"CC+",
	"CC",
	"CC-",
	"C+",
	"C",
	"C-"
);
	
//declare global variables
var current_visible_desc = 0;
var banks = Array();
var last_sort_col = 0;
var sort_order;

function showBankHistory(regn) {
    window.open("http://www.rusrating.ru/internal/ru/"+regn+".php",'','height=400,width=300,toolbar=no,directories=no,status=no,menubar=no,resizable=yes,scrollbars=yes');
}

// displays the bank description by making its container visible
function showBankDesc(regn) {
	// if selected element is currently visible, hide it.
	if(current_visible_desc == regn) {
		var hideItem = document.getElementById("ratinglist_description_" + current_visible_desc);
		hideItem.style.display = "none";
		current_visible_desc = 0;
	}
	// otherwise show selected element
	else {	
		// hide currenly visible element if one exists
		if(current_visible_desc > 0) {
			var hideItem = document.getElementById("ratinglist_description_" + current_visible_desc);
			hideItem.style.display = "none";
		}

		// show selected element
		var item = document.getElementById("ratinglist_description_" + regn);
		item.style.display = "block";
	
		//remember that it is visible
		current_visible_desc = regn;
	}
		
}

// sort a column (descending)
function sort(column) {
	// if the sort column is the same as last time, then change the sort order
	if(column == last_sort_col) {
		sort_order = ( sort_order + 5 ) % 2;
	} else {
		sort_order = SORT_ORDER_DESC;
	}
	last_sort_col = column;
	
	// if the column is the rating column,
	// then the comparison type is COMP_TYPE_RATING,
	// otherwise default to COMP_TYPE_STRING
	if(parseInt(column) == 4) {
		sortCol(column, COMP_TYPE_RATING);
	} else if(parseInt(column) == 3 || parseInt(column) == 5) {
		sortCol(column, COMP_TYPE_DATE);
	} else {
		sortCol(column, COMP_TYPE_STRING);
	}
}

function typedSort(column,type) {
	// if the sort column is the same as last time, then change the sort order
	if(column == last_sort_col) {
		sort_order = ( sort_order + 5 ) % 2;
	} else {
		sort_order = SORT_ORDER_DESC;
	}
	last_sort_col = column;
	
	// if the column is the rating column,
	// then the comparison type is COMP_TYPE_RATING,
	// otherwise default to COMP_TYPE_STRING
	if(type == 'rating') {
		sortCol(column, COMP_TYPE_RATING);
	} else if(type == 'date') {
		sortCol(column, COMP_TYPE_DATE);
	} else {
		sortCol(column, COMP_TYPE_STRING);
	}
}



// ***** Private Functions *****

/* actualy sort the column acording to given comparison type
	
	column	- the number of the column to sort by
	type	- the comparison type (eg COMP_TYPE_RATING)
*/
function sortCol(column, type) {
	var table = document.getElementById("ratinglist_body");
	var rows = table.getElementsByTagName("tr");
	
	// If the bank list is empty, create it.
	if(banks.length <= 0) {
		for(var i=0; i < rows.length; i++) {
			if(rows[i].getElementsByTagName("td").length > 1) {
				var regnstr = rows[i].getAttribute("id").substring(16);
				var regn = parseInt(regnstr, 10);

				if(! isNaN(regn)) {
					banks.push(new Bank(regn));
				}
			}
		}
	}
	
	// fill up bank list with data
	for(var i=0; i < banks.length; i++) {
		var row = document.getElementById("ratinglist_info_" + banks[i]['regn']);
try{
		var value = row.getElementsByTagName("td")[column].firstChild.nodeValue;
		banks[i]['value'] = value;
}catch(ex){}
	}
	
	// Sort the bank array
	banks = mergesort(banks, type);	
	
	// Sort the rows in the table in according to the newly sorted array
	for(var i=0; i < banks.length;i++){
		var row_info = document.getElementById("ratinglist_info_" + banks[i]['regn']);
		var row_desc = document.getElementById("ratinglist_descrow_" + banks[i]['regn']);
		
		table.appendChild(row_info);
		table.appendChild(row_desc);
	}
}

/* Merge Sort algorithm implementation
	a		- array to sort
	type	- type of comparison to do between elements (eg COMP_TYPE_STRING)
*/
function mergesort(a, type) {
	if(a.length > 1) {
		var length = a.length;
		var midpoint = Math.floor( ( a.length - 1 ) / 2 ) + 1;
		var left = mergesort(a.slice(0, midpoint), type);
		var right = mergesort(a.slice(midpoint), type);
		
		var leftl = left.length;
		var rightl = right.length;
		
		var res = new Array();

		var op;
		if(sort_order == SORT_ORDER_DESC) {
			op = COMP_OP_GT;
		} else {
			op = COMP_OP_LT;
		}
	
		while(left.length > 0) {
			if(right.length > 0 && compare(left[0], right[0], op, type)) {
				res.push(right.shift());
			} else {
				res.push(left.shift());
			}
		}
		while(right.length > 0) {
			res.push(right.shift());
		}

		return res;
	} else {
		var res = a;
		return res;
	}
}

/* compare 2 values depending on the comparison type

	left	- left Row object
	right	- right Row object
	op		- comparison operation (eg COMP_OP_LT)
	type	- comparison type (eg COMP_TYPE_RATING)
	
	returns boolean
*/
function compare( left, right, op, type) {
	// standard comaprison for numeric/string values
	if(type == COMP_TYPE_NUMERIC || type == COMP_TYPE_STRING) {
		if(op == COMP_OP_EQ) {
			if( left['value'] == right['value'] ) {
				return true;
			} else {
				return false;
			}
		} else if(op == COMP_OP_LT) {
			if( left['value'] < right['value'] ) {
				return true;
			} else {
				return false;
			}
		} else if(op == COMP_OP_GT) {
			if( left['value'] > right['value'] ) {
				return true;
			} else {
				return false;
			}
		}
	}
	
	else if(type == COMP_TYPE_DATE)
	{
	   //ß ÈÄÈÎÒ! ÓÁÅÉÒÅ ÌÅÍß, ÊÒÎ-ÍÈÁÓÄÜ!
	   var ld = left['value'].split(".");
	   var rd = right['value'].split(".");
	   var leftd = new Date(ld[2],ld[1]-1,ld[0]);
	   var rightd = new Date(rd[2],rd[1]-1,rd[0]);
	   
	   if(op == COMP_OP_EQ)
	   {
	        if (leftd == rightd){
	    	    return true;
		}
		
		return false;
	   }
	   if(op == COMP_OP_LT)
	   {
	        if (leftd < rightd){
	    	    return true;
		}
		
		return false;
	   }
	   if(op == COMP_OP_GT)
	   {
	        if (leftd > rightd){
	    	    return true;
		}
		
		return false;
	   }

	}
	
	// comparison for ratings
	else if(type == COMP_TYPE_RATING) {
		var rightindex;
		var leftindex;
		for(i = 0; i < RATINGS.length; i++){
			if(RATINGS[i] == right['value']) {
				rightindex = i;
			}
			if(RATINGS[i] == left['value']) {
				leftindex = i;
			}				
		}

		if(op == COMP_OP_EQ) {
			if(rightindex == leftindex) {
				return true;
			} else {
				return false;
			}
		} else if(op == COMP_OP_LT) {
			if(rightindex > leftindex) {
				return true;
			} else {
				return false;
			}
		} else if(op == COMP_OP_GT) {
			if(rightindex < leftindex) {
				return true;
			} else {
				return false;
			}
		}
	}
}

// constructor for Bank object
function Bank(regn){
	this.regn = regn;
}


// changes colour of specified 'element' to 'colour'
function changeColour(element, colour) {
        element.style.color = colour;
}

// changes background of specified 'target' to 'colour'
function changeBG(element, colour) {
        element.style.backgroundColor = colour;
}

// follows the 1st child link in given parent
function followChildLink(parent) {
        child = parent.getElementsByTagName('a').item(0);
        document.location = child.getAttribute("href");
}

// init function. This the global init function that is called when
// a document is loaded. It calls different function depending on the
// document loaded
function init() {
        // is this the list of ratings page
        if(document.getElementById("ratinglist")) {
                sort(1);
        }
}

