// On DOM load
$(function()
{
	
	
	$('.saveAlert').click(function(){
		//Get the language from this form
		lang = ($(this).parent().find('#alertLang').val());
		
		//Set the display value
		if ($('#display_alert_' + lang).attr('checked')){
			display = 1;
		}
		else {
			display = 0;
		}
		
		//Set the alert value
		message = $('#alert_' + lang).val();
		
		//Ajax the request
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/updateAlerts.php",
			data: {alertLang: lang,
				   display: display,
				   alert: message
				  },
			success: function (msg){
				$('.saveAlert').val('Saved');
				$('.saveAlert').effect('highlight', 3000);
			}

		});
		
		return false;
	});
	
	$('.fixtureInfoLink').fancybox();
	
	$('a#loginButton').button('disable');
	$('a#loginButton').button('enable');
	
	$('.siteNotice').dialog({modal: true,
							opactity: 90,
							width: 400});
	
	$('.expandHeadToHead').click(function(){
		if($(this).find('img').attr('src') == '/images/icons/chevron-expand.png'){
			$(this).find('img').attr('src',"/images/icons/chevron-contract.png");
		}
		else{
			$(this).find('img').attr('src',"/images/icons/chevron-expand.png");
		}
		//Toggle the stats
		$(this).parent().find('.h2hListing').slideToggle();
	});
	
	$('.editProfileLink').click(function(){
		$('.playerInfoDetail').hide();
		$('.playerInfoInput').show();
	});
		
	$('#resetFixtureButton').click(function(){
		conf = confirm('Are you sure?');
		if(conf){
			$(this).parent().load('/ajax/resetFixture.php?fixture=' + $('#id').val());
		}
		else{
			return false;
		}
	});
	
	$('#menuExpandPlayers').click(function(){
		//Drop the list down
		$('#menuPlayerSubList').toggle();
		
		//Swap the image
		if($(this).html() == '<img src="/images/icons/chevron-small-expand.png">'){
			$(this).html('<img src="/images/icons/chevron-small-contract.png">');
		}
		else{
			$(this).html('<img src="/images/icons/chevron-small-expand.png">');
		}
	});
	
	$('.allocationPlayer').draggable({	revert: 'invalid',
										helper: 'clone',
										cursor: 'move'
	 								 }
	);
	
	$('.allocationDroppable').droppable({
								tolerance: 'pointer',
								hoverClass: 'ui-state-active',
								drop: function(event, ui) {
										id = ui.draggable.attr('id').replace('id_', '');
		
										//Check all other droppable divs for this ID
										$('.allocationDroppable').each(function(){
											if($(this).find('input').val() == id){
												//Found, so delete value and html
												$(this).find('input').val('');
												$(this).find('span').html('');
												//Reset the class
												$(this).removeClass('ui-state-highlight');
											}										
										});
										//Display name as text and update hidden field value
										$(this).addClass('ui-state-highlight').find('span').html(ui.draggable.html());
										$(this).find('input').val(id);
										
										//Only enable submit if all fields completed
										btnFlag = true;
										$('.allocationDroppable').each(function(){
											if($(this).find('input').val() < 1){
												btnFlag = false;
											}
										});
										if(!btnFlag){
											$('#submitKoAllocations').button('disable');
										}
										else {
											$('#submitKoAllocations').button('enable');
										}
									  }
	});
	
	$('#submitKoAllocations').button({disabled: true});
	
	$('#submitKoAllocations').click(function(){
		arrSeeds = new Array();
		i = 0;
		$('.seededAllocation').each(function(){
			arrSeeds[i] = $(this).val();
			i++;
		});
		arrOthers = new Array();
		i = 0;
		$('.otherAllocation').each(function(){
			arrOthers[i] = $(this).val();
			i++;
		});
		
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/knockoutAllocations.php",
			data: {seeds: arrSeeds,
				   others: arrOthers,
				   eventID: $('#eventID').val(),
				   level: $('#level').val()},
			success: function (msg){
				if(msg == '1'){
					output = "Allocation Successful";
				}
				else {
					//output = "There was some sort of problem";
					output = msg;
				}
				$('#koAllocationContent').html(output);
			}
		});
	});


	
	//Admin menu toggle 
	$('#toggleAdminMenu a').click(function(){
		$('#toggleAdminMenu a').toggle();
		$('#adminHeader').toggle('slow');
	});
	
	var icons = {
			header: "ui-icon-circle-arrow-e",
			headerSelected: "ui-icon-circle-arrow-s"
		};

	$('.accordion').accordion({ collapsible: true,
								active: false,
								autoHeight: false,
								icons: icons});
	
	$('.tabbed').tabs({active: false});
	
	$('.uiButton').button();

	$('.dialog').dialog({modal:true,
						 autoOpen: false,
						 buttons: { "Ok": function() { $(this).dialog("close"); }}
	});
	
	$('.registrantsList').load('/ajax/registrants.php');
	
	$('.fixtureList').each(function(){
		intEvent = $(this).attr('id').replace('fixturesEvent_', '');
		$(this).load('/ajax/showFixtures.php', {event: intEvent});
	});
	
	//$('.fixtureList').load('/ajax/showFixtures.php?event=' + $(this).attr('id'));
							

	

	
	$('.registerButton').click(function(){
		//Strip out the event id
		event_id = $(this).attr('id').replace('event_','');
		
		//Send registration request
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/registration.php?action=add&event=" + event_id,
			success: function (msg){
				if(msg == 1){
					$('.registrantsList').load('/ajax/registrants.php');
					$('#registerSuccess').dialog('open');
					$('#register').hide();
					$('#unregister').show();
				}
				else {
					alert('There was a problem');
				}
			}
		});
	});
	
	
	
	$('.unregisterButton').click(function(){
		//Strip out the event id
		event_id = $(this).attr('id').replace('event_','');
		
		//Send registration request
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/registration.php?action=delete&event=" + event_id,
			success: function (msg){
				if(msg == 1){
					$('.registrantsList').load('/ajax/registrants.php');
					$('#unregisterSuccess').dialog('open');
					$('#unregister').hide();
					$('#register').show();
					
				}
				else {
					alert('There was a problem');
				}
			}
		});
	});
	
	
	$('#addFrameLink').fancybox();
	
	
	$('.resetFixture').click(function(){
		return confirm('Are you sure?');
	});
	
	$('.goToLeagueTable').click(function(){
		parent.window.location('/leagueTable.php');
	});
	
	
	//Tab the stats
	$('#tabbedChartsContainer').tabs();
	$('.profileStats').tabs();
	
	//Frame form stuff
	
	//Show break input details p1
	$('#addP1Break').click(function(){
		$('#p1BreakDetails').toggle();
	});
	
	//Default time link p1
	$('#p1DefaultTime').click(function(){
		$('#p1_minutes').val('20');
		$('#p1_seconds').val('00');
	});
	
	//Show break input details p2
	$('#addP2Break').click(function(){
		$('#p2BreakDetails').toggle();
	});
	
	//Default time link p2
	$('#p2DefaultTime').click(function(){
		$('#p2_minutes').val('20');
		$('#p2_seconds').val('00');
	});
	
	//Show head to head stats
	$('#h2hLink').click(function(){
		$('#h2hContainer').slideToggle();
		
		if($('a#h2hlink').html() == '+'){
			$('a#h2hlink').html('-');
		}
		else {
			$('a#h2hlink').html('+');
		}
	});
	
	$('.datepicker').datepicker({ dateFormat: 'yy-mm-dd'});
	
	$('#profileForm').submit(function(){
		//AjaxForm Options
		var profileFormOptions = {   
				target: 		'#profileImage',
		        url:       		'/ajax/editProfile.php',   // override for form's 'action' attribute 
		        type:      		'post',
		        success:		function(msg){
										$('#playerName').html($('#name').val());
										$('#playerLocation').html($('#location').val());
										$('#playerGG').html($('#GG').val());
										$('#playerDescription').html($('#description').val());
										
										$('.playerInfoDetail').show();
										$('.playerInfoInput').hide();									
								}	
		};
		$('#profileForm').ajaxSubmit(profileFormOptions);
		return false;
	});
	
	$('#eventsForm').submit(function(){
		//AjaxForm Options
		var contactFormOptions = {   
				target: 		null,
		        url:       		'/ajax/addEvent.php',   // override for form's 'action' attribute 
		        type:      		'post',
		        success:		function(msg){
									if(msg == 1){
										alert('Saved');
									}
									else {
										alert(msg);
									}
								}	
		};		
		$('#eventsForm').ajaxSubmit(contactFormOptions);
		return false;
		
	});
	
	$('.registrantsListRowAdmin').draggable({revert: true,
											 cursor: 'move',
											 handle: '.registerListName',
											 helper: 'clone',
											 opacity: 0.6});
	
	$('.adminRemoveRegistrant').click(function(){
		
		conf = confirm("Delete Registration?");
		
		if(conf){
		
		eventid = $(this).attr('event');
		playerid = $(this).attr('player');
				
		//Send registration request
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/registration.php",
			data: {action: 'delete',
				   event: eventid,
				   player: playerid },
			success: function (msg){
				if(msg == 1){
					$(this).parent().parent().remove();
				}
				else {
					alert('There was a problem.Please refresh the page and try again.');
				}
			}
		});
		$(this).parent().parent().remove();
		}
		else {
			return false;
		}
	});
	
	
	$('#generateGroupButton').click(function(){
		if($('#revenge').attr('checked')) {
			revenge = 1;
		}
		else {
			revenge = 0;
		}
		uri = '/ajax/createGroups.php?groups=' + $('#numGroups').val() + '&event=' + $('#event_ID').val() + '&revenge=' + revenge;
		$('#groupCreation').load(uri);
	});
	
	$('.eventDateSubmit').click(function(){
		eventStage = $(this).attr('id').replace('submit_', '');
		if(!$('#start_' + eventStage).val() || !$('#finish_' + eventStage).val()){
			alert("Fill in both dates, dude");
		}
		else {
			$.ajax({
				type: "GET",
				cache: false,
				url: "/ajax/eventStageDate.php",
				data: { eventStage: eventStage,
					   	start: $('#start_' + eventStage).val(),
					   	finish: $('#finish_' + eventStage).val(),
					   	best_of: $('#best_of_' + eventStage).val()},
				success: function (msg){
				  if(msg == 1){
					  $('#submit_' + eventStage).attr('disabled', 'disabled');
					  $('#submit_' + eventStage).attr('value', 'Saved!');
				  }
				  else {
					  alert('There was a problem saving the change');
				  }
				}
			});
		}
		
	});
	
	$('#submitKnockoutFixturesCreate').click(function(){
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/createKnockoutFixtures.php",
			data: { stage: $('#knockoutStartStage').val(),
					event: $('#knockoutEvent').val()},
			success: function (msg){
				if(msg == 1){
					$('#knockoutCreateContent').html('Fixtures Created');
				}
				else {
					$('#knockoutCreateContent').html('There was a problem creating the fixtures');
				}
			}
		});
	});
	
	$('#closeEventButton').click(function(){
		$('#closeEvent').load('/ajax/closeEvent.php?eventID=' + $('#hiddenEventId').val());
	});
	
	$('.expandEventRanking').click(function(){
		if($(this).html() == '<img src="/images/icons/chevron-expand.png">'){
			$(this).html('<img src="/images/icons/chevron-contract.png">');
		}
		else{
			$(this).html('<img src="/images/icons/chevron-expand.png">');
		}
		
		$(this).parent().parent().parent().find('.eventRankingBreakdown').slideToggle();
	});


	$('.groupSeedsSubmit').click(function(){
		event = $('#hiddenEventID').val();
		group = $(this).attr('id').replace('submit_', '');
		seeds = $('#num_seeds_' + group).val();
		qualifiers = $('#num_qualifiers_' + group).val();
		
		$.ajax({
			type: "GET",
			cache: false,
			url: "/ajax/groupSeeds.php",
			data: { event: event,
					group: group,
					seeds: seeds,
					qualifiers: qualifiers},
			success: function (msg){
				if(msg == '1'){
					alert("Saved");
				}
				else {
					alert(msg);
				}
			}
		});
	});
	
	$('#sidebarRecentFixtures').accordion({
		collapsible: true,
		active: 0,
		autoHeight: false});

	$('#recentFixtures').cycle({ 
	    fx:    'scrollLeft', 
	    speed:  1500,
	    timeout:  5000
	 });
	
	$('#sidebarMyFixtures').accordion({
		collapsible: true,
		active: 0,
		autoHeight: false});
	
	$('#expandNewsFeed').click(function(){
		if($(this).html() == '<img src="/images/icons/chevron-expand.png">'){
			$(this).html('<img src="/images/icons/chevron-contract.png">');
		}
		else{
			$(this).html('<img src="/images/icons/chevron-expand.png">');
		}
		$('#newsFeedContent').slideToggle();
	});
	
	$('#seasonInfoContainer').tabs();
	
	$('#rankingPlayersHeader').click(function(){
		$('#rankingPlayersList').slideToggle();
	});
	
	$('.rankingPlayerID').click(function(){
		
		url = '/charts/chartRankingHistory.php?custom=1'
		
		$('.rankingPlayerID').each(function(){
			if($(this).attr('checked')){
				url+= '&id[]=' + $(this).val();
			}
		});
		
		$('#rankingHistoryFrame').attr('src', url);
	});
	
	$('#selectAllRankingPlayers').click(function(){
		$('.rankingPlayerID').each(function(){
			$(this).attr('checked', true);
		});
		$('#rankingHistoryFrame').attr('src', '/charts/chartRankingHistory.php');
	});
	
	$('#deselectAllRankingPlayers').click(function(){
		$('.rankingPlayerID').each(function(){
			$(this).attr('checked', false);
		});
		$('#rankingHistoryFrame').attr('src', '/charts/chartRankingHistory.php');
	});
	
	$('.expandRankingPlayersLink').click(function(){
		
		if($(this).html() == '<img src="/images/icons/chevron-expand.png">'){
			$(this).html('<img src="/images/icons/chevron-contract.png">');
		}
		else{
			$(this).html('<img src="/images/icons/chevron-expand.png">');
		}
		$('#rankingPlayersList').slideToggle();
	});
	
});
