// Event listener callback for page loaded event.
document.observe('dom:loaded', function() {
	if (($('users_new') || $('users_create'))) {
		if ($('users_country')) {
			checkStates($('users_country', 'users'));
		}
		
		if ($('user_organization') && $('user_organization').value == 'false' && $('organization_login')) {
			$('organization_login').disabled = true;
		}
	}
	
	if (($('teams_new') || $('teams_create'))) {
		if ($('team_country')) {
			checkStates($('team_country', 'teams'));
		}
	}

	if ($('teams_show_layer')) {
		layerEvents($('team_info_layer'));
	}
	if ($('users_show_layer')) {
		layerEvents($('profile_info_layer'));
	}
});

// Inserts a state select for a number of countries.
function checkStates(element, controller, layer) {
	if (element.value == 'Germany' || element.value == 'Switzerland' || element.value == 'Austria' || element.value == 'United States') {
		new Ajax.Request('/' + controller + '/insert_states', {asynchronous:true, evalScripts:true,
			parameters:'country=' + element.value + '&layer=' + layer + '&authenticity_token=' + encodeURIComponent(getAuthKey())});
	} else {
		$('insert_states').update('');
	}
}

// Inserts a state select for a number of countries.
function checkAccountStates(element, controller, layer) {
	if (element.value == 'Germany' || element.value == 'Switzerland' || element.value == 'Austria' || element.value == 'United States') {
		new Ajax.Request('/' + controller + '/insert_account_states', {asynchronous:true, evalScripts:true,
			parameters:'country=' + element.value + '&layer=' + layer + '&authenticity_token=' + encodeURIComponent(getAuthKey())});
	} else {
		$('account_insert_states').update('');
	}
}

// Switches fields for a user / organization.
function setOrganizationValues(setValues) {
	if (setValues) {
		$('user_organization').value = "true";
		$('organization_login').disabled = false;
	} else {
		$('user_login').removeClassName('error');
		$('user_organization').value = "false";
		$('organization_login').disabled = true;
	}
}

// add events to the layers
function layerEvents(layer){
	// set layer position
	layer.show();
	var wrapper = layer.firstDescendant();
	var posY = (document.viewport.getHeight()/2) + document.viewport.getScrollOffsets().top - (wrapper.getDimensions().height/2);
	wrapper.setStyle({marginTop:posY+'px'});
	new Draggable(wrapper);
	
	// hide select fields in IE
	if(Prototype.Browser.IE){
		var select_fields = $$('#wrapper select');
		select_fields.each(function(el){
			el.hide();
		});
	}
	
	// init close buttons
	var closer = layer.select('.close');
	closer.each(function(el){
		el.observe('click',function(){
			layer.hide();
			if(Prototype.Browser.IE){
				select_fields.each(function(el){
					el.show();
				});
			}
		});
	});
}

function dontShowAgain(cookieName) {
	writeCookie(cookieName, "true");
}

function readCookie(name) {
	var tC = document.cookie.split('; ');
	for (var i = tC.length - 1; i >= 0; i--) {
		var x = tC[i].split('=');
		if (name == x[0]) return unescape(x[1]);
	}
	return null;
}

function writeCookie(name, val) {
	document.cookie = name + '=' + escape(val);
}

// Organizer Calendar
function getXYpos(elem){
	if(!elem) return {'x':0, 'y':0};
	var xy = {'x':elem.offsetLeft, 'y':elem.offsetTop};
	var par = getXYpos(elem.offsetParent);
	for (var key in par) xy[key] += par[key];
	return xy;
}

function addCalendarEntry(team_id, date, day_id) {
	new Ajax.Request('/teams/' + team_id + '/add_organizer_date', {
		asynchronous:true, evalScripts:true, parameters:'date=' + encodeURIComponent(date) + '&layer=true'
		+ '&day_id=' + day_id.id + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
		onComplete: function(){
			var wrapper = $('add_organizer_date_layer').firstDescendant();
			var event_pos = getXYpos(day_id);
			wrapper.setStyle({marginLeft:event_pos['x']-350+'px',marginTop:event_pos['y']-187+'px'});
			new Draggable(wrapper);
		}
	});
}

function retrieveGameInfos() {
	if ($('event_name').value == 'New Event') {
		$('event_name').value = 'Team Name';
	}
	$('event_description_text').innerHTML = 'Info';
	$('select_city').show();
}

function unsetGameInfos() {
	if ($('event_name').value == 'Team Name') {
		$('event_name').value = 'New Event';
	}
	$('event_description_text').innerHTML = 'Description';
}

function loadHomeLocation(team_id) {
	if (team_id && team_id != "0") {
		new Ajax.Request('/teams/'+ team_id + '/load_home_location', {asynchronous:true, evalScripts:true,
			parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())});
	}
}

function seasonSelection(element) {
	if (element.value == 0) {
		$('select_location').hide();
		$('new_series').hide();
		$('event_new_series').value = '';
	} else {
		if (element.value == 'New series') {
			$('new_series').show();
		} else {
			$('event_new_series').value = '';
			$('new_series').hide();
		}
		$('select_location').show();
	}
}

function enableTeamOptions() {
	if ($('event_team_id') && $('event_team_id').value > 0) {
		$('event_type').value = 2;
		$('event_type').disabled = false;
	} else {
		$('event_type').value = 4;
		$('event_new_series').value = '';
		$('event_type').disabled = true;
	}
	eventTypeOptions();
}

function eventTypeOptions() {
	if($('event_type').value!=1){
		$('select_season').hide();
		unsetGameInfos();
	} else {
		$('select_season').show();
		retrieveGameInfos();
	}
	
	if($('event_type').value==4){
		$('event_allday').show();
	} else {
		$('event_allday').hide();
	}
	
	if($('event_type').value==3){
		$('select_date').hide();
		$('select_repeat').show();
	} else {
		$('select_date').show();
		$('select_repeat').hide();
	}
	
	if($('event_type').value==1){
		$('eventlabel').innerHTML='vs.';
	} else {
		$('eventlabel').innerHTML='';
	}
}

function addHourlyCalendarEntry(team_id, date, hour, element, view) {
	new Ajax.Request('/teams/' + team_id + '/add_organizer_date', {asynchronous:true, evalScripts:true,
		parameters:'date=' + encodeURIComponent(date) + '&hour=' + hour + '&layer=true&view=' + view
		+ '&day_id=' + element.id + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
		onComplete: function(){
			var wrapper = $('add_organizer_date_layer').firstDescendant();
			var posY = (document.viewport.getHeight()/2) + document.viewport.getScrollOffsets().top - (wrapper.getDimensions().height/2);
			var posX = (document.viewport.getWidth()/2) + document.viewport.getScrollOffsets().left - (wrapper.getDimensions().width/2) + 115;
			wrapper.setStyle({marginTop:posY+'px',marginLeft:posX+'px'});
			new Draggable(wrapper);
		}	
	});
}

function showCalendarEntry(team_id, event_id, element, view, personal) {
	new Ajax.Request('/teams/' + team_id + '/events/' + event_id, {asynchronous:true, evalScripts:true, method:'get',
		parameters:'layer=true'+ '&view=' + view + '&element_id=' + element.id + '&personal=' + personal + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
		onComplete: function(){
			if(view == 'monthly'){
				var wrapper = $('add_organizer_date_layer').firstDescendant();
				var event_pos = getXYpos(element);
				wrapper.setStyle({marginLeft:event_pos['x']-264+'px',marginTop:event_pos['y']-114+'px'});
			} else if (view == 'list') {
				var wrapper = $('add_organizer_date_layer').firstDescendant();
				var event_pos = getXYpos(element.down('.event_title'));
				wrapper.setStyle({marginLeft:event_pos['x']-$('add_organizer_date_layer').firstDescendant().getWidth()+10+'px',marginTop:event_pos['y']-114+'px'});
			} else if (view == 'games') {
				var wrapper = $('add_organizer_date_layer').firstDescendant();
				var event_pos = getXYpos(element);
				wrapper.setStyle({marginLeft:event_pos['x']-$('add_organizer_date_layer').firstDescendant().getWidth()+10+'px',marginTop:event_pos['y']-127+'px'});
			} else {
				var wrapper = $('add_organizer_date_layer').firstDescendant();
				var posY = (document.viewport.getHeight()/2) + document.viewport.getScrollOffsets().top - (wrapper.getDimensions().height/2);
				var posX = (document.viewport.getWidth()/2) + document.viewport.getScrollOffsets().left - (wrapper.getDimensions().width/2) + 115;
				wrapper.setStyle({marginTop:posY+'px',marginLeft:posX+'px'});
			}
			new Draggable(wrapper);
			$('add_organizer_date_layer_close').observe('click',function(){
				$('add_organizer_date_layer').hide();
			});
		}
	});
}

// Being called from within the show layer.
function editEvent(team_id, event_id, view, personal, edit_series) {
	new Ajax.Request('/teams/' + team_id + '/events/' + event_id + '/edit', {asynchronous:true, evalScripts:true, method:'get',
		parameters:'layer=true&view=' + view + '&personal=' + personal + '&edit_series=' + edit_series +
		'&authenticity_token=' + encodeURIComponent(getAuthKey()),
		onComplete: function(){
			var wrapper = $('add_organizer_date_layer').firstDescendant();
			var day_pos = getXYpos(element);
			wrapper.setStyle({marginLeft:day_pos['x']-335+'px',marginTop:day_pos['y']-190+'px'});
			new Draggable(wrapper);
		}	
	});
}

// Being called directly to edit an event.
function fullEditEvent(team_id, event_id, element, view, personal) {
	new Ajax.Request('/teams/' + team_id + '/events/' + event_id + '/edit', {asynchronous:true, evalScripts:true, method:'get',
		parameters:'layer=true&create_layer=true&view=' + view + '&personal=' + personal + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
		onComplete: function(){
			var wrapper = $('add_organizer_date_layer').firstDescendant();
			var day_pos = getXYpos(element);
			wrapper.setStyle({marginLeft:day_pos['x']-282+'px',marginTop:day_pos['y']-110+'px'});
			new Draggable(wrapper);
		}	
	});
}

// Holler
function checkTwitterSettings(oAuth) {
	if (!oAuth) {
		alert("Please go the Settings page first to verify your twitter account.");
		$('twitter').checked = false;
	}
}

// Weekly calendar mouseover
function wcalendar(){
	document.observe('dom:loaded',function(){
		$$('div#wcalendar div.w_event').each(function(el){
			var eventClass = el.readAttribute('class').split(' ');
			var eventType = eventClass[1].substring(eventClass[1].length-1);
			el.observe('mouseover',function(event){
				$$('div#wcalendar div.'+eventClass[2]).each(function(el){
					el.addClassName('w_event_type_'+eventType+'_hover');
				});
			});
			el.observe('mouseout',function(event){
				$$('div#wcalendar div.'+eventClass[2]).each(function(el){
					el.removeClassName('w_event_type_'+eventType+'_hover');
				});
			});
		});
	});
}

// Stats

// Stats Step 1
function calculate_total_rebounds(index) {
	offence = $('game_statistic_player_statistics_attributes_' + index + '_offensive_rebounds')
	defence = $('game_statistic_player_statistics_attributes_' + index + '_defensive_rebounds')
	total = $('game_statistic_player_statistics_attributes_' + index + '_total_rebounds') 
	if (offence && defence && total) {
		total.value = new Number(offence.value) + new Number(defence.value);
	}
}

function numberOfPlayerStats() {
	return $$(".stats_lineup").size();
}

function invitePlayer(team_id) {
	new Ajax.Request('/game_statistics/invite?team_id=' + team_id, {asynchronous:true, evalScripts:true,
		parameters:'index=' + numberOfPlayerStats() + '&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function showOptionalStats() {
	$$('.optional_details').invoke('show'); $$('.details_more').invoke('hide'); $$('.info').invoke('hide');
}

function hideOptionalStats() {
	$$('.optional_details').invoke('hide'); $$('.details_more').invoke('show'); $$('.info').invoke('show');
}

function gameDecisionLayer(game_id) {
	new Ajax.Request('/games/' + game_id + '/game_won_status', {asynchronous:true, evalScripts:true, method: 'get',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())});
	return false;
}

function setGameWithoutStatsStatus(game_id, game_won_value) {
	new Ajax.Request('/games/' + game_id + '/set_game_won_status', {asynchronous:true, evalScripts:true, method: 'put',
		parameters:'game_won_without_stats=' + game_won_value + '&authenticity_token=' + encodeURIComponent(getAuthKey())});
	return false;
}

// Stats Step 2
var current_period = 1;
var current_quarter = 1;
var selected_player = -1;
var total_points = 0;
var quarter_points = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0, 10:0};
var edit_score_id = 0;
var halftime_period = false;
var in_overtime = false;

function addToTotalPoints(points) {
	if (points && points > 0) {
		total_points += points;
		quarter_points[current_quarter] += points;
		
		if ($('total_points_counter')) {
			$('total_points_counter').innerHTML = "Total <b>" + total_points + "</b> Pts.";
		}
	}
}

function totalOpponentScore() {
	if ($('game_statistic_first_quarter_opponent_score').value != "") {
		total_points_opponent = parseInt($('game_statistic_first_quarter_opponent_score').value);
	} else {
		total_points_opponent = 0;
	}
	if ($('game_statistic_second_quarter_opponent_score').value != "") total_points_opponent += parseInt($('game_statistic_second_quarter_opponent_score').value);
	if ($('game_statistic_third_quarter_opponent_score').value != "") total_points_opponent += parseInt($('game_statistic_third_quarter_opponent_score').value);
	if ($('game_statistic_fourth_quarter_opponent_score').value != "") total_points_opponent += parseInt($('game_statistic_fourth_quarter_opponent_score').value);
	$('game_statistic_total_opponent_score').value = total_points_opponent;
}

function addScore(team_id, game_id, game_statistic_id, period, quarter, minute, element) {
	new Ajax.Request('/teams/' + team_id + '/games/' + game_id + '/game_statistics/' + game_statistic_id + '/scores/new',
		{asynchronous:true, evalScripts:true, method: 'get', parameters:'minute=' + minute + '&period=' + period + '&quarter=' + quarter +
		'&authenticity_token=' + encodeURIComponent(getAuthKey()), onComplete: function(){scrollIntoView(element);}}); return false;
}

function editScore(team_id, game_id, game_statistic_id, period, quarter, minute, score_id, element) {
	if ($('quarter_' + quarter + '_minute_' + minute + '_player_statistic_' + score_id)) {
		$$('.minute_rows').each(function(e){ e.removeClassName("active"); })
		$('quarter_' + quarter + '_minute_' + minute + '_player_statistic_' + score_id).addClassName("active");
	}
	new Ajax.Request('/teams/' + team_id + '/games/' + game_id + '/game_statistics/' + game_statistic_id + '/scores/' + score_id + '/edit',
		{asynchronous:true, evalScripts:true, method: 'get', parameters:'minute=' + minute + '&period=' + period + '&quarter=' + quarter +
		'&authenticity_token=' + encodeURIComponent(getAuthKey()), onComplete: function(){scrollIntoView(element);}}); return false;
}

function selectPlayer(element, player_statistic_id, top, score_id) {
	$$('.player').each(function(e) {
		e.removeClassName('player_top_active');
		e.removeClassName('player_bottom_active');
	});
	$('undefined_player').removeClassName('tab_small_active');

	if (element && top != "undefined_player") {
		selected_player = player_statistic_id;
		element.addClassName('player_' + top + '_active');
	} else {
		selected_player = 0;
		element.addClassName('tab_small_active');
	}

	// Edit
	if (score_id > 0) {
		edit_score_id = score_id;
	}
}

function saveScore(team_id, game_id, game_statistic_id, period, quarter, minute, score_type, element) {
	if (selected_player != -1) {
		container_exists = $('quarter_' + quarter + '_minute_' + minute) ? true : false;

		if (selected_player > 0) {
			$('player_' + selected_player).removeClassName('player_top_active');
			$('player_' + selected_player).removeClassName('player_bottom_active');
		} else {
			$('undefined_player').removeClassName('tab_small_active');
		}

		before_id = 'new'; after_id = ''; existing_minutes = $$('.period_' + period + '_quarter_' + quarter + '_minutes');
		if (!container_exists && existing_minutes && minute > 1) {
			existing_minutes.each(function(e) {
				if (e.attributes["minute"] && e.attributes["quarter"] && before_id == 'new') {
					if (parseInt(e.attributes["quarter"].value) == quarter && parseInt(e.attributes["minute"].value) > minute) {
						before_id = e.id;
					}
				}
			});
			if (before_id == 'new') {
				after_id = existing_minutes.last().id;
			}
		}

		if (edit_score_id > 0) {
			new Ajax.Request('/teams/' + team_id + '/games/' + game_id + '/game_statistics/' + game_statistic_id + '/scores/' + edit_score_id,
				{asynchronous:true, evalScripts:true, method: 'put', parameters:'minute=' + minute + '&period=' + period + '&quarter=' + quarter +
				'&score_type=' + score_type + '&player_statistic_id=' + selected_player + '&container_exists=' + container_exists +
				'&before_id=' + before_id + "&after_id=" + after_id + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
				onComplete: function(){scrollIntoView(element);}}); return false;
		} else {
			addToTotalPoints(score_type);
			new Ajax.Request('/teams/' + team_id + '/games/' + game_id + '/game_statistics/' + game_statistic_id + '/scores',
				{asynchronous:true, evalScripts:true, method: 'post', parameters:'minute=' + minute + '&period=' + period + '&quarter=' + quarter +
				'&score_type=' + score_type + '&player_statistic_id=' + selected_player + '&container_exists=' + container_exists +
				'&before_id=' + before_id + "&after_id=" + after_id + '&authenticity_token=' + encodeURIComponent(getAuthKey()),
				onComplete: function(){scrollIntoView(element);}}); return false;
		}
	} else {
		alert("Please select a player.");
	}
}

function endOfPeriod(game_statistic_id) {
	if (game_statistic_id) {
		if (current_quarter == 1) {
			$('second_quarter_home').value = quarter_points[1];
			$('2_quarter_home').value = quarter_points[1];
			if ($('game_statistic_first_quarter_opponent_score')) $('game_statistic_first_quarter_opponent_score').disabled = true;
			if ($('game_statistic_third_quarter_opponent_score')) $('game_statistic_third_quarter_opponent_score').disabled = true;
		} else if (current_quarter == 4) {
			$('fourth_quarter_home').value = quarter_points[4];
			$('4_quarter_home').value = quarter_points[4];
			if ($('result_home')) {
				$('result_home').value = total_points;
				$('result_home_hidden').value = total_points;
			}
		}
		
		$('game_statistic_halftime_period').value = "1";
		halftime_period = true;
		
		existing_minutes = $$('.period_' + current_period + '_quarter_' + current_quarter + '_minutes');
		minute_id = existing_minutes.last().id;
		
		if (in_overtime) {
			new Ajax.Request('/scores/end_of_period', {asynchronous:true, evalScripts:true, method: 'get',
				parameters:'&game_statistic_id=' + game_statistic_id + '&quarter=' + current_quarter + '&minute_id=' + minute_id + 
				'&overtime=true&end_of_game=true&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
		} else {
			new Ajax.Request('/scores/end_of_period', {asynchronous:true, evalScripts:true, method: 'get',
				parameters:'&game_statistic_id=' + game_statistic_id + '&quarter=' + current_quarter + '&minute_id=' + minute_id + 
				'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
		}
	}
}

function endOfQuarter(game_statistic_id) {
	if (game_statistic_id) {
		existing_minutes = $$('.period_' + current_period + '_quarter_' + current_quarter + '_minutes');
		minute_id = existing_minutes.last().id;
		new Ajax.Request('/scores/end_of_quarter', {asynchronous:true, evalScripts:true, method: 'get',
			parameters:'&game_statistic_id=' + game_statistic_id + '&quarter=' + current_quarter + '&minute_id=' + minute_id + 
			'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	}
}

function overtime(game_statistic_id) {
	in_overtime = true;

	if (game_statistic_id) {
		existing_minutes = $$('.period_' + current_period + '_quarter_' + current_quarter + '_minutes');
		minute_id = existing_minutes.last().id;
		new Ajax.Request('/scores/end_of_quarter', {asynchronous:true, evalScripts:true, method: 'get',
			parameters:'&game_statistic_id=' + game_statistic_id + '&quarter=' + current_quarter + '&minute_id=' + minute_id + 
			'&overtime=true&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	}
}

function insertTotalPointsInLastMinuteContainer(total_points) {
	last_minute_row = $$('.minute_rows').last();
	if (last_minute_row) {
		total_points_li = "<li class=\"total\" id=\"total_points\"><span class=\"total_points\" id=\"total_points_counter\">Total <b>"
		total_points_li += total_points ? total_points : "0"
		total_points_li += "</b> Pts.</span></li>"
		last_minute_row.insert({after: total_points_li});
	}
}

function selectLastPlayerSelection() {
	if (selected_player > 0) {
		if ($('player_' + selected_player) && $('player_' + selected_player).hasClassName('player_top')) {
			$('player_' + selected_player).addClassName('player_top_active');
		}
		
		if ($('player_' + selected_player) && $('player_' + selected_player).hasClassName('player_bottom')) {
			$('player_' + selected_player).addClassName('player_bottom_active');
		}
	}
}

function scrollIntoView(element){
	/* TODO: calculate correct scroll height
	var item = $$('.minute_rows')[element_id];
	var parent = element.up('ul');
	var pos = getXYpos(parent);
	if(pos['x']+parent.getHeight()+100>document.viewport.getHeight()){
		window.scrollBy(0,parent.getHeight()+100);
	}
	*/
	window.scrollBy(0,30);
}

function disableAllGameSelectionFields() {
	if ($('game_statistic_selection_stats_season')) {
		$('game_statistic_selection_stats_season').disable();
	}
	
	if ($('game_statistic_selection_stats_opponent')) {
		$('game_statistic_selection_stats_opponent').disable();
	}
	
	if ($('game_statistic_selection_stats_date')) {
		$('game_statistic_selection_stats_date').disable();
	}
}

function displayTeamStatsWarning() {
	new Ajax.Request('/scores/show_warning', {asynchronous:true, evalScripts:true, method: 'post',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// Analysis
var statsElementCount = 0;

function insertNewSeasonAnalysisGraph(team_id, game_statistic_ids, team_membership_id, opponent, season, game_id) {
	statsElementCount += 1;
	
	if (team_membership_id) {
		new Ajax.Request('/game_statistics/insert_season_analysis_stats_element', {asynchronous:true, evalScripts:true, method: 'get',
			parameters:'&team_id=' + team_id + '&game_statistic_ids=' + game_statistic_ids + '&index=' + statsElementCount +
			'&team_membership_id=' + team_membership_id + '&opponent=' + opponent + '&season=' + season + '&game_id' + game_id + 
			'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	} else {
		new Ajax.Request('/game_statistics/insert_season_analysis_stats_element', {asynchronous:true, evalScripts:true, method: 'get',
			parameters:'&team_id=' + team_id + '&game_statistic_ids=' + game_statistic_ids + '&index=' + statsElementCount +
			'&opponent=' + opponent + '&season=' + season + '&game_id' + game_id +
			'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	}
}

function deleteModule(index) {
	if ($$('.inline_delete').size() > 1) {
		$('stats_details_element_' + index).remove();
	} else {
		alert("There must be at least one graph.");
	}
}

function displayAttendancesFormFields() {
	$$('.signoffs_number').invoke('hide');
	$$('.signoffs_fields').invoke('show');
	$('edit_button').hide();
	$('save_button').show();
}

function sendGameStatisticSelection(team_id, index, opponent_changed) {
	if ($('game_statistic_selection_stats_opponent_' + index) && $('game_statistic_selection_stats_date_' + index) && opponent_changed) {
		$('game_statistic_selection_stats_date_' + index).disable();
	}
	new Ajax.Request('/teams/' + team_id + '/game_statistics/analysis', {asynchronous:true, evalScripts:true, 
		parameters:Form.serialize('game_statistic_selection_form_box_' + index)});
}

// Search
function clearSearch() {
	$('q1').value = '';
	$('q2').value = '';
	$('search_country').value = '';
	$('search_sex').value = '';
	$('search_age_group').value='Age Groups';
	
	if ($('search_players_sticker')) $('search_players_sticker').remove();
	if ($('search_coaches_sticker')) $('search_coaches_sticker').remove();
	if ($('search_teams_sticker')) $('search_teams_sticker').remove();
	if ($('search_games_sticker')) $('search_games_sticker').remove();
	if ($('search_fans_sticker')) $('search_fans_sticker').remove();
	
	new Ajax.Request('/clear_search', {asynchronous:true, evalScripts:true,
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// Navigation
function setTab(tab) {
	new Ajax.Request('/users/set_tab?tab=' + tab, {asynchronous:true, evalScripts:true,
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// Stats/Charts
function invokeChart(element, game_statistic_id, chart_number) {
	$$('.line_chart_action_' + game_statistic_id).each(function(e) {e.removeClassName('active');});
	element.up().addClassName('active');
	$$('.line_charts_' + game_statistic_id).invoke('hide');
	$(game_statistic_id + '_chart' + chart_number).show();
}

// Album
var selectedAlbumItem = 0;

function loadTeamUploadSelection() {
	if ($F('album_item_team_id') && $F('album_item_team_id').length > 0) {
		new Ajax.Request('/album_items/insert_team_selection?team_id=' + $F('album_item_team_id'), {asynchronous:true, evalScripts:true, method:'get',
			parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	} else {
		$('album_item_season').hide();
		$('album_item_opponent').hide();
		$('album_item_game_id').hide();
		$('photo_publish').checked = false; $('photo_publish_label').hide();
	}
}

function loadTeamUploadSelectionBySeason() {
	new Ajax.Request('/album_items/insert_team_selection', {asynchronous:true, evalScripts:true, method:'get',
		parameters:'team_id=' + $F('album_item_team_id') + '&season=' + $F('album_item_season') +
		'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function loadTeamUploadSelectionByOpponent() {
	new Ajax.Request('/album_items/insert_team_selection', {asynchronous:true, evalScripts:true, method:'get',
		parameters:'team_id=' + $F('album_item_team_id') + '&season=' + $F('album_item_season') + '&opponent=' + $F('album_item_opponent') +
		'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function deleteAlbumItem() {
	new Ajax.Request('/album_items/' + selectedAlbumItem, {asynchronous:true, evalScripts:true, method:'delete',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function deleteTeamAlbumItem(team_id) {
	new Ajax.Request('/album_items/' + selectedAlbumItem + '?team_id=' + team_id, {asynchronous:true, evalScripts:true, method:'delete',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;	
}

// Messages

function insertCopyRecipient(element) {
	element.hide();
	new Ajax.Request('/messages/insert_copy_recipient', {asynchronous:true, evalScripts:true, method:'post',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// Teamboard

function changeRecordSeason(team_id, season) {
	new Ajax.Request('/teams/' + team_id + '/change_record?season=' + season, {asynchronous:true, evalScripts:true, method:'post',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function addToPersonalCalendar(event_id) {
	new Ajax.Request('/events/' + event_id + '/add_to_personal_calendar', {asynchronous:true, evalScripts:true, method:'post',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// User Network

function setFavorite(source_type, source_id, element) {
	new Ajax.Request('/favorites', {asynchronous:true, evalScripts:true, method:element.checked == true ? 'post' : 'delete',
		parameters:'favorite[source_type]=' + source_type + '&favorite[source_id]=' + source_id + 
		'&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function setDisplayEventsForFanTeam(fan_id, element) {
	new Ajax.Request('/fans/' + fan_id + "/set_display_events", {asynchronous:true, evalScripts:true, method:'put',
		parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

// account layer tab events
function accountLayerTab(link,element){
	$$('#account_tabs a').each(function(el){ el.removeClassName('active'); });
	link.addClassName('active');
	
	$$('.account_wrapper').each(function(el){ el.hide(); });
	element.show();
}

function displayAccountLayer(layer_to_hide, returnPath) {
	$(layer_to_hide).remove();
	if (returnPath == null) {
		new Ajax.Request('/users/account', {asynchronous:true, evalScripts:true, method:'post',
			parameters:'authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	} else {
		new Ajax.Request('/users/account', {asynchronous:true, evalScripts:true, method:'post',
			parameters:'return_path=' + returnPath + '&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
	}
}

function checkTerms(taxCheckFailed) {
	if (taxCheckFailed) {
		alert("Please update your tax information under the Details tab! After finishing, please restart the conversion process. Thank you!");
		accountLayerTab($('tab_credits'), $('account_details'));
		$('account_details_link').className = "active";
		$('tab_credits').className = "";
		
		return false;
	}
	
	if ($('credit_terms').checked) {
		return true;
	} else {
		alert("Please accept the Terms of Purchase.");
		return false;
	}
}

// Personal Settings
function convertHeight() {
	new Ajax.Request('/users/convert_height', {asynchronous:true, evalScripts:true, method:'post',
		parameters:'height_1=' + $('user_height_1').value + '&height_2=' + $('user_height_2').value +
		'&height_metric=' + $('user_height_metric').value + '&authenticity_token=' + encodeURIComponent(getAuthKey())}); return false;
}

function setAllLinksInactive(className) {
	$$(className).each(function(e) {e.removeClassName('active')});
}

function checkRealNameSettings() {
	if ($('show_realname').checked == false) {
		$('realname_in_searchengines').disabled = true;
		$('realname_in_searchengines').checked = false;
	} else {
		$('realname_in_searchengines').disabled = false;
	}
}

// uservoice integration
var uservoiceOptions = {
	key: 'ballside',
	host: 'ballside.uservoice.com', 
	forum: 'general',
	lang: 'en',
	showTab: false
};
function _loadUserVoice() {
	var s = document.createElement('script');
	s.src = ("https:" == document.location.protocol ? "https://" : "http://") + "cdn.uservoice.com/javascripts/widgets/tab.js";
	document.getElementsByTagName('head')[0].appendChild(s);
}
_loadSuper = window.onload;
window.onload = (typeof window.onload != 'function') ? _loadUserVoice : function() { _loadSuper(); _loadUserVoice(); };

// -----------------------------------------------------------------------------------
//
//	Protolimit v1
//	A CoralFly Creation (www.coralfly.com)
//	Last Modified 12-19-2008
//
//	For Information, instructions, and new releases, visit:
//	http://www.coralfly.com/Creations/Protolimit
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//  	- Free for use in both personal and commercial projects
//		- Attribution requires leaving author name, author link, and the license info intact
//
// -----------------------------------------------------------------------------------
var Protolimit = Class.create({
	initialize : function() {
		var ref = this;
		// Wire the Events
		$$('a[rel^=protolimit]').each(function(anchor){
			var rel = ref.parseRel(anchor.rel);
			if($(rel[0]) != null){
				ref.setRemainingCount(anchor,$(rel[0]),rel[1]);
				$(rel[0]).observe("keydown", function(limit){
					return function(event){
						ref.raiseLimitExceed(this,limit);
					}
				}(rel[1]));
				$(rel[0]).observe("keyup", function(anchor, limit){
					return function(){
						ref.raiseLimitExceed(this,limit);
						ref.setRemainingCount(anchor,this,limit);
					}
				}(anchor,rel[1]));
			}
		});
	},
	// Parse the Rel attribute
	parseRel : function(value) {
		var relRegex = new RegExp("(\\w{1,})=(\\d{1,})");
		var result = relRegex.exec(value);
		return [result[1], result[2]];
	},
	// Sets the Remaining Count
	setRemainingCount : function(anchor,input,limit){
		anchor.innerHTML = limit-input.value.length;
	},
	// Limit Exceed Event
	raiseLimitExceed : function(obj,limit) {
		if(limit-obj.value.length < 0) {
			obj.value = obj.value.substring(0, limit);
		}
	}
});
document.observe('dom:loaded', function () { new Protolimit(); });
