// Simplified version of picks.js


function filterTable(o) {
	this.filtersTable = $i( o.namespace + 'filters' );
	this.tableBody = $i( o.namespace + 'content' );
	this.timeRange = $i( o.namespace + 'range' );
	this.models = $i( o.namespace + 'models' );
	this.modelDesc = $i( o.namespace + 'model_desc' );
	this.o = o;
	
	this.filters = [];
	this.filterSets = {};
	this.linkBacks = {};
	this.postVars = o.postVars ? o.postVars : {};
	this.countdowns = {};
	this.countdownInt;
	
	var self = this;
	this.aRef = new simpleAjax( {type:'ctn', url:'/ajax/league/picks_controller.php?type=apply_filter', callback:function(r){self.refreshCallback(self,r);}, ctn:this.tableBody} );
	this.aUp = new simpleAjax( {type:'json', url:'/ajax/league/picks_controller.php?type=refresh_column', callback:function(r){self.updateColumnsCallback(self,r);}} );
}
filterTable.prototype = {
	
	init : function() {
		var self = this;		
			
			
		// -- Add model events (if they exist)
		
		if (this.models)
		{			
			this.models.onchange = function() { self.modelChanged(); }		
			this.updateModelDesc();
		}
		
		
		// -- Add events to time controls
		
		this.timeRange.onchange = function() { self.timeChanged(); }
		
		
		
						
		/*
		Select dropdowns should have compare attribute:
			The name is the attribute to check on each table row
			can be:
			- name of attribute
			- json array of attributes: [atr1,atr2,atr2]
		
		Select dropdown Options should have value attribute:
			The value is matched to the 'compare' attribute on each row
			can be:
			- single value
			- json array of values: [1,2,3]		
		*/
		// -- Find all filter fields, apply events
	
		var flags, flagSet, valueElement;
		var filters = this.filtersTable.getElementsByTagName('select');

		for(var i=0; i<filters.length; i++) 
		{
			
			var filter = filters[i];
			var compare = filter.getAttribute('compare');
			
			this.addFilter(filter, compare);
				
		}
		
		
		// Link lists
		
		var filters = getElementsByClassName(this.filtersTable, 'ul', 'tr_link_list');
		var links;
		
		for(var i=0; i<filters.length; i++) 
		{				
			var filter = filters[i];
			var compare = filter.getAttribute('compare');
			
			this.addFilter(filter, compare, 'link_list');
		
			// add onclicks to each link
			links = filter.getElementsByTagName('a');
			for(var j=0; j<links.length; j++)
			{
				links[j].setAttribute('index', j);
				links[j].onclick = function(e, obj, noUpdate) 
				{ 
					obj = obj ? obj : this;
					var selectedIndex = obj.parentNode.parentNode.getAttribute('selectedIndex');
					if (selectedIndex >= 0 && selectedIndex != null)
						Removeclass(obj.parentNode.parentNode.getElementsByTagName('a')[selectedIndex].parentNode, 'tr_selected');
					
					Addclass(obj.parentNode, 'tr_selected');
					obj.parentNode.parentNode.setAttribute('selectedIndex', obj.getAttribute('index'));					
					
					if (!noUpdate)
						self.filterChanged();
				}
				
				// preselect
				if (links[j].parentNode.className.match('tr_selected'))
					links[j].onclick(null, links[j], true);
			}			
		}
		
		
		
		//
		
		if (this.o.autoUpdate) {
			var self = this;
			this.autoUpdateInt = setInterval(function() 
			{ 
				
				if (!self.autoUpdateCount) { self.autoUpdateCount = 0; }
				self.autoUpdateCount++;
				if (self.autoUpdateCount < self.o.autoUpdateMax) {
					self.refresh(self,true);
				} else {
					
					// Check if refresh row is already there
					
					var rowExists = self.tableBody.parentNode.getElementsByTagName('div');
					if (!rowExists[0] || !rowExists[0].className.match('tr_info_row')) {							
						
						// Add refresh row
						var refreshRow = document.createElement('div');
						refreshRow.className = 'tr_info_row';
						refreshRow.innerHTML = '<a onclick="'+self.o.variableName+'.refresh()">Refresh</a>';
						self.tableBody.parentNode.insertBefore(refreshRow, self.tableBody);
						
					}
					
				}
			}, this.o.autoUpdate);
		}
		
		this.refresh();
		
	},
	
	addFilter : function(filter, compare, type)
	{
		var self = this;
		var flags, flagSet, valueElement;
		
		if (compare)
		{
			
			// Determine flags to check against (value or array)
			flagSet = compare;
			if (flagSet.match(/\[/)) {
				flags = eval(flagSet);
			} else {
				flags = [flagSet];
			}
							
			// add filter
			this.filters.push(
				{
					self: filter,
					flagsToCheck: flags, //probably should add an option to allow AND or OR setting, default to OR for now					
					type: type
				}
			);
			
			// Add event
			if (!type)
				filter.onchange = function() { self.filterChanged(); }
			
		}
	},
	
	/* --- */
	
	filter : function() {
		
		var rows, i, f, c, v, valueSet, values, filters, flags;
		var show, matched;
		var value, filter, index;
		
		// Make a filter array with the pre-extracted values only for checked items to speed up things inside the loop
		filters = [];
		for(f in this.filters) {
					
			filter = this.filters[f];
			
			// get value
			if (filter.type == 'link_list')
			{
				index = filter.self.getAttribute('selectedIndex');
				if (index)
				{
					value = filter.self.getElementsByTagName('a')[index].getAttribute('value');	
				}
				else { value = 'all'; }
			}
			else {	
				value = filter.self.value; 
			}
			
			if (value != 'all') 
			{				
			
				// Is value a single value or list?				
				if (value.match(/\[/)) {
					values = eval(value);
				} else {
					values = [value];
				}
				
				// Add value to filters we will use
				filters.push( {
					filter:filter,
					values:values
					} );
				
			}
			
		}	
		
		// run through the rows and drop any that don't match all of the filters
		showCount = 0;
		zebraN = 0;
		rows = this.tableBody.getElementsByTagName('TR');
		isIE = navigator.appName == 'Microsoft Internet Explorer';
		for(var i=0; i<rows.length; i++) {
			if (rows[i].tagName == 'TR' && rows[i].parentNode.tagName != 'THEAD') {
				
				// run through filters and check row
				if (filters.length == 0) 
				{
					show = true; // Nothing to filter
				}
				
				else 
				{
					show = true;
					for(f in filters) 
					{ 
						// compare: has to match all
						matched = false;
						flags = filters[f].filter.flagsToCheck;
						values = filters[f].values;
						
						for(c in flags) 
						{ 
							// compare: match at least one					
							for(v in values) 
							{ 
								// compare: match at least one
								if (values[v] == 0 || rows[i].getAttribute(flags[c]) == values[v]) {
									matched = true;
									break; break; // flag matches at least one of the values, move on
								}
							}
						}
						if (!matched) { 
							show = false;
							break; // the rows flag didn't match any allowed values, so move on to the next row
						}	
					}
				}
				
				rows[i].style.display = show ? ( isIE ? "block" : "table-row") : 'none';			
				if (show) 
				{
					showCount++;
					
					// redrawing alt shading
					if ( zebraN%2 != 0) {
						Addclass( rows[i] , 'tr_alt' );
					} else {
						Removeclass( rows[i] , 'tr_alt' );
					}
					zebraN++;
				}
				
			}
		}
		
		// TODO
		if (!this.footerMsg || !this.footerMsg.parentNode) {
			this.footerMsg = createNodeN('div', {align:'center','class':'no_match'});
			this.footerMsg.innerHTML = 'No games match';
			this.tableBody.parentNode.insertBefore(this.footerMsg, this.tableBody.nextSibling);
		}
		this.footerMsg.style.display = showCount ? 'none' : 'block';
	},
	
	filterChanged : function() 
	{				
		this.filter();		
	},
	
	/* --- */
	
	timeChanged : function() 
	{
		this.refresh();		
	},
	
	// -- //
	
	modelChanged : function()
	{		
		this.updateModelDesc();
		this.refresh();		
	},
	
	updateModelDesc : function()
	{
		this.modelDesc.innerHTML = this.models.options[this.models.selectedIndex].getAttribute('desc');		
	},
	
	/* --- */
	
	refresh : function(noSpinner) 
	{
		if (this.models)
			this.postVars.model = this.models.value;
		this.postVars.time_range = this.timeRange.value;
		
		clearInterval(this.countdownInt);
		this.aRef.spinner = !noSpinner;
		this.aRef.send( this.postVars );	
	},
	
	refreshCallback : function(self, r) {		
		self.refreshTable();
	},
	
	refreshTable : function() {
		try {
		
		var self = this;
		
		// Set up sorting
		this.sortTable = new sortableTable2( this.tableBody.id, {
			eventSorted: function(sortTable){ 
				self.sortedIndex = sortTable.currentColumn;
				self.sortedDir = sortTable.sortDir;
			},
			defaultSortIndex : this.sortedIndex ? this.sortedIndex : 0,
			startDir : this.sortedDir ? this.sortedDir : false
		} );
		
		
		// Filter results
		this.filter();
		
		
		// Start countdown timers
		var c=0;
		this.countdowns = {};
		countCells = getElementsByClassName(this.tableBody, 'TD', 'tr_countdown');
		for(var i=0; i<countCells.length; i++) {
			if (countCells[i].tagName == 'TD') {
				this.countdowns[i] = {
					date : new Date(),
					cell : countCells[i]
				};
				this.countdowns[i].date.setTime( countCells[i].getAttribute('countDown')  * 1000);
				c++;
			}
		}
		if (c > 0) {
			var self = this;
			this.updateCountdowns(this);
			this.countdownInt = setInterval(function() { self.updateCountdowns(self); }, 30000); //only updates every 30 seconds since we aren't tracking seconds
		}
		
		// setup tooltips
		setupTooltips('tabs_filters_content');
		
		} catch(e) { alert(e); }
		
	},
	
	// -- //
	
	updateCountdowns : function(obj) {
		var now = new Date();	
		
		for(var i in obj.countdowns) {
			if (obj.countdowns[i]) {
				
				date = obj.countdowns[i].date;
				cell = obj.countdowns[i].cell;
				
				var dif = (date.getTime() - now.getTime() ) /1000;
				
				if (dif < 0) { cell.innerHTML = ''; }
				
				var d = Math.floor( dif /60/60/24 );
				var hr = Math.floor( dif /60/60 ) - (d*24);
				var mn = Math.floor( dif /60 ) - (hr*60);
				var s = Math.floor( dif ) - (hr*60*60) - (mn*60);
				
				if (mn == 0 && hr>0) { mn = 60; hr--; }
				
				cell.innerHTML = 'Kickoff in<br>';
				if ( hr > 0 || d > 0 ) { 
					
					if (d > 24) cell.innerHTML += d + 'day' + (d==1?'':'s') + ' ';					
					if (hr > 0) cell.innerHTML += hr + 'hr' + (hr==1?'':'s') + ' ';
					if (d < 24 && m > 0) cell.innerHTML += mn + 'min' + (mn==1?'':'s');
				}
								
			}
		}		
	}
	
}

if (navigator.userAgent.match(/firefox/i)) { document.body.className += ' firefox'; }