// this is a class that will control the login modal. it controls the opening and closing of said modal. 
// it also integrates itself with the events that are called by the facebook plugin we have, so that it
// can auto close when it should. it also allows for the destruction of the modal without killing the
// div that contains the content of the modal. finally, if needed, we can speify that there are multiple
// instances of this modal on the page, though this needs refining if there is actually a use for it.
(function($){
	// defaults
	var _defs = {
		single:true,
		ev:'click',
		ele:'a.sign-in',
		closebtnsel:'#close-modal',
		modalcont:'#modal-login'
	};
	var _modal_inc = 1;
	// namespace
	$.BM = $.BM || {};
	// modal constructor
	$.BM.loginModal = function(e,o) {
		this.o = $.extend({}, _defs, {author:'loushou', version:'1.0-lou'}, o);
		this.e = e;
		this.e.data('bm-login-modal', this);
		this.init();
	}
	// modal functions
	$.BM.loginModal.prototype = {
		// setup settings for the modal, like adding it to the modal list, and setting up the basic events it will use
		init: function() {
			if (this.o.single) {
				var d = $(window).data('bm-login-modals') || {__count:0};
				if (d.__count) return this.destroy();
			}
			this.o.slug = 'modal-'+(_modal_inc++);
			this._add_modal();
			this._setup_styles();
			this._setup_events();
		},
		// remove the modal from the modal list, and itself from association with the modal div, and clean up internal objects
		destroy: function() {
			this._remove_modal();
			this.o = undefined;
			this.e = undefined;
		},
		// sets up the heights and widths of all parts of the modal that are relevant
		_setup_styles: function() {
			this.e.css({height:1, width:1, 'top':-2000, 'left':0}).show();
			this.mc = $(this.o.modalcont, this.e);
			this._calc_size();
			this.e.hide();
			this._resize();
		},
		// calculate the height and width to use to move the form while the form is not visible
		_calc_size: function() {
			// store the size of the container holding the actual form because we are going to move it while it is
			// not visible also, so that when it does appear it is not jumpy
			this.hd = { // hd = hidden dimensions
				h: this.mc.outerHeight(),
				w: this.mc.outerWidth()
			};
		},
		// what happens when the user scrolls the window down, in relation to the modal
		_scroll: function() {
			var newtop = $(window).scrollTop() + (($(window).height() - this.hd.h)/2);
			var newleft = $(window).scrollLeft() + (($(window).width() - this.hd.w)/2);
			this.mc.stop().animate({'top':newtop,'left':newleft}, 300, 'linear');
		},
		// when the window is resized, we need to compensate for that
		_resize: function() {
			this.e.css({height:$(document).height(), width:$(document).width(), 'top':0, 'left':0});
			this._scroll();
		},
		// setup the events that will be used, such as to activate the modal, close the modal, and interactions between fb plugin and modal
		_setup_events: function() {
			var self = this;
			$(this.o.ele).die(this.o.ev+'.bm-login-modal').live(this.o.ev+'.bm-login-modal', function(e) { e.preventDefault(); self._show.apply(self,[]); });
			$(this.o.closebtnsel).die('click.bm-login-modal').live('click.bm-login-modal', function(e) {e.preventDefault(); self._hide.apply(self,[]);});
			$(window).bind('startauth.bmfbauth', function() { self._hide.apply(self,[]); });
			$(window).unbind('scroll.bm-login-modal').bind('scroll.bm-login-modal', function() { self._scroll.apply(self, []);});
			$(window).unbind('resize.bm-login-modal').bind('resize.bm-login-modal', function() { self._resize.apply(self, []);});
			/* $(window).bind('loginsuccess.bmfbauth', function() { self._hide.apply(self,[]); }); */
		},
		// hides the modal
		_hide: function() {
			this.e.hide();
		},
		// show the modal
		_show: function() {
			//window.scrollTo(0,0);
			//this.e.css({top:parseInt(document.body.scrollTop)}).show().css({left:Math.floor((parseInt($(document).width()) - parseInt(this.e.outerWidth())) / 2)+'px'});
			this.e.show();
			this._calc_size();
			this._resize();
		},
		// remove the modal from the list of login modals
		_remove_modal: function(name) {
			var d = $(window).data('bm-login-modals') || {__count:0};
			if (d[name] && d.__count) {
				d.__count--;
				d[name].e.hide();
				d[name].e.removeData('bm-login-modal');
				d[name] = undefined;
			}
			$(window).data('bm-login-modals', d);
		},
		// add the modal to the list of login modals
		_add_modal: function() {
			var d = $(window).data('bm-login-modals') || {__count:0};
			d[this.o.slug] = this;
			d.__count++;
			$(window).data('bm-login-modals', d);
		}
	};
	// login modal factory
	$.fn.bmLoginModal = function(o) { return this.each(function(){if (!$(this).data('bm-login-modal')) (new $.BM.loginModal($(this),o))}) };
})(jQuery);

// regardless of the existence of the modal, we want a visual indicator that the info from facebook has been recieved
// and that we are now just trying to load the account to which it is linked. the reason for this is so that the user
// does not get impatient with no visual confirmation of a login, and so that the user does not take for granted that 
// is already done, if it is not. ths block will handle that.
(function($) {
	$.BM = $.BM || {};
	$.BM.fbCommMsg = function(msg) {
		var comm = $('#facebook-communication-div').css({display:'none'});
		if ($(comm).length == 0) {
			var comm = $('<div id="facebook-communication-div"></div>').css({display:'none',position:'absolute',zIndex:1500}).appendTo('body');
			$('<div id="facebook-communication-backdrop"></div>').css({position:'absolute'}).appendTo(comm);
			$('<div id="facebook-communication-message"></div>').css({position:'absolute'}).appendTo(comm);
			$(window).unbind('closemsg.fbcomm').bind('closemsg.fbcomm', function() { comm.hide(); });
			$(window).unbind('openmsg.fbcomm').bind('openmsg.fbcomm', function() {
				comm.show();
				$(window).trigger('scroll');
			});
			$(window).unbind('changemsg.fbcomm').bind('changemsg.fbcomm', function(e,msg) {
				var msgdiv = $('#facebook-communication-message', comm);
				$('<div>'+msg+'</div>').appendTo(msgdiv.empty());
			});
			$(window).unbind('resize.fbauthmsg').bind('resize.fbauthmsg', function() {
				var hw = {height:parseInt($(document).height())+'px', width:parseInt($(document).width())+'px','top':0,'left':0};
				comm.css(hw);
				$('#facebook-communication-backdrop', comm).css(hw);
				$(this).trigger('scroll');
			});
			$(window).unbind('scroll.fbauthmsg').bind('scroll.fbauthmsg', function() {
				var msgdiv = $('#facebook-communication-message', comm);
				var newtop = $(window).scrollTop() + (($(window).height() - msgdiv.outerHeight())/2);
				var newleft = $(window).scrollLeft() + (($(window).width() - msgdiv.outerWidth())/2);
				msgdiv.css({'top':newtop,'left':newleft});
			});
			$(window).trigger('resize').trigger('scroll');
		}
		$(window).trigger('changemsg.fbcomm', [msg]);
		$(window).trigger('openmsg.fbcomm');
	}
	$(function() {
		$(window).bind('startauth.bmfbauth', function(ev, ele) {
			ele.each(function() {
				var extra = ($(this).attr('fb-extra')||'').split('|');
				var o = {};
				for (i in extra) {
					var attr = extra[i];
					var attr = attr.split(':');
					var name = attr.shift().replace(/[^\w]+/g, '-');
					if (attr.length) var val = attr.join(':');
					else var val = true;
					o[name] = val;
				}
				o = $.extend({rplc:false, w:0, h:0}, o);
				if (o.rplc) {
					$(this).empty();
					$('<div class="facebook-loading-account"><span>Loading Your Account</span></div>').css({color:'#b2b2b2', 'float':'right'}).appendTo(this);
				} else {
					var off = $(this).position();
					$('<div> </div>').css({
						position:'absolute',
						backgroundColor:'white',
						opacity:.5,
						'top':off.top,
						'left':off.left,
						height:$(this).innerHeight()+parseInt(o.h),
						width:$(this).innerWidth()+parseInt(o.w)
					}).appendTo(this);
				}
			});
		});
		// $.BM.fbCommMsg('<div class="loading-facebook-account">Loading your account...<div>'); });
		$(window).bind('successafterreplace.bmfbauth', function() { $(window).trigger('closemsg.fbcomm'); });
		$(window).bind('unsuccessafterreplace.bmfbauth', function() { window.location.reload(true); });
	});
})(jQuery);

(function($){
	/** tricky code to make sure that if they have js, that the modal is called and that they are not linked to /sign-in/ when they click the
	  * sign-in link before the pages is completely loaded */
	$(function() {
		/* if there is actually a div on the page that will be the login modal, then call the modal factory to setup a modal for that div */
		if ($('#modal-cover').length) $('#modal-cover').bmLoginModal();
		/* otherwise cover your bases so that if the fb connect stuff is on the page, without the modal, we dont get errors */
		else {
			$('a.sign-in').die('click.pre-page-load');
			// if they are on a page that does not have the hidden sign-in modal (like /sign-in/) then this code tells it to refresh the page
			// when the user successfully signs into facebook
			$(window).bind('loginsuccess.bmfbauth', function(e, r) {
				if (r.rfrsh) window.location.reload(true);
			});
		}
	});
	$('a.sign-in').live('click.pre-page-load', function(e){e.preventDefault()});
})(jQuery);

