// login lightbox stuff
;(function($,jBox,rootURL,console) {
	// regular expression to detect the login/session cookie 
	// declared here as a 'static' variable as it's only eval'd once ;-)
	var re = /SESSION=(.+?)(?:;|$)/;

	var selector = "a.loginOrRegister";
	var selectorRequiresLogin = "#btnPost, a.flagSpoiler, a.reportAbuse";	
	var login = {
		isLoggedIn: null,
		login: function () {
			if (!this.isLoggedIn) $(selector).click();
		}
	};
	
	// this is the thing that requiresLogin  
	var target = null;
	
	$(login).bind("login",function (event) {
		if (console.debug) console.debug("logged in, continuing...");
		login.isLoggedIn = true;
		$(selector).contents().replaceWith("Update Profile");
		if (console.debug) console.debug("unbinding requiresLogin click");
		$(selectorRequiresLogin).unbind("click");
		if (target) {
			if (console.dir) console.dir(target);
			// click() apparenty doesn't exist for <a> but does for <input> 
			if (target.attr("href")) location = target.attr("href"); 
			else if (target.attr("type") == "submit") target.parents("form").submit();
			else target.click();
			jBox.hideLightBox();
		}
	}).bind("logout",function (event) {
		if (console.debug) console.debug("waiting for login");
		login.isLoggedIn = false;
		$(selector).contents().replaceWith("Register or Login");
		if (console.debug) console.debug("binding requiresLogin click");
		$(selectorRequiresLogin).click(function (event) {
			if (console.debug) console.debug("Click, requires login");
			event.preventDefault();
			target = $(event.target);
			login.login();
		});
	});

	var interval = setInterval(function () {
		if (re.test(document.cookie)) {
			if (!login.isLoggedIn) $(login).trigger("login");
		} else {
			if (login.isLoggedIn) $(login).trigger("logout");
		}
	}, 500);

	$(function() {
		
		var o = $(selector);

		if (console.assert) console.assert(o.size(),"No element matched by " + selector);
		var settings = {
			type : "iframe",
			id : "login",
			src : o.attr("href"),
			height : 520,
			width : 440,
			buttons : selector,
			root: rootURL
		};
		if (console.debug) console.debug("Initialising login iframe lightbox");
		jBox.init(settings);
		$(login).trigger(login.isLoggedIn ? "login" : "logout");
	});
})(jQuery,jBox,rootURL,window.console || {});

// video light box stuff
;(function($,jBox,rootURL,console) {
	$(function() {
		var settings = {
			type : "iframe",
			id : "video",
			src : "about:blank",
			height : 503,
			width : 550,
			buttons : "a.liveStream, a.video",
			root: rootURL
		};
		$("a.liveStream, a.video").click(function (event) {
			event.preventDefault();
			settings.src = $(this).attr("href");
		});
		if (console.debug) console.debug("Initialising video iframe lightbox");
		jBox.init(settings);		
	});
})(jQuery,jBox,rootURL,window.console || {});


