(function($){
	$.fn.avaTip = function(){
		return this.each(function() {
			var avatar = this,
					attr = ( $(this).find('a').attr("rel") )? $(this).find('a').attr("rel").split(',',3) : undefined;
			
			if(attr !== undefined) {
				var name = attr[0],
						img = attr[1],
						key = attr[2];
				
				$(this).hover(function(e){

					if (avatar.ignore === true) { return; }
					
					//create html
					var html = '';
					if (img) { html += '<img src="'+img+'" />'; }
					html += '<div class="rollover_content"><p class="name">'+name+'</p></div>';
					
					$("body").append("<div class='avatar_rollover'>" + html + "</div>");
					this.rollover = $('.avatar_rollover:last');
					var rollover = this.rollover;
					//load additional data via ajax
					if (key && !$(this).data('user')) {
						$.getJSON('/ajax/users/getUserData', {'key':key}, function(data) {
							if (data.status == 'error') { return; }
							//tell it to ignore updates
							avatar.ignore = true;
							// Build and store user data
							$.fn.avaTip.buildUserStats(rollover,data);
							$(avatar).data('user',data);
							//update position and re-support outtro
							$('body').trigger('mousemove');
							avatar.ignore = false;
						});
					}
					// load additional data without ajax
					if (key && $(this).data('user')) {
						$.fn.avaTip.buildUserStats(rollover,$(this).data('user'));
					}
					
					$(".avatar_rollover").css( $.fn.avaTip.edge(e.pageX,e.pageY) ).fadeIn("slow");
				}, 
				function(){
					$(".avatar_rollover").remove();
				});
				$(this).mousemove(function(e){
					$(".avatar_rollover").css( $.fn.avaTip.edge(e.pageX,e.pageY) ).fadeIn("slow");
				});
			}
		});
	};
	$.fn.avaTip.buildUserStats = function (rollover,data) {
		var html = '<div class="more">';
		if (data.location && data.location != 'null') { html += '<p class="location">'+data.location+'</p>'; }
		html += '<p class="stat views">Views: '+data.views_sum+'</p>' +
						'<p class="stat points">Points: '+data.points_sum+'</p>' +
						'<p class="stat friends">Friends: '+data.friends_sum+'</p>' +
						'<p class="stat posts">Posts: '+data.forum_posts_sum+'</p>' +
						'</div>';

		$(rollover).find('.rollover_content').append(html);

		//update position and re-support outtro
		$('body').trigger('mousemove');
	};
	$.fn.avaTip.edge = function(pageX,pageY){
		
				// setting up tolerances here should make this configurable 
		var tolerance = {x:240,y:100},
				$w = $(window),
				// pageX relative to window
				screenPos = { x:pageX-$w.scrollLeft(), y:pageY-$w.scrollTop() },
				css = {};
		css.left = ( $w.width() - screenPos.x <= tolerance.x )? pageX - 230 : pageX+12;
		css.top = ( $w.height() - screenPos.y <= tolerance.y )? pageY - 120 : pageY+12;
		return css;
	};
	//display engine messages fixed and centered
	$.fn.fixedCenter = function(){
		return this.each(function(){
			var element = $(this),
					centerElement = function(){
						var elementWidth = element.outerWidth(),
								elementHeight = element.outerHeight(),
								X2 = window.innerWidth/2 - elementWidth/2,
								Y2 = window.innerHeight/2 - elementHeight/2;
					element.css({'left':X2,'top':Y2, 'position':'fixed'});
				};
				
			centerElement();
			$(window).bind('resize',function(){
				centerElement();
			});
		});
	};
})(jQuery);

//--------------
//UTILS

//gotoUrl another page
function gotoUrl(url) {
	window.location = url;
}

//load a JS include
function require(path) {
	$(document).append('<script type="text/javascript" src="'+path+'"><\/script>');
}

//call a jsonp API from flash, like for twitter.  Robert has a demo.
function jsonp(api, swf_id) {
	$.getJSON(api, function(data, status) {
		document.getElementById(swf_id).jsonp(data);
	});
}

//show the splash page if they haven't seen it yet
function showSplash(splash_days_till_expire) {
	
	//if expire is 0, set to null, which will make it a session cookie
	if (parseInt(splash_days_till_expire) == 0 || !splash_days_till_expire) splash_days_till_expire = null;
	
	if (
	  window.location.pathname != '/' || //only show splash on homepage requests
	  $.cookie('splash_set') == 1 || //check if cookie is set
	  window.location.protocol == 'https:' //don't show the splash on https pages, this would happen when switching to checkout
	) return;
	
	//set cookie and redirect
	$.cookie('splash_set', 1, {
	  expires: splash_days_till_expire,
	  path: '/'
	});
	gotoUrl('/splash');

}

//--------------
//DASHBOARD

//toggle dashboard
function toggleDashboard(event) {
	//get element
	event.preventDefault();
	var dash = $('#dashboard');
	//close
	if (dash.data('open') === 1) {
		dash.animate({marginTop: dash.data('offset')}, 300).data('open', 0);
	//open
	} else {
		dash.animate({marginTop: '0px'}, 300).data('open', 1);
	}
	//save state
	$.cookie('dashboard_open', dash.data('open'), { expires: 14, path: '/' });
}

//init the dashboard
function initDashboard() {
	
	var el = $('#dashboard');

	//get ref
	if (el.length === 0) { return; }
	
	//respect choice
	if (!el.find('a.toggle'))  { return; } //if they're not logged in, there won't be this button
	el.find('a.toggle').click(toggleDashboard);
	el.data('offset', el.css('margin-top'));
	if ($.cookie('dashboard_open') == 1) {
		el.css('margin-top','0px');
		el.data('open', 1);
	}
}

//--------------
//INITIALIZE

//this adds observers to hooks in pages
function init() {

	//toggle the dashboard
	initDashboard();

	//add avatar rollovers
	$('span.avatar_wrapper').avaTip();
	
	$('#GC.GC_engine').fixedCenter();

	//hide engine messages
	if ($('#GC.GC_engine, #engine').length > 0) {
		setTimeout(function() {
			$('#GC.GC_engine:has(.success)').fadeOut();
		}, 5000);
		$('#GC.GC_engine button.close, #engine .close, #engine [name="close"]').click(function(e) {
			e.preventDefault();
			$('#GC.GC_engine, #engine').fadeOut();
		});
	}
	
	//hide inlinde errors
	$('#GC form li').click(function(){
		$(this).find('.error').fadeOut('fast');
	});
	
	//make redirect pulldown menus work
	$('select.redirect').change(function() {
		gotoUrl($(this).val());
	});
	
	//remove default value on click for login inputs
	$('label[for=email]:hidden').next('input#email').val('Email').focus(function () {
		if ($(this).val() == 'Email') { $(this).val(''); }
    }).blur(function() {
		if ($(this).val() === '') { $(this).val('Email'); }
	});
	$('label[for=password]:hidden').next('input#password').val('Password').focus(function () {
		if ($(this).val() == 'Password') { $(this).val(''); }
    }).blur(function() {
		if ($(this).val() === '') { $(this).val('Password'); }
	});
	
	// Check all
	$('#check_all').click(function() { $("input.multicheck").attr('checked', $('#check_all').is(':checked')); } );
	$("#GC_friend_action").submit(function(event) {
		var submit_button = $("button#Go").attr("disabled", "disabled");
		submit_button.find("span").text("Processing...");
	});

	// Fancybox
	if($.isFunction($.fn.fancybox)) {
		$.fn.fancybox.defaults.padding = 0;
		$.fn.fancybox.defaults.overlayColor = '#000';
		$.fn.fancybox.defaults.overlayOpacity = 0.8;
		$.fn.fancybox.defaults.centerOnScroll = true;
		$.fn.fancybox.defaults.scroll = false;
		
		$('a[href$=".jpg"],a[href$=".jpeg"],a[href$=".png"],a[href$=".gif"]').not('a[href*="photobucket"],a[href*="imageshack"],.ignore').fancybox({
			type			: 'image'
		});
		$('a[href*=".swf"]').fancybox({
			type			: 'swf',
			swf 			: {
				wmode			: 'transparent',
				allowfullscreen	: 'true'
			}
		});
	}
	
	var t = $("#_ctoken:first");
	if (t.length > 0) {
		t.after( $("<input>", {"type": "hidden", "name": "_gc_token", "id": "_gc_token", "value": "v"}) );
	}
}

$(function() { init(); });
