/*<script language="javascript1.1" type="text/javascript" src="js/jquery-1.3.2.min.js">
<script language="javascript1.1" type="text/javascript" src="js/jquery.cluetip.js">
<script language="javascript1.1" type="text/javascript" src="js/jquery.hoverIntent.minified.js">
*/
// include formatdate.js for all

// Not even sure what this is.  :)
function toggleSelectedTD(selected) {
	var nodes = getElementsByClass( "depressed", document, "td" );
	for( var key in nodes ) {
		var btn = nodes[key];
		// LJR -- this needs to be much smarter -- must remove one class from string of classes.
		btn.className = "";
	}
	document.getElementById(selected).className = "depressed";
	
}		


// Do we use this at all anymore?
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if (node == null)
		node = document;
	if (tag == null)
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if (pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function isMobile() {
	if ( $("table#mobile_frame").length > 0 )
		return true;
	return false;
}

function applyZebraStriping() {
	$("table.zebra tr:nth-child(odd)").addClass("odd");
	$("table.zebra tr:nth-child(even)").removeClass("odd");
}

function fixTime() {
	$('span.time').add( '.forumtime' ).each( function() {
		var ms = this.innerHTML;
		if( ms.indexOf( ":" ) == -1 ) {
			if( ms == "000" ) {
				this.innerHTML = "---";
			} else {
				var newdate = new Date();
				newdate.setTime(ms);
				var datestring = formatDate( newdate, "h:mma on EE, MMM d, y" );
				this.innerHTML = datestring;
			}
		}
	});
}

function pastWeeksLoadFunctions() {
//	alert( "striping" );
	applyZebraStriping();
}

function schedule() {
	$("select#sort_week").change(function() {
		var week = this.options[this.selectedIndex].value;
		$("div#result").load( "ajax_schedule.php", { week : week }, applyZebraStriping );
	});
	$("select#sort_team").change(function() {
		var team = this.options[this.selectedIndex].value;
		$("div#result").load( "ajax_schedule.php", { team : team }, applyZebraStriping );
	});
}
	
function pastWeeks() {
	$("div#weekselect select#week").change(function() {
		var week = this.options[this.selectedIndex].value;
		$("div#result").load( "ajax_pastweek.php", { week : week }, pastWeeksLoadFunctions );
	});
}

$( function() {
	applyZebraStriping();
	fixTime();
	pastWeeks();
	schedule();
});




// Roster selection stuff.  Will need modification for mobile use, but should
// be similar enough to put in "main".

function initRosterSelect($pickWeek) {
	var action_is_post = false;
	var page_is_dirty = false;
	var $week = $pickWeek;
	$('#rosterform').submit(function () {
	    action_is_post = true;
	});

	$('td.roster_player').each( function() { 
		var id = this.getAttribute( "playerid" );
		var position = this.id.substr( 0, this.id.length - 5 );
		var inputName = position + '_input';
		$('input#' + inputName).attr('value', id);
		});
	window.onbeforeunload = function() {
		if( this.page_is_dirty == true && action_is_post == false ) {
			return "You have made changes to your week " + $week + " roster, but haven't saved them.  In order to do so, hit 'Cancel' now.";
		}
	}
	$('#dialog').dialog( {autoOpen: false} );  

	/*** for pc version only ***/
	$("#pool").tabs();
	$('#radioweek').click(function() {
		$('table.position_select_table td.season').hide();
		$('table.position_select_table td.week').show();
		});
	$('#radioseason').click(function() {
		$('table.position_select_table td.week').hide();
		$('table.position_select_table td.season').show();
		});
	$('button.playerlistname').click(function() {
			select(this);
		  }
		);
	sortables_init();

	/*** for mobile version only ***/
	$('select#mobile_select_position').change(function() {
		var optionName = $('select#mobile_select_position :selected').attr("name");
		var regex = /(\w+)_select/i;
		var matches = regex.exec( optionName );
		if( matches != null ) {
			posSelector = 'div#' + matches[1];
			$('.mobile_pool').hide();
			$('#' + matches[1] ).show();
		}		
		});

	$('table.position_select_table td.week').add('div#qb_pool').show();
	$('button').focus(
		function() {
			$(this).addClass("ui-state-focus");
		  }
		);
	$('button').blur(
		function() {
			$(this).removeClass("ui-state-focus");
		  }
		);
}

function putPlayerInSlot( element, name, abbrevname, team, id ) {
	page_is_dirty = true;
//		$('#selection_roster tr').css("background", "#c00" ); 
	if( !isMobile() ) {
		abbrevname = "<a id=\"roster_" + id + "\" class=\"playerlink\" href=\"main.php?do=playercard&amp;player=" + id + "\">" + abbrevname + "</a>";
	}

	$(element).css("background", "#c00" ); 
	element.innerHTML = abbrevname + "<br/>" + "(" + team + ")";
	element.setAttribute("playerid", id );
	element.setAttribute("playername", name );
	// get the slot's id and transfer its value to the corresponding input field
	var regex = /(\w+)_slot/i;
	var matches = regex.exec( element.id );
	if( matches != null ) {
		var inputField = "#" + matches[1] + "_input";
//			alert( inputField );
		$(inputField).attr('value', id);
//			alert( $(inputField).attr('value' ));
	} else {
	}
	// Check to see if it's okay to enable the save button
	if( $('table#selection_roster td').filter( function() { return this.getAttribute("playerid") != null; } ).length == 7 ) {
		$('#rosterform input#save').removeAttr('disabled');
	}
	if( !isMobile()) {
		$("#roster_" + id).cluetip( 
			{	
				activation: 'click',
				width: 430, 
				sticky: true, 
				arrows: true,
				cursor: 'pointer',
				attribute : 'href',
				cluetipClass : 'cdffl',
				mouseOutClose : true,
				closeText : '',
				showTitle: false
	//			,
	//			hoverIntent: {
	//				sensitivity:  3,
	//				interval:     250,
	//				timeout:      750    
	//			}
			} 
		);
	}
	// Finally, scroll
	var scrollOffset = $('#selection_roster').offset().top;
	if ( $("table#mobile_frame").length > 0 ) scrollOffset = $('body').offset().top;
	$('html,body').animate({scrollTop: scrollOffset }, 1000);

}

function select(pbutton) {
	var regex = /(\w+)_pool/i;

	var playerName = pbutton.innerHTML;
	var abbrevName = pbutton.parentNode.parentNode.getAttribute("shortname");
	var playerId = pbutton.getAttribute("playerid"); // no good; need to clean it up.
	var playerTeam = pbutton.parentNode.nextSibling.innerHTML;

	// If player is on a bye week for the roster week, abort
	if( pbutton.parentNode.nextSibling.nextSibling.innerHTML == 'BYE' ) {

		$("#dialog").html( playerName + " is on a bye week this week.  Idiot." )
			.dialog( 
				{ 	
//					buttons: { "Ok": function() { $(this).dialog("close"); } } ,
					modal: true,
					width: 250, 
					height: 250
				}
			);
		var buttons = {};
		buttons["Ok"] = function() { $(this).dialog("close"); };
		$("#dialog").dialog("option", "buttons", buttons );
		$("#dialog").dialog("option", "title", "Selection Error" );
		$("#dialog").dialog("option", "modal", true );
		if ( isMobile() ) $("#dialog").dialog("option", "position", [10,10] );
		pbutton.blur();
		$("#dialog").dialog("open");
		//ljr
		return;
	}
	// If this player's already in the roster selections, abort
	if( $('table#selection_roster td[playerid=' + playerId + ']').length > 0 ) {
		$("#dialog").html( playerName + " is already on your roster!" )
			.dialog( 
				{ 	
					modal: true, 
					width: 250, 
					height: 250
				}
			);
		var buttons = {};
		buttons["Ok"] = function() { $(this).dialog("close"); };
		$("#dialog").dialog("option", "buttons", buttons );
//		$("#dialog").dialog("option", "buttons", { "Ok": function() { $(this).dialog("close"); } );
		$("#dialog").dialog("option", "title", "Selection Error" );
		$("#dialog").dialog("option", "modal", true );
		if ( isMobile() ) $("#dialog").dialog("option", "position", [10,10] );
		pbutton.blur();
		$("#dialog").dialog("open");
		return;
	}

	// Determine position of player clicked
	var className = pbutton.parentNode.parentNode.className;
	var matches = regex.exec( className );
	var position = null;
	if( matches != null ) {
		position = matches[1];
		var slots  = $('table#selection_roster td.' + position + '_roster');

		// If slot 0 empty, no sweat.
		if( slots[0].getAttribute("playerid") == null || slots[0].getAttribute("playerid") == '' ) {
			putPlayerInSlot( slots[0], playerName, abbrevName, playerTeam, playerId );
			pbutton.blur();
		} else {
			// if only one slot for this position, also no sweat
			if( slots.length == 1 ) {
				putPlayerInSlot( slots[0], playerName, abbrevName, playerTeam, playerId );
				pbutton.blur();
			} else {
				// We need further input!
				var button1text = "Replace " + slots[0].getAttribute("playername");
				var button2text = "Put him in the empty slot";
				if( slots[1].getAttribute("playerid") != null && slots[1].getAttribute("playerid") != '' ) {
					button2text = "Replace " + slots[1].getAttribute("playername");
				}
				var buttons = {};
				buttons[button1text] = function() { putPlayerInSlot( slots[0], playerName, abbrevName, playerTeam, playerId ); $(this).dialog("close"); };
				buttons[button2text] = function() { putPlayerInSlot( slots[1], playerName, abbrevName, playerTeam, playerId ); $(this).dialog("close"); };
				buttons["Cancel"] = function() { $(this).dialog("close"); };
				$("#dialog").html("What would you like to do with " + playerName + "?" )
					.dialog( 
						{ 	modal: true, 
							width: 250, 
							height: 250
						}
					);
				$("#dialog").dialog("option", "buttons", buttons );
				$("#dialog").dialog("option", "title", "Selection Input" );
				$("#dialog").dialog("option", "modal", true );
				if ( $("table#mobile_frame").length > 0 ) $("#dialog").dialog("option", "position", [10,10]);
				pbutton.blur();
				$("#dialog").dialog("open");
				//ljr
			}
		}
	} else {
	}
}


// Date functionality
function resolveDates() {
	var nodes = getElementsByClass( "time", document, "span" );
	for( var datenode in nodes ) {
		var ms = nodes[datenode].innerHTML;
		if( ms == "000" ) {
			nodes[datenode].innerHTML = "---";
		} else {
			var newdate = new Date();
			newdate.setTime(ms);
			var datestring = formatDate( newdate, "h:mma on EE, MMM d, y" );
			nodes[datenode].innerHTML = datestring;
		}
	}
	nodes = getElementsByClass( "forumtime", document, "td" );
	for( var datenode in nodes ) {
		var ms = nodes[datenode].innerHTML;
		if( ms == "000" ) {
			nodes[datenode].innerHTML = "---";
		} else {
			var newdate = new Date();
			newdate.setTime(ms);
			var datestring = formatDate( newdate, "M/d &#97;&#116;  h:mm:ssa" );
			nodes[datenode].innerHTML = datestring;
		}
	}
	nodes = getElementsByClass( "forumtime", document, "span" );
	for( var datenode in nodes ) {
		var ms = nodes[datenode].innerHTML;
		if( ms == "000" ) {
			nodes[datenode].innerHTML = "---";
		} else {
			var newdate = new Date();
			newdate.setTime(ms);
			var datestring = formatDate( newdate, "M/d &#97;&#116;  h:mm:ssa" );
			nodes[datenode].innerHTML = datestring;
		}
	}
}

// Forum quoting functionality
function quoteMe(link) {
	$ownerName = link.parentNode.parentNode.childNodes[0].childNodes[0].innerHTML;
	$date = link.parentNode.parentNode.childNodes[0].childNodes[2].innerHTML;
	$text = link.parentNode.parentNode.childNodes[1].innerHTML;
	$ta = document.getElementById("forumTextArea");
	$ta.focus();
	$ta.value = 
		"<blockquote>On " + $date + ", " + $ownerName + " wrote:\n" + $text + "</blockquote>\n";
}

