$(function() {
	
	// focus on first form field input
	$('.forms input:first').focus();

	// Change button text onClick
	$('input.buttons').click(function(){
		$(this).val('Submitting, Please Wait...');
	});
	
	// Home page accordion
	$('.accordion').accordion({autoHeight: false});
	
	// Schedules accordion
	$('.sch-accordion').accordion({
		autoHeight: false,
		header: 'h4',
		collapsible: true,
		activate: false,
		active: false
	});
	
	// Tabs (home page, baseball, and softball pages)
	$('.tabs').tabs({
		fx: {'opacity' : 'toggle', 'duration' : 400},
          cookie : { expires : 30 },
          collapsible : true
	}).filter('.schedules-tabs').tabs({
		selected : -1
	});
	
	$('#contact-form').submit(function(e) {
		var obj = $(this),
			btn = obj.find('.buttons').prop('disabled', 'disabled');	
		$.post(
			'/contact',
			obj.serialize(),
			function(data) {
				obj.find('label').removeClass('error');
				$('#notice').remove();
				console.log(data);
				var arr = jQuery.parseJSON(data);
				if (arr.status == 'error') {
					for (var key in arr)
					{	
						if (arr[key] != '')
						{
							obj.find('label[for="' + key + '"]').hide().addClass('error').fadeIn(2000);
						}
					}
				} else {
					clear_form(obj);
				}
				$('<div id="notice" />').html(arr.msg).hide().insertBefore('#contact-form-wrap').fadeIn(2000);
				btn.prop('disabled', false).val('Send Message');
				$('body').scrollTo('#header-bottom', 800);
			}
		), 'json';	
		e.preventDefault();
	});
	
	// Score reporting form ajax submission...
	$('#scores-form').submit(function(e) {
		var obj = $(this);	
		$.post(
			'/contact/report_game_scores',
			obj.serialize(),
			function(data) {

				var arr = $.parseJSON(data),
					division = obj.find('label[for="division"]').html(),
					lteamruns = obj.find('label[for="lteamruns"]').html();
				obj.find('label').removeClass('error');
				$('#notice').remove();
				obj.find('label[for="division"]').html('Select Your Division');
				obj.find('label[for="lteamruns"]').html('Runs Scored');
				
				if (arr.status == 'error')
				{
					for (var key in arr)
					{	
						if (arr[key] != '')
						{
							if (key == 'division')
							{
								if (/exist/.test(arr[key]))
								{
									obj.find('label[for="division"]').html('Select Your Division: ' + arr[key]);
								}
							}
							else if (key == 'lteamruns')
							{
								if (/more runs/.test(arr[key]))
								{
									obj.find('label[for="lteamruns"]').html('Runs Scored: ' + arr[key]);
								}
							}
							obj.find('label[for="' + key + '"]').hide().addClass('error').fadeIn(2000);
						}
					}
				}
				else
				{
					clear_form(obj);
				}
				$('<div id="notice" />').html(arr.msg).hide().insertBefore(obj).fadeIn(2000);
				obj.find('.buttons').val('Report Scores');
				$('body').scrollTo('#notice', 800);
			}
		), 'json';	
		e.preventDefault();
	});
	
	// email signup form
	$('#subscript-options input').change(function(){
		var $cow = $('#category-options-wrap');
		if ($('#unsub').is(':checked'))
		{
			$($cow + 'input:checkbox').attr('checked', false);
			$cow.slideUp('fast');
		}
		else
		{
			$cow.slideDown('fast');
		}
	}).trigger('change');	
	$('#subscript-cats-1').change(function(){
		var $ca = $('#other-cats');
		if ($(this).is(':checked'))
		{
			$('#nes').hide();
			$($ca + 'input:checkbox').not($(this)).attr('checked', false);
			$ca.slideUp('fast');
		}
		else
		{
			$('#nes').show();
			$ca.slideDown('fast');
		}
	}).trigger('change');	
	
	// submit subsciption form
	$('#subscription-form').submit(function(e) {
		var obj = $(this);
		$.post(
			'/subscriptions',
			obj.serialize(),
			function(data) {
				var arr = $.parseJSON(data);
				obj.find('label, h5').removeClass('error');
				$('#notice').remove();
				
				if (arr.status == 'error')
				{
					for (var key in arr)
					{	
						if (arr[key] != '')
						{
							if (key == 'option')
							{
								$('#subscription-form-options').hide().addClass('error').fadeIn(2000);
							}
							if (key == 'groups')
							{
								$('#subscription-form-categories').hide().addClass('error').fadeIn(2000);
							}
							obj.find('label[for="' + key + '"]').hide().addClass('error').fadeIn(2000);
						}
					}
				}
				else
				{
					clear_form(obj);
				}
				$('<div id="notice" />').html(arr.msg).hide().insertBefore(obj).fadeIn(2000);
				obj.find('.buttons').val('Process');
				$('body').scrollTo('#notice', 800);
			}
		), 'json';		
		e.preventDefault();
	});

	// Tinymce for forms
	$('textarea.tinymce').tinymce({
		script_url : 'https://mjbsa.com/js/tiny_mce/tiny_mce.js',
		theme : 'advanced',
		theme_advanced_buttons1 : "bold,italic,underline,|,justifyleft,justifycenter,justifyright,justifyfull,|,link,unlink,anchor,formatselect",
		theme_advanced_buttons2 : '',
		theme_advanced_buttons3 : ''
	});
	
	// Colorbox image/page overlay
	$('a.colorbox').colorbox({
		width: '70%',
		height: '70%',
		iframe: true,
		rel: 'maps',
		transition: 'fade'
	});
	$('a.gallery').colorbox({
		maxWidth: '70%',
		maxHeight: '70%',
		iframe: false,
		rel: 'gallery',
		transition: 'fade',
		speed: '200'
	});
	$('div#cboxTitle').prepend('a.colorbox').html();
	
	// Tweet on home page
	getTwitters('tweet', { 
		id: 'mjbsaupdate', 
		count: 1, 
		enableLinks: true, 
		ignoreReplies: true, 
		clearContents: true,
		template: '%text% <a href="https://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'	});
		
	// Tweets in footer
	getTwitters('footer-tweets', { 
		id: 'mjbsaupdate', 
		count: 5, 
		enableLinks: true, 
		ignoreReplies: true, 
		clearContents: true,
		template: '%text% <a href="https://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'	});
	
	// remove conditionally irrelevant form fields on registration form
	$('#returning').change(function(){
		var $this = $(this);
		if ($this.val() == 0)
		{
			$('#no-mjbsa')
				.find('option[value="0"]').attr('selected', 'selected')
				.end()
				.find('input').attr('value', '')
				.end()
				.slideDown('slow');
		}
		else if ($this.val() == 'Yes')
		{
			$('#no-mjbsa').slideDown('slow');
		}
		else
		{
			$('#no-mjbsa')
				.find('option[value="No"]').attr('selected', 'selected')
				.end()
				.find('input').attr('value', '')
				.end()
				.slideUp('fast');
		}
	}).trigger('change');
	
	$('#sibling').change(function(){
		if ($(this).val() == 'No')
		{
			$('#list_siblings')
				.attr('value', '')
				.parents('p.inline-inputs')
				.slideUp('fast');
			$('#siblings-list').slideUp('fast');
		}
		else
		{
			$('#list_siblings')
				//.attr('value', '')
				.parents('p.inline-inputs')
				.slideDown('slow');
			$('#siblings-list').slideDown('slow');
		}
	}).trigger('change');

	$('#agegroup').change(function(){
		if ($(this).val() == 'No')
		{
			$('#sameteam-wrap')
				.find('option[value="No"]').attr('selected', 'selected')
				.end()
				.slideUp('fast');
		}
		else if ($(this).val() == 'Yes')
		{
			$('#sameteam-wrap').slideDown('slow');
		}
		else
		{
			$('#sameteam-wrap')
				.find('option[value="0"]').attr('selected', 'selected')
				.end()
				.slideDown('slow');
		}
	}).trigger('change');
	
	// scroll up to schedules
	$('.ps-anchor').click(function(e){
		$('body').scrollTo(0, 800);
		e.preventDefault();
	});
	
	$('.print-tb').click(function(){
		var $schWrap = $(this).parents('#tball-sch');
		$schWrap.printElement({
			printMode : 'popup',
			leaveOpen : false
		});
		return false;		
	});
	
	$('.print-sch').click(function(){
		var $schWrap = $(this).parents('.schedules-table-wrap');
		$schWrap.printElement({
			printMode : 'iframe',
			leaveOpen : false
		});
		return false;		
	});
	
	// umpire application form
	var $ma = $('#minor-auth');
	$('#ump-age').change(function(){
		if ($(this).val() >= 18)
		{
			$ma.slideUp('slow').find('input:checkbox').attr('checked', '');
		}
		else
		{
			$ma.slideDown('slow');
		}
	}).trigger('change');
	
	// umpire submissions
	$('#ump-application-form').submit(function(e) {
		var obj = $(this);	
		$.post(
			'/contact/umpire_application',
			obj.serialize(),
			function(data) {

				var arr = $.parseJSON(data),
					name = obj.find('label[for="name"]').html();
					
				obj.find('label').removeClass('error');
				
				$('#notice').remove();
				
				obj.find('label[for="name"]').html('Name');
				
				if (arr.status == 'error')
				{
					for (var key in arr)
					{	
						if (arr[key] != '')
						{
							// due to callback validation, we need to handle some special cases
							if (key == 'name')
							{
								if (/Duplicate Application/.test(arr[key]))
								{
									obj.find('label[for="name"]').html('Name: ' + arr[key]);
								}
							}
							else if (key == 'age')
							{
							   if (/at least 12/.test(arr[key]))
							   {
							   	obj.find('label[for="age"]').html(arr[key]);
							   }
							}
							obj.find('label[for="' + key + '"]').hide().addClass('error').fadeIn(2000);
						}
					}
				}
				else
				{
					clear_form(obj);
				}
				$('<div id="notice" />').html(arr.msg).hide().insertBefore(obj).fadeIn(2000);
				obj.find('.buttons').val('Send Application');
				$('body').scrollTo('#notice', 800);
			}
		), 'json';	
		e.preventDefault();
	});
	
	// Email Options dialog
	var emailDialog = $('#modal-subscriptions').dialog({
		modal : true,
		resizable : false,
		title : 'Manage MJBSA Email Subscriptions - Subscribe/Update/Unsubscribe',
		show : 'fade',
		hide : 'fade',
		draggable : false,
		position: 'center',
		autoOpen: false,
		width: 800,
		minHeight: 600,
		closeText: 'x'
	});
	$('a.email-subscript-link').click(function(e){
		if (!(/subscriptions/.test(window.location.href)))
		{
			emailDialog.dialog('open');
		}
		clear_form('#subscription-form');
		$('#subscription-form-wrap')
			.find('input:first').attr('checked', 'checked')
			.end()
			.find('#notice').remove()
			.end()
			.find('label, h5').removeClass('error')
			.end()
			.find(':hidden:not("#nes")').show()
			.find('input:submit')
			.val('Process');
		e.preventDefault();
	});
	
	// RSS Options dialog
	var rssDialog = $('#modal-rss').dialog({
		modal : true,
		resizable : false,
		title : 'Manage MJBSA RSS Subscriptions',
		show : 'fade',
		hide : 'fade',
		draggable : false,
		position: 'center',
		autoOpen: false,
		width: 500,
		minHeight: 200,
		closeText: 'x'
	});
	$('a.rss-subscript-link').click(function(e){
		if (!(/subscriptions/.test(window.location.href)))
		{
			rssDialog.dialog('open');
		}
		e.preventDefault();
	});
	
	$('ul.flips div.back').css('z-index', '2');
	$('ul.flips li').hover(function(e){
		var $el = $(this),
			$ht = $el.find('div.front').outerHeight() + 10 + 'px';
		$el.find('div.front')
			.stop(true, true)
			.animate({
				marginTop : $ht
			}, 300);
		e.preventDefault();	
	}, function(e){
		var $el = $(this);
		$el.find('div.front')
			.stop(true, true)
			.animate({
				marginTop : 0
			}, 100);
		e.preventDefault();	
	});
	
	// toggle view of how standings are calculated
	var $stdc = $('#st-calc-desc'),
		$ht = $stdc.height();
	$stdc.css('height', $ht + 'px').hide();
	$('#st-calc-trigger').click(function(e){
		$stdc.slideToggle(500);
		e.preventDefault();
	});
	
	// toggle view of subscriptions information
	var $subi = $('#subscript-info'),
		$ht = $subi.height(),
		$trigger = $('#subscript-info-trigger'),
		$lt = $trigger.text();
	$subi.css('height', $ht + 'px').hide();
	$trigger.click(function(e){
		$(this).text() === $lt ? $(this).text('[ hide info ]') : $(this).text($lt);
		$subi.slideToggle(800);
		e.preventDefault();
	});
	
	$('div.cal-content h5').hover(function(e){
		obj = $(this),
		container = obj.parents('div.cal-content').css({position : 'relative', overflow : 'visible'}),
		popup = container.find('div.cal-details');
		$('#hp-content-wrap').css('overflow', 'visible');	
		popup.css('top', -popup.outerHeight()).stop(true, true).fadeIn(800);	
		e.preventDefault();
	}, function(){
		popup.stop(true, true).fadeOut(50);
		$('#hp-content-wrap', container).css('overflow', 'hidden');
	});
	
	$('#sponsorships > div:not(:first)').hide();
	$('#numspons').change(function(){
		var divindex = parseInt($(this).val());
		$('#sponsorships')
			.find('div:lt(' + (divindex + 1) + ')')
			.fadeIn(1000)
			.end()
			.find('div:gt(' + (divindex - 1) + ')')
			.hide()
			.find('option:first')
			.attr('selected', 'selected')
			.parent()
			.siblings('input')
			.val('');
	}).trigger('change');

	// umpire application form
	$('#experience').change(function(){
		var $pu = $('#previously-umpired');
		if ($pu.is(':hidden')) {$pu.slideDown();}
		if ($(this).val() != 0)
		{
			$pu.slideDown('slow');
		}
		else
		{
			$('#mjbsa-ump').val(0);
			$pu.slideUp('fast');
		}
	}).trigger('change');
	
	// clear form values
	function clear_form(ele)
	{
		$(ele).find(':input').each(function() {
			switch(this.type) {
				case 'password':
				case 'text':
				case 'textarea':
					$(this).val('');
					break;
				case 'select-multiple':
				case 'select-one':
					$(this).val(0);
					break;
				case 'checkbox':
				case 'radio':
					this.checked = false;
			}
		});
	}
	
	// message for feedback option on contact form
	$('#subject').change(function(){
		var selectval = $(this).find('option:selected').val();
		if (selectval === '7' && ($('#fname').val() === '' || $('#lname').val() === '' || $('#email').val() === ''))
		{
			$('<div id="fb-notice" class="noticebg"><h3>Anonymous Feedback Notice</h3><p>Although feedback can be submitted anonymously by not entering your name and email address, if you have specific issues that need to be addressed (coaching or umpire issues, etc.), or if you ask specific questions, these cannot be answered or addressed thoroughly if we do not have a way to contact you.  If we cannot address your issues, there is really no way to fix it for next season. We encourage you to provide your contact information in those cases.</p></div>').css({'margin-top' : '40px', 'text-align' : 'center', 'border' : '1px solid #333'}).insertAfter($(this)).hide().fadeIn(800);
		}
		else
		{
			$('#fb-notice').fadeOut(500, function(){ $(this).remove() });	
		}
	});
	
	// FAQ page
	$('#faq-list dd').hide().prev().click(function(){
		$(this).next().slideToggle(400);
	});
	
	$('.print-page').click(function(e){
		$('#faq-list dd').show();
		window.print();
		e.preventDefault();
	});
	
	// board members sliding boxes
	$('#board-members-wrap')
		.find('.board-members-list')
		.css({
			margin: '0 0 40px 0',
			height: '220px',
			width: '879px',
			overflow: 'hidden',
			whiteSpace: 'nowrap',
			padding: '0'
		})
		.find('li')
			.css({
				position: 'relative',
				zIndex: 2,
				margin: 0,
				padding: 0,
				height: '220px',
				width: '219px',
				overflow: 'hidden',
				float: 'left',
				cursor: 'pointer'
			}).hover(function() {
				$(this).stop(true, true).animate({
					width: '879px'
				}, 600).siblings().stop(true, true).animate({
					width: '0px'
				}, 600).end().find('.caption').fadeOut();
			}, function() {
				$(this).stop(true, true).animate({
					width: '219px'
				}, 600).siblings().stop(true, true).animate({
					width: '219px'
				}, 600).end().find('.caption').fadeIn();
			})
		.find('div')
			.css({
				overflow: 'hidden',
				position: 'absolute',
				top: '0',
				left: '0',
				height: '200px',
				float: 'none'
			}).filter('.bio-info')
				.css({
					left: '220px',
					width: '630px',
					overflow: 'auto',
					whiteSpace: 'normal',
					padding: '5px 15px 0 15px'
			}).end()
				.filter('.photo')
				.css('width', '200px')
				.end()
				.filter('.caption')
					.css({
						position: 'static',
						paddingTop: '4px',
						height: '37px',
						lineHeight: '37px',
						width: '200px',
						marginTop: '-37px',
						background: '#fff',
						opacity: 0.7,
						fontSize: '.73em'
					})
					.find('h4, h5')
						.removeClass('hidden')
						.css('margin', 0);

	
});


