function removeRound(id) {
	// first, delete the node
	deletedNode = document.getElementById(id);
	deletedNode.parentNode.removeChild(deletedNode);
	// second, hide the delete button if only one node exists
	(document.getElementById("round_table").childNodes[0].childNodes.length == 2) ? setStyleByClass("td","action_cell","visibility","hidden") : setStyleByClass("td","action_cell","visibility","visible") ;
};


function addRound(disableImmediateInput) {
	// if a round is being "chosen", stop that process before a new round is created
	if (globalCourse['cell']) hideCourseChooser();
	
	rcount++; // advance global round count
	var round_table_section = document.getElementById("round_table").childNodes[0];
	var new_round = round_table_section.lastChild.cloneNode(true);	
	
	// change names of inputs to avoid conflicts
	new_round.id = 'round_'+rcount;
	for (var x = 0; x < new_round.childNodes.length; x++) {
		var cell = new_round.childNodes[x];
		for (var y = 0; y < cell.childNodes.length; y++) {
			if (cell.childNodes[y].name) // replace names
				cell.childNodes[y].name = cell.childNodes[y].name.replace(/\d+/, rcount);
			if (cell.childNodes[y].id) // replace ids
				cell.childNodes[y].id = cell.childNodes[y].id.replace(/\d+/, rcount);
			if (cell.childNodes[y].src && cell.childNodes[y].src.match('/images/cal.png')) // replace onclick of calendar img
				cell.childNodes[y].onclick = function() {YAHOO.example.calendar.exposeCal(this, {month:document.getElementById('tournament_round_'+rcount+'_month'), day: document.getElementById('tournament_round_'+rcount+'_day'), year: document.getElementById('tournament_round_'+rcount+'_year')});};
		}
	}
	round_table_section.appendChild(new_round);
	if (!disableImmediateInput) showCourseChooser('course_link_'+rcount); // show the input box immediately
	setStyleByClass("td","action_cell","visibility","visible");
}


function setStyleByClass(t,c,p,v){
	var ie = (document.all) ? true : false;
	var elements;
	
	if (t == '*') {
		// '*' not supported by IE/Win 5.5 and below
		elements = (ie) ? document.all : document.getElementsByTagName('*');
	} else {
		elements = document.getElementsByTagName(t);
	}
	for (var i = 0; i < elements.length; i++){
		var node = elements.item(i);
		for(var j = 0; j < node.attributes.length; j++) {
			if(node.attributes.item(j).nodeName == 'class') {
				if(node.attributes.item(j).nodeValue == c) {
					eval('node.style.' + p + " = '" +v + "'");
				}
			}
		}
	}
}


/* FAVORITES */
function toggle_fav() {
	var fav_link = document.getElementById('fav_link');
	startThrob(fav_link); // animate

	var callback = { 
		success: function(o) { // change visible link
			throbber.element.className = (throbber.element.className == 'bright_star') ? 'dark_star' : 'bright_star' ;
			document.getElementById('course_star').style.visibility = (throbber.element.className == 'bright_star') ? 'visible' : 'hidden' ;
			if (MSIE) throbber.element.innerHTML = (throbber.element.innerText == 'Remove from My Favorites') ? 'Add to My Favorites' : 'Remove from My Favorites' ;
			else throbber.element.innerHTML = (throbber.element.text == 'Remove from My Favorites') ? 'Add to My Favorites' : 'Remove from My Favorites' ;
			throbber.element.title = (throbber.element.className == 'bright_star') ? 'Remove this course from My Favorite Golf Courses' : 'Add this course to My Favorite Golf Courses' ;
			endThrob( function() {
				throbber.element.onmouseover = function() {this.style.backgroundColor = '#ccffcc'};
				throbber.element.onmouseout = function() {this.style.backgroundColor = '#f0f0f0'};
			} );
		},
		failure: function(o) {
			throbber.animation.onComplete.unsubscribeAll();
			throbber.animation.stop();
			throbber.element.style.backgroundColor = '#f0f0f0';
			alert('Sorry, this favorite request has failed.  Please try again and if this persists, contact us using the link at the bottom of the page and report this bug.');
		},
		argument: []
	};

	var transaction = YAHOO.util.Connect.asyncRequest('POST', document.location.href.replace('/view/', '/toggle_fav/'), callback, null); 
}

function startThrob(el) {
	throbber = { element: el, animation: null };
	_throbUP(el);
}


function endThrob(cleanupFunction) {
	throbber.animation.onComplete.unsubscribeAll();
	throbber.animation.stop();
	_pulse(cleanupFunction);
}


function _throbUP() {
	throbber.animation = new YAHOO.util.ColorAnim(throbber.element, {backgroundColor: { to: '#ccff00' } }, .7, YAHOO.util.Easing.easeOutStrong);
	throbber.animation.onComplete.subscribe(_throbDOWN); 
	throbber.animation.animate();
}


function _throbDOWN() {
	throbber.animation = new YAHOO.util.ColorAnim(throbber.element, {backgroundColor: { to: '#f0f0f0' } }, .3, YAHOO.util.Easing.easeOut);
	throbber.animation.onComplete.subscribe(_throbUP); 
	throbber.animation.animate();
}


function _pulse(cleanupFunction) {
	var pulse = new YAHOO.util.ColorAnim(throbber.element, {backgroundColor: { from: '#ffff99', to: '#f0f0f0' } }, 2.5, YAHOO.util.Easing.backIn);
	if (cleanupFunction) pulse.onComplete.subscribe(cleanupFunction); 
	pulse.animate();
}


/* YUI SCRIPTS */
// YAHOO.namespace("choosers.container");
var oAutoComp, oACDS, aEscape, aReturn;
var Safari = (navigator.userAgent.match('Safari')) ? true : false ;
var MSIE = (navigator.userAgent.match('MSIE')) ? true : false ;
var globalCourse = {iteration: null, name: null, id: null, cell: null};
var throbber = null;

function showCourseChooser(link_id) {
	// if a round is being "chosen", stop that process before a new round is created
	if (globalCourse['cell']) hideCourseChooser();
	
	globalCourse['iteration'] = link_id.replace(/[^\d]./g, '');
	globalCourse['id'] = document.getElementById('tournament_round_'+globalCourse['iteration']+'_course_id').value;
	globalCourse['cell'] = document.getElementById(link_id).parentNode;
	globalCourse['name'] = (MSIE) ? document.getElementById(link_id).innerText : document.getElementById(link_id).text;
	
	// create data object if it doesn't already exist
	if (!oACDS) {
		oACDS = new YAHOO.widget.DS_XHR("/json/courses", ["courses","name","id","city","state","nation"]); 
		oACDS.queryMatchContains = true;
		oACDS.maxCacheEntries = 0; // this produces weird results because city is included in search
		oACDS.queryMatchSubset = true;
	}
	
	// create input
	var h = ['<input type="hidden" id="tournament_round_'+globalCourse['iteration']+'_course_id" name="tournament_round['+globalCourse['iteration']+'][course_id]" value="'+globalCourse['id']+'">'];
	//h.push('<form action="http://search.yahoo.com/search" onsubmit="return false;">');
	h.push('<div id="myAutocomplete">');
		h.push('<input id="searchinput" type="text" onfocus="showHelp(document.getElementById(\'searchinput\'), \'Enter a Golf Course, City, or both and we will do our best to find it\')">');
		h.push('<div id="searchcontainer"></div>');
	h.push('</div>')
	h.push(' <a href="javascript:void(0);" title="Close the Golf Course Chooser" class="chooser_cancel" onclick="hideCourseChooser();">x</a>');
	//h.push('</form>');
	globalCourse['cell'].innerHTML = h.join('');
	
	// autocomplete
	oAutoComp = new YAHOO.widget.AutoComplete("searchinput","searchcontainer", oACDS); 
	oAutoComp.alwaysShowContainer = false;
	oAutoComp.forceSelection = true;
	oAutoComp.minQueryLength = 3;
	oAutoComp.maxResultsDisplayed = 12;
	oAutoComp.formatResult = function(oResultItem, sQuery) {
		return oResultItem[0] + " ("+oResultItem[2]+", "+oResultItem[3]+", "+oResultItem[4]+")"; 
	};
	oAutoComp.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults) { 
		var pos = YAHOO.util.Dom.getXY(oTextbox); 
		pos[1] += YAHOO.util.Dom.get(oTextbox).offsetHeight + 2; 
		YAHOO.util.Dom.setXY(oContainer,pos); 
		return true; 
	};
	oAutoComp.itemSelectEvent.subscribe(itemSelectHandler);
	setTimeout("document.getElementById('searchinput').focus()", 10);
	
	// enable key listeners - but not for the retarded IE
	if (!MSIE) {
		aEscape = new YAHOO.util.KeyListener("searchinput", {keys:27}, hideCourseChooser); // ESC
		aEscape.enable();
	
		if (!Safari) {
			aReturn = new YAHOO.util.KeyListener("searchinput", {keys:13}, hideCourseChooser); // ENTER
			aReturn.enable();
		}
	}
}


function hideCourseChooser() {
	if (globalCourse['cell']) {
		globalCourse['cell'].innerHTML = '<a href="javascript:void(0)" class="popin" title="Use the Golf Course Chooser to find a Golf Course" id="course_link_'+globalCourse['iteration']+'" onclick="showCourseChooser(this.id);">'+globalCourse['name']+'</a><input type="hidden" id="tournament_round_'+globalCourse['iteration']+'_course_id" name="tournament_round['+globalCourse['iteration']+'][course_id]" value="'+globalCourse['id']+'">';
		globalCourse = {iteration: null, name: null, id: null, cell: null};
		
		// disable key generators
		if (!MSIE) aEscape.disable();
		if (!Safari && !MSIE) aReturn.disable();
		hideHelp();
	}
}


// handle an auto-selection event
var itemSelectHandler = function(sType, aArgs) {
	globalCourse['name'] = aArgs[2][0];
	globalCourse['id'] = aArgs[2][1];
	setTimeout("hideCourseChooser()", 10);
};


/* Help */

function showHelp(parent, text) {
	// create help node, if it doesn't already exist
	if (!document.getElementById('help')) {
		hNode = document.createElement("div");
		hNode.id = 'help';
		document.body.appendChild(hNode);
		
		dNode = document.createElement("img");
		dNode.id = 'darktip';
		dNode.src = '/images/darktip.png';
		document.body.appendChild(dNode);
	}
	
	var help = document.getElementById('help');
	var darktip = document.getElementById('darktip');
	help.innerHTML = text;
	
	// position
	help.style.left='-1000px';help.style.top='-1000px';
	help.style.display = 'block';
	
	var top = YAHOO.util.Dom.getY(parent) - help.offsetHeight - ((MSIE)?12:9)
	var left = YAHOO.util.Dom.getX(parent) - 5;
	help.style.left = left + 'px';
	help.style.top = top + 'px';
	darktip.style.left = left + Math.floor(help.offsetWidth/2) - 8 + 'px';
	darktip.style.top = top + help.offsetHeight - 1 + 'px';	
	darktip.style.display = 'block';
}

function hideHelp() {
	document.getElementById('darktip').style.display = 'none';
	document.getElementById('help').style.display = 'none';
}


/* Calendar */
if (document.getElementById('calContainer')) {
	YAHOO.namespace("example.calendar");

	YAHOO.example.calendar.exposeCal = function(icon, fields) {
		var calContainer = document.getElementById('calContainer');
		YAHOO.example.calendar.cal.fields = fields;
		// position calendar
		calContainer.style.left = YAHOO.util.Dom.getX(icon) + 'px';
		calContainer.style.top = YAHOO.util.Dom.getY(icon) + 'px';

		YAHOO.example.calendar.updateCal();
		YAHOO.example.calendar.cal.show();
	}

	YAHOO.example.calendar.updateCal = function() {
		var selMonth = YAHOO.example.calendar.cal.fields.month;
		var selDay = YAHOO.example.calendar.cal.fields.day; 
		var selYear = YAHOO.example.calendar.cal.fields.year; 

		var month = parseInt(selMonth.options[selMonth.selectedIndex].value);
		var day = parseInt(selDay.options[selDay.selectedIndex].value);
		var year = parseInt(selYear.options[selYear.selectedIndex].value);

		if (! isNaN(month) && ! isNaN(day) && ! isNaN(year)) {
			var date = month + "/" + day + "/" + year;
			YAHOO.example.calendar.cal.select(date);
			YAHOO.example.calendar.cal.cfg.setProperty("pagedate", month + "/" + year);
			YAHOO.example.calendar.cal.render();
		}
	}

	YAHOO.example.calendar.init = function() {
		function handleSelect(type,args,obj) {
			var dates = args[0]; 
			var date = dates[0];
			var year = date[0], month = date[1], day = date[2];

			var selMonth = YAHOO.example.calendar.cal.fields.month;
			var selDay = YAHOO.example.calendar.cal.fields.day; 
			var selYear = YAHOO.example.calendar.cal.fields.year;

			selMonth.selectedIndex = month - 1;
			selDay.selectedIndex = day - 1;

			for (var y=0;y<selYear.options.length;y++) {
				if (selYear.options[y].value == year) {
					selYear.selectedIndex = y;
					break;
				}
			}
			// hide the Calendar, if it is currently showing
			if (document.getElementById('calContainer').style.display == 'block')
			YAHOO.example.calendar.cal.hide();
		}

		var year = new Date().getFullYear();
		YAHOO.example.calendar.cal = new YAHOO.widget.CalendarGroup("cal","calContainer", { pages: 2, mindate:"1/1/"+(year-5), maxdate:"12/31/"+(year+5), title:"Choose Date:", close:true });
		YAHOO.example.calendar.cal.selectEvent.subscribe(handleSelect, YAHOO.example.calendar.cal, true);
		YAHOO.example.calendar.cal.render();
		YAHOO.example.calendar.cal.fields = null;
	}

	YAHOO.util.Event.onDOMReady(YAHOO.example.calendar.init);
}
