var FM = {
	geo: {}
};

(function($, FM, window) {

	FM.getGeo = function(callback) {

		var geo_json;
		if (geo_json = Pie.cookie('fm_geo')) {
			FM.geo = JSON.parse(geo_json);
			if (typeof(callback === 'function')) {
				callback(FM.geo);
			}
			return;
		}

		Pie.addScript("http://j.maxmind.com/app/geoip.js", function() {
			FM.geo = {
				"country_name": geoip_country_name(),
				"city": geoip_city(),
				"region": geoip_region(),
				"region_name": geoip_region_name(),
				"latitude": geoip_latitude(),
				"longitude": geoip_longitude(),
				"postal_code": geoip_postal_code()
			};

			var geo_json = JSON.stringify(FM.geo);
			Pie.cookie('fm_geo', geo_json);

			// TODO: save this in a cookie that expires soon

			if (typeof callback === 'function') {
				callback(FM.geo);
			}
		});
		
	}
	
	FM.activatePlaceholders = function(jq) {
		var detect = navigator.userAgent.toLowerCase();
		if(detect.indexOf("safari") > 0)
			return;
		function activatePlaceholder() {
			var $this = $(this);

			var plch = $this.attr('placeholder');
			if(!(plch))
				return;

			$this.focus(function(){
				var $t = $(this);
				if($t.attr('value') == $t.attr('placeholder')
				|| $t.attr('value') == '') {
					$t.attr('value', '');
					$t.removeClass('placeholder');
				}
			}).blur(function(){
				var $t = $(this);
				if(!$t.attr('value')) {
					$t.attr('value', $t.attr('placeholder'));
					$t.addClass('placeholder');
				}
			});

			if(!$this.attr('value')) {
				if (document.activeElement !== this) {
					$this.attr('value', plch);
					$this.addClass('placeholder');
				}
			}
		}
		if (jq && jq.jquery) {
			$('input', jq).add('textarea', jq).each(activatePlaceholder);
		} else {
			$('input').add('textarea').each(activatePlaceholder);
		}
	}
	
	FM.login = function(options) {
		if (!options) {
			options = {};
		}
		if (typeof options === 'function') {
			options.onSuccess = arguments[0];
			if (arguments.length > 1) {
				options.onRequireComplete = arguments[1];
			}
		}
		var o = {
			onSuccess: function(response) {
				if (options.onSuccess) {
					Pie.handle(options.onSuccess);
				}
				window.location = Pie.urls['fm/profile'];
			},
			onRequireComplete: function(response) {
				if (options.onRequireComplete) {
					Pie.handle(options.onRequireComplete);
				}
				window.location = Pie.urls['fm/profile']; // + '?edit&incomplete';
			},
			accountStatusUrl: Pie.url('/api/accountStatus'),
			using: 'native,facebook'
		};
		Pie.Users.login(o);
	}
	
	FM.logout = function(options) {
		var o = $.extend({
			onSuccess: function(response) {
				window.location = Pie.url();
			},
			using: 'facebook'
		}, options);
		Pie.Users.logout(o);
	}
	
	function jQueryToolsSetup() {
		var conf = jQuery.tools.overlay.conf;
		conf.closeOnClick = false;
		conf.closeOnEsc = true;
		conf.color = '#eee';
		conf.top = 80;
		conf.onClose = function () {
			$('*', $(this)).trigger('closingOverlay.fm');
		};
		conf.oneInstance = true;
		if (!$.browser.msie) {
			conf.mask = {
				color: conf.color, //$('body').css('background-color'),
				loadSpeed: 200,
				opacity: 0.30
			};
		} else {
			conf.closeOnClick = true;
		}
		var conf2 = jQuery.tools.tooltip.conf;
		conf2.effect = 'fade';
		conf2.opacity = 0.9;
		conf2.position = "bottom center";
		conf2.offset = [0, 0];
		var conf3 = jQuery.tools.validator.conf;
		conf3.errorClass = 'pie_errors';
		conf3.messageClass = 'pie_error_message';
		conf3.position = 'bottom left';
		conf3.offset = [-5, 0];
	}
	
	function onWindowResize() {		
		
		return;

		if (!onWindowResize.firstContentSlotWidth) {
			onWindowResize.firstContentSlotWidth = $('#content_slot').outerWidth();
			onWindowResize.firstContentSlotHeight = $('#content_slot').outerHeight();
			onWindowResize.firstContentWidth = $('#content').width();
			onWindowResize.firstContentHeight = $('#content').height();
			onWindowResize.minContentSlotHeight = h2 - $('#page').offset().top * 2;
		}

		var width = $('#sidebar_slot').outerWidth(true);
		var height = $('#content_slot').outerHeight(true);
		if ($('#notices_slot').length) {
			height += $('#notices_slot').outerHeight(true);
		}
		$('#sidebar_slot').height(height);
		
		var w = $(this).width();
		if (w < onWindowResize.firstContentSlotWidth + width) {
			$('#sidebar_slot').hide();
			$('#page').css('width', '840px');
			$('#content_slot').css('width', '840px');
			$('#content').css('width', '840px');
			$('#notices_slot').css('width', '840px');
		} else {
			$('#sidebar_slot').show();
			$('#page').css('width', '960px');
			$('#content_slot').css('width', '840px');
			$('#content').css('width', '840px');
			$('#notices_slot').css('width', '840px');
		}
		
		
		return;
		
		var cs = $('#content_slot');
		var c = $('#content');
		var h = $(this).height();
		var h2 = h - $('#footer').outerHeight(true) - cs.offset().top;
		
		if (!onWindowResize.firstContentSlotWidth) {
			onWindowResize.firstContentSlotWidth = $('#content_slot').width();
			onWindowResize.firstContentSlotHeight = $('#content_slot').height();
			onWindowResize.firstContentWidth = $('#content').width();
			onWindowResize.firstContentHeight = $('#content').height();
			onWindowResize.minContentSlotHeight = h2 - $('#page').offset().top * 2;
		}
	
		if (cs.height() >= h2) {
			cs.height(h2);
		} else if (cs.height() < c.height()) {
			cs.height(c.height() + 30);
		}
		
		var nice_height = c.height();
		if (cs.height() >= h2) {
			cs.height(h2);
		} else if (cs.height() < nice_height) {
			cs.height(nice_height);
		}
		
		var width = $('#sidebar_slot').outerWidth(true);
		var height = $('#content_slot').outerHeight(true);
		if ($('#notices_slot').length) {
			height += $('#notices_slot').outerHeight(true);
		}
		$('#sidebar_slot').height(height);
		
		var w = $(this).width();
		if (w < onWindowResize.firstContentSlotWidth + width) {
			if (w < onWindowResize.firstContentSlotWidth) {
				$('#content_slot').width(w);
				$('#notices_slot').width(w);
				$('#sidebar_slot').hide();
				$('#content_slot').css('overflow', 'auto');
				$('html').css('overflow', 'hidden');
			} else if ($('#sidebar_slot').length) {
				$('#content_slot').width(w-width);
				$('#notices_slot').width(w-width);
				$('#content_slot').css('overflow-x', 'auto');
				$('html').css('overflow-x', 'hidden');
				$('#sidebar_slot').show();
			}
		} else {
			$('#content_slot').width(onWindowResize.firstContentSlotWidth);
			$('#notices_slot').width(onWindowResize.firstContentSlotWidth);
			$('#content_slot').css('overflow-x', 'hidden');
			$('html').add('body').css('overflow', 'visible');
			$('#sidebar_slot').show();
		}
	}
	
	function effects() {
		function onSubmit(event) {
			var $this = $(this);
			var serialized = $this.serialize();
			
			if ($this.data('fm-lastSerialized') === serialized) {
				// prevent lightning-fast resubmission of forms, until they change
				return false;
			}
			
			var button = $('button[type=submit]', $this).eq(0);
			button.addClass('active');
			setTimeout(function() {
				button.removeClass('active');
			}, 150);
			
			$this.data('fm-lastSerialized', serialized);
			
			function reset () {
				$this.data('fm-lastSerialized', false);
			}
			
			setTimeout(reset, 1000);
			$this.blur(reset);
		}
		
		var $oldHandle = $.event.handle;
		$.event.handle = function(event) {
			var namespaces = event.type.split(".");
			var type = namespaces.shift();
			event = jQuery.event.fix(event || window.event);
			if (type === 'submit') {
				if (event.target && onSubmit.call(event.target, event) === false) {
					event.preventDefault();
					event.stopPropagation();
					return false;
				}
			}
			$oldHandle.apply(this, arguments);
		}
		
		var state = 0;
		var duration = 100;
		$('#dashboard_slot').mouseenter(function() {
			$(this).animate({'opacity': 1});
		}).mouseleave(function () {
			$(this).animate({'opacity': (state ? 0.9 : 1)})
		});
		$(window).bind('scroll resize', function() {
			if ($(window).scrollTop() > 35) {
				if (state == 0) {
					duration = 0;
					$('#dashboard_slot')
					.animate({'opacity': 0.9}, duration, function() {
							$(this).addClass('compact')	
					});
				}
				state = 1;
			} else {
				if (state == 1) {
					duration = 50;
					$('#dashboard_slot').animate({'opacity': 1}, duration, function () {
						$(this).removeClass('compact')
					});
				}
				state = 0;
			}
		});
		
		if ($('#dashboard .user_username').text().trim().length > 10) {
			$('#dashboard_user_status').css('font-size', '12px');
		}
		
	}
	
	$(function() {
		$('#footer .acknowledgments').html(
			"This site uses <a target='_blank' href='http://www.maxmind.com/app/javascript_city'>MaxMind</a> for GeoIP"
		);
		
		$('.login').click(function() { FM.login(); return false; });
		$('.logout').click(function() { FM.logout(); return false; });
		
		$('form').live('submit', function() {
			
		});
		
		var right = $('#dashboard_user_status').length
			? $('#dashboard_user_status')
			: $('#dashboard_login');
		var t_width = right.offset().left - $('#dashboard_toolbar').offset().left - 20;
		$('#dashboard_toolbar').add('#dashboard_toolbar table').width(t_width);
		$('#dashboard_toolbar table').css('table-layout', 'auto');
		
		effects();
		
		jQueryToolsSetup();
		
		//setInterval(onWindowResize, 100);
		$(window).resize(onWindowResize);
		
		// delay the following, in case some document.ready handler
		// wants to set the values of textboxes to ""
		setTimeout(FM.activatePlaceholders, 100);
	});
	
})(jQuery, FM, window);

