/* INITIALIZE
---------------------------------------------------------------------- */
sp_base = 'http://localhost/sportspave/';
//sp_base = 'http://betapave.com/';
//sp_base = 'http://sportspave.com/';

function initAll() {
	$('a.dialogform').click(dialogForm);	
	$('a.dialogclose').live('click', dialogClose);	
	$('a.cancel-form').live('click', cancelForm);
	$('.timeago').timeago();
	messageScroll();
	countChars();
	elasticText();
	inviteList();
	datePicker();
}

/* MAIN PROCESSING FACILITY
---------------------------------------------------------------------- */	
function submitform(form, beforeSubmit, success, reset, iframe) {	
	var options = {
		beforeSubmit: function() {
			startThinking(form);
			beforeSubmit;
		},
		data: { 'rand': Math.floor(Math.random() * 99999) },
		dataType: 'json',
		success: function(data) {
			stopThinking(form);
			success(data, $(form));
		}, 
		resetForm: reset, 
		iframe: iframe 
	};
	$(form).ajaxSubmit(options);
}

function postData(e, url, params, callback, dataType)
{
	e.preventDefault();
	$.post(url, params, function(data) {
		if(callback) callback(data, e);
	}, dataType);	
}

function saveData(url, params, callback)
{
	$.post(sp_base + url, params, function(data) {
		if(callback) callback(data);
	});	
}
	
// Posting a message
function post_msg(data, $theform) {
	var $msgarea = $theform.children('.form-msg-area');
	$msgarea.stop();
	$msgarea.html(data.msg).show();
	if(!data.error) $msgarea.animate({ opacity: 1 }, 3000, function() { 
		$(this).slideUp(400); 
	});
}

// thinking...
function startThinking(form) {
	$(form).find(':submit').attr('disabled', 'disabled');
	$(form).animate({ opacity: .4 }, 300);
}

// thinking...
function stopThinking(form) {
	$(form).find(':submit').attr('disabled', '');
	$(form).animate({ opacity: 1 }, 300);
}

/* NAVIGATION and such
---------------------------------------------------------------------- */
function homeOn(e) {
	$(e.target).siblings('em').show();
}

function homeOff(e) {
	$(e.target).siblings('em').hide();
}

// tabbed content
function tabbedNav() {
	var settings = { start:0, change:false };
	$("#tabbed").idTabs(settings,false);
}

/* FORMS, etc.
---------------------------------------------------------------------- */
function ajaxifyForms() {
	$('#right form').prepend('<input type="hidden" name="a" value="1" />');
}

function cancelForm(e) {
	e.preventDefault();
	var $thelink = $(e.target);
	$thelink.parents('.node-box-inner').hide(200, function() { $thelink.remove(); });
}

// dialogForms
function dialogForm(e, height) 
{
	e.preventDefault();
	var $thelink = $(e.target);
	
	var newbox = $('#container').append('<div id="dialog"></div>');
	$('#dialog').load( $thelink.attr('href'), { a: 1 }, function() {
		$(this).dialog({
			bgiframe: true,
			modal: true,
			height: height,
			width: 550,
			open: initDynForm,
			close: function(event, ui) {
				$(this).remove();
			},
			hide: 'fade',
			zIndex: 1
		});
	});
}

function dialogBox(e, box, height, buttons) 
{
	e.preventDefault();
	var $thebox 	 = $(box);
	var $theboxclone = $(box).clone(true);
	
	$theboxclone.dialog({
		bgiframe: true,
		modal: true,
		height: height,
		width: 550,		
		hide: 'fade',
		zIndex: 1,
		buttons: buttons,
		close: function(event, ui) {
			$thebox.replaceWith( $(this).hide() );
		}
	});
}

function dialogClose(e) {
	e.preventDefault();
	$('#dialog').dialog('close').remove();
}

function initDynForm() {
	addExamples();
	countChars();
	elasticText();
	inviteList();
	datePicker();
}

function changeFlag(e) {
	var $theselect = $(e.target);
	var c = $theselect.val();
	$theselect.next('img').attr('src', '../assets/img/flags/'+c+'.png');
	fetchRegions(e);
}

function updateYears(e) {
	var $theselect = $(e.target);
	var year 	   = $theselect.val();
	var yearIndex  = $theselect.children(':selected')[0].index + 1;
	$('#year-ended').val(year).children('option').show();
	$('#year-ended').children('option:gt('+yearIndex+')').hide();		
}

function fetchRegions(e) {
	var $theselect  = $(e.target);
	var $thearea	= $theselect.parents('form').find('.regions-area');
	var n = $theselect.val();
	$.post(sp_base + 'ajax/fetch_regions/'+n, { 'country': n }, function(data) {
		if(data!='') {
			$thearea.show().children('select').html(data);
		} else {
			$thearea.hide();
		}
	});
}
	
// Form spiffiness.
function addExamples() {
	$(':input[title]').livequery( function() {
		$(this).example( function() {
			return $(this).attr('title');
		});
	});
}

function countChars() {	
	$(".count-chars").livequery( function() {
		$(this).charCounter(2000, {  container: '.charcount' });
	});
}

function elasticText() {
	$(".elastic-text").elastic();	// don't load for AJAX forms
}

/* MESSAGES
---------------------------------------------------------------------- */
// Profile updates - success
function send_message_success(data, $theform) {
	if(!data.error) {
		window.location.href = data.redirect;
	} else {
		post_msg(data, $theform);	
	}
}

function delete_messages_success(data, $theform) {
	if(!data.error) {
		$('input[name="node[]"]:checked').parents('dl').hide(500);
		$('form').resetForm();
	}	
}

function messageScroll() {
	if($('#messages-area').length>0) {
		$.scrollTo( 0, {
			axis: 'y',
			onAfter: function() {
				$.localScroll.hash({
					duration: 700,
					easing: 'easeOutExpo'
				});
			}
		});
	}
}

/* GAMEBOARD
---------------------------------------------------------------------- */
// Profile updates - success
function send_gameboard_success(data, $theform) {
	if(!data.error) {
		window.location.href = data.redirect;
	} else {
		post_msg(data, $theform);	
	}
}

/* PAVEMENT
---------------------------------------------------------------------- */
// Profile updates - success
function send_comments_success(data, $theform) {
	if(!data.error) {
		window.location.href = data.redirect;
	} else {
		post_msg(data, $theform);	
	}
}

/* FANS, STARS, etc.
---------------------------------------------------------------------- */
function fanAction(e) {
	e.preventDefault();
	var $thelink = $(e.target);
	$.post(this.href, { 'a': 1 }, function(data) { 
		if(!data.error) {
			//$('strong#star-count-total').text(data.count);
			$thelink.parent().fadeOut(300, function() {
				$(this).replaceWith(data.msg).fadeIn(500);
			});			
		} else {
			alert(data.msg);
		}
	}, "json");
	return false;		
}
function starAction(e) {
	e.preventDefault();
	var $thelink = $(e.target);
	$.post(this.href, { 'b': 1 }, function(data) { 
		if(!data.error) {
			//$('strong#star-count-total').text(data.count);
			$thelink.parent().fadeOut(300, function() {
				$(this).replaceWith(data.msg).fadeIn(500);
			});			
		} else {
			alert(data.msg);
		}
	}, "json");
	return false;		
}
function send_invites_success(data, $theform) {
	if(!data.error) {
		$('#skinny').html(data.html);
	}
	else {
		post_msg(data, $theform);
	}
}

/* SETTINGS
---------------------------------------------------------------------- */	
// Profile updates - success
function update_settings_success(data, $theform) {
	post_msg(data, $theform);	
	if(!data.error) {
		if(data.image) {
			$('.p-img-area').html(data.new_img_lg).contents().fadeIn(500);
			$('#profile-img img').replaceWith(data.new_img_sm);
		}
	}
}

// Remove a subscription
function removeSubRow($thelink) {
	var url = $thelink.attr('href');
	$.post($thelink.attr('href'), { a: 1 }, function(data) {
		if(!data.error) {	
			$thelink.parents('.item-row').animate({ height: 'hide', opacity: 'hide' }, 500, function() {
				$(this).remove();
			});
		} else {
			$thelink.closest('.row-area').prepend('<p class="error">'+data.msg+'</p>');
		}
	}, 'json');
}

function removeSubscription(e) {
	var buttons = 
	{
		'Unsubscribe?': function() {
			removeSubRow($(e.target));
			$(this).dialog('close');
		},
		Cancel: function() {
			$(this).dialog('close');
		}
	};
	dialogBox(e, '#unsubscribe-confirm', 220, buttons);
}

/* TEAMS
---------------------------------------------------------------------- */
function joinAction(e) {
	e.preventDefault();
	var $thelink = $(e.target);
	var url = this.href;
	$.post(url, {a: 1}, function(d) { 
		if(!d.error) {
			$('span#team-status').text(d.html);
			$thelink.fadeOut(300, function() {
				$(this).replaceWith(d.msg).fadeIn(500);
			});			
		} else {
			alert(d.msg);
		}
	}, "json");
}
	
// Find team - success
function find_team_success(data, $theform) {
	if(!data.error) {
		$theform.find('.form-msg-area').empty();
		if(data.msg=='create') {
			$('.node-result-box').empty();
			$('.node-create-box').html(data.html);
		}
		else {
			$('.node-create-box').empty();
			$('.node-result-box').html(data.html);
		}
	}
	else {
		post_msg(data, $theform)
	}	
}
	
// Create team - success
function create_team_success(data, $theform) {
	if(!data.error) {
		$theform.find('.form-msg-area').empty();
		window.location.href = data.url;
	} else {
		post_msg(data, $theform);
	}	
}

function save_privileges_success(data, $theform) {
	post_msg(data, $theform);	
}

// Team invite - success
function team_invite_success(data, $theform) {
	if(!data.error) {
		$theform.find('label, ul').hide();		
	}
	post_msg(data, $theform);
}

/* LEAGUES
---------------------------------------------------------------------- */	
// Find league - success
function find_league_success(data, $theform) {
	if(!data.error) {
		$theform.find('.form-msg-area').empty();
		if(data.msg=='create') {
			$('.node-result-box').empty();
			$('.node-create-box').html(data.html);
		}
		else {
			$('.node-create-box').empty();
			$('.node-result-box').html(data.html);
		}
	}
	else {
		post_msg(data, $theform);
	}	
}
	
// Create league - success
function create_league_success(data, $theform) {
	if(!data.error) {
		$theform.find('.form-msg-area').empty();
		window.location.href = data.url;
	} else {
		post_msg(data, $theform);
	}	
}

/* CALENDARS and EVENTS
---------------------------------------------------------------------- */
function filterSubscriptions(e)
{
	dialogBox(e, '#calendar-filters', 450);
}

// Set a filter status
function setSubscriptionFilter(e)
{
	var thiscal = window.location.pathname.split('/').pop();
	var cid = $(this).val();
	if($(this).is(':checked'))
	{
		$('div.cal-'+cid).slideDown().removeClass('f-cal-row-hidden');
		$(this).parent().removeClass('filter-off');
	}
	else {
		$('div.cal-'+cid).slideUp().addClass('f-cal-row-hidden');
		$(this).parent().addClass('filter-off');
	}
	var ids = [];
	var vals = $(this).parents('ul').find(':checked').serializeArray();
	jQuery.each(vals, function(i, cb) {
		ids[i] = cb.value;
	});
	saveData('calendar/save_subscription_filters/'+thiscal, { 'a' : 1, 'ids[]' : ids });
}

function subscribeAction(e) {
	e.preventDefault();
	var $thelink = $(e.target);
	$.post(this.href, { 'a': 1 }, function(data) { 
		if(!data.error) {
			$thelink.fadeOut(300, function() {
				$(this).attr('href', data.url).text(data.msg).fadeIn(500);
			});			
		} else {
			alert(data.msg);
		}
	}, "json");
	return false;		
}

// New event - success
function add_event_success(data, $theform) {
	var pm = post_msg(data, $theform);
	if(!data.error) {
		window.location.href = data.full_uri;
	}
}

function eventsOver(e) {
	var $theevent = $(e.target);
	$theevent.addClass('f-cal-hover');
	/*
	if($(this).find('.f-cal-title').text() == '') {
		var $theevent = $(this);
		var w = $theevent.outerWidth();
		var offset = $theevent.offset();
		var $floater = $theevent.children('.float-title').css({ top: offset.top+2, left: offset.left+w+10 });		
		$floater.fadeIn(200).addClass('float-show');
	}
	*/	
}

function eventsOff(e) {
	var $theevent = $(e.target);	
	$theevent.removeClass('f-cal-hover');
	//$('.float-show').hide();		
}

function toggleInviter(e) {
	$(e.target).is(':checked') ? $('#invite-area').addClass('invite-area-show') : $('#invite-area').removeClass('invite-area-show');
}

function inviteList() {	
	// "Invite" autocomplete	
	$("#invite").autocomplete(
		sp_base + "ajax/lookup_name", 
		properties = {
			maxItems: 20,
			max_limit: "You've reached the limit of invitees.",
			matchContains: true,
			minChars: 2,
			selectFirst: false,
			intro_text: "Type Name",
			no_result: "No Names"
		}
	);
}

function removeInvite(e) {
	postData(e, $(e.target).attr('href'), { a: 1 }, removeInviteSuccess, 'json');
}

function removeInviteSuccess(data, e)
{
	if(!data.error)
	{-
		$(e.target).parent().fadeOut(1000, function() {
			$(this).remove();	
		});
	}
}

// Date-range pickers
function datePicker() {
	var sd;
	var ed;
	
	$('#event_start').datepicker({
		constrainInput: true,
		numberOfMonths: 3,
		showButtonPanel: true,
		onSelect: function(dateText) {
	    	sd = $(this).datepicker("getDate");	    	
	    	$('#event_end').datepicker('setDate', sd);
	    	$('#event_end').datepicker('enable');
	  	}
	});
	
	$('#event_end').datepicker({
		beforeShow: customRange,
		constrainInput: true,
		numberOfMonths: 3,
		showButtonPanel: true
	});
	
	//if($('span#eid').length==0) $('#event_end').datepicker('disable');	
}

function customRange(input) {
	if($('span#eid').length==0)
	{
		return {
			minDate: $(this).datepicker("getDate")
		}
	}
	else {
		return {
			minDate: $('#event_start').datepicker("getDate")
		}
	}
}
		

/*----------------------------------------------------------------------
And go...
---------------------------------------------------------------------- */

jQuery(function() {
	// Set some defaults.
	jQuery.easing.def = "easeInOutExpo";
	
	/*
	---------------------------------------
	Initialize
	---------------------------------------
	*/
	
	initAll();
	ajaxifyForms();
	addExamples();
	tabbedNav();
		
  	/*
	---------------------------------------
	Navigation
	---------------------------------------
	*/	
	// Main nav, show "Home"
  	$('#session-nav li.username a').hover(homeOn, homeOff);
	
	/*
	---------------------------------------
	Form functions
	---------------------------------------
	*/
	// toggle checkboxes
	$('#toggle-checks').click( function() {
		var chk = $(this).is(':checked') ? 'checked' : '';
		$(':checkbox').attr('checked', chk);
	});
	
	$('.check-regions').change(fetchRegions);
	
	/*
	---------------------------------------
	Messages / Inbox
	---------------------------------------
	*/	
	// "To" autocomplete	
	$("#to").autocomplete(
		sp_base + "ajax/lookup_name", 
		properties = {
			maxItems: 20,
			max_limit: "You've reached the limit of recipients.",
			matchContains: true,
			minChars: 2,
			selectFirst: false,
			intro_text: "Type Name",
			no_result: "No Names"
		}
	);
	
	// Send message
	$('#form-send-message').submit( function() {
		submitform(this, null, send_message_success, false, false);
		return false;
	});
	
	// Delete messages
	$('#form-delete-messages').submit( function() {
		submitform(this, null, delete_messages_success, false, false);
		return false;
	});

	/*
	---------------------------------------
	Game Board
	---------------------------------------
	*/	
	// Send message
	$('#form-send-gameboard').submit( function() {
		submitform(this, null, send_gameboard_success, false, false);
		return false;
	});
	
  	/*
	---------------------------------------
	User Profiles
	---------------------------------------
	*/
  	
  	// team description expander
  	$('.group-desc').expander({  		
		expandEffect: 'fadeIn', 
  		expandText: ' [read more...]',
		slicePoint: 80, 
		userCollapseText: '[x]'
	});
	
	/*
	---------------------------------------
	Stars
	---------------------------------------
	*/	
	// first they giveth, then they taketh away.
	$('a#fan-action').live('click', fanAction);
	$('a#star-action').live('click', starAction);
	/*
	---------------------------------------
	Media Ticker
	---------------------------------------
	*/
	
	// Selecting a media type
	$('#mh a').click( function() {
		var t = $(this).attr('rel');
		var m = $('#'+t).clone(true).show();
		$('#add-m-e').empty();
		$('#add-m-i').html(m);
		$('#add-m').fadeIn(300);
		$('input[name="m"]').val(t);
		addExamples();
		$("#m-text").charCounter(140, { container: '#m-text-count', format: "%1" });
		$("#m-quote").charCounter(140, { container: '#m-quote-count', format: "%1" });
		return false;
	});	
	
	// Cancelling media
	$('.m-cancel').click( function() {
		$('#add-m').hide().children('form').clearForm();
		return false;
	});
	
	// Add media
	$('#add-m form').ajaxForm({
		beforeSubmit: function(a,f,o) {
        },
        dataType: 'json',
		success: function(d) {
			if(d.error) {
				$('#add-m-e').html(d.msg).show();
			}
			else {
				$('#add-m-e').empty();
				var newm = $(d.html).fadeIn(300);
				$('.m-empty, #add-m').animate({ height: 'hide', opacity: 'hide' }, 500, function() {
					$('.m-empty').remove();
					$('#form-add-media').clearForm();
					$('#mb').prepend(newm);
				});
			}
		}
	});
	
	$('.m-d').click( function() {
		var thismu = $(this);
		$.ajax({ 
			url: "media/delete_media/"+$(thismu).parents('.munit')[0].id,
			type: 'post',
			success: function(d) { 
				if(!d.error) {
					$(thismu).parents('.munit').animate({ height: 'hide', opacity: 'hide' }, 700, function() {
						$(this).remove();
					});	
				}
			},
			dataType: 'json'
		});		
	});
	
  	/*
	---------------------------------------
	Teams
	---------------------------------------
	*/	
	// Create team
	$('#form-create-team').live('submit', function() {
		submitform(this, null, create_team_success, false, false);
		return false;
	});
	
	// Save team privileges
	$('#form-save-privileges').submit( function() {
		submitform(this, null, save_privileges_success, false, false);
		return false;
	});
	
	// first they giveth, then they taketh away.
	//$('a.join-action').live('click', joinAction);
	
	// Team invite
	$('#form-team-invite').submit( function() {
		submitform(this, null, team_invite_success, true, false);
		return false;
	});
	
  	/*
	---------------------------------------
	Leagues
	---------------------------------------
	*/	
	// Create league
	$('#form-create-league').live('submit', function() {
		submitform(this, null, create_league_success, false, false);
		return false;
	});
	
	/*
	---------------------------------------
	Profile / Settings Edits
	---------------------------------------
	*/	
	// region helper / dynamic flag for country
	$('p.dynaflag select').change(changeFlag);
	
	// year helper
	$('#year-started').change(updateYears);
	
	// Profile updates	
	$('form.form-settings').submit( function() {
		submitform(this, null, update_settings_success, false, false);
		return false;
	});
	
	// Subscription management
	$('.unsubscribe').click(removeSubscription);
	
	/*
	---------------------------------------
	Calendar / Events
	---------------------------------------
	*/
	// first they giveth, then they taketh away.
	$('a#subscribe-action').live('click', subscribeAction);
	
	// Open subs filters
	$('a#filter-subs').click(filterSubscriptions);
	
	$('#filters-list :checkbox').click(setSubscriptionFilter);
	
	// Inviter toggler
	$('#private').live('click', toggleInviter);
	
	// New event	
	$('#form_add_event').live('submit', function() {
		submitform(this, '', add_event_success, false, false);
		return false;
	});
	
	// Remove an invitee
	$('.remove-invite').click(removeInvite);
	
	// Event rollovers
	$('p.f-cal-event').hover(eventsOver, eventsOff);
	
	/*
	---------------------------------------
	Invite
	---------------------------------------
	*/	
	$('#form-send-invites').submit( function() {
		submitform(this, null, send_invites_success, false, false);
		return false;
	});
	
});
