$.showing  = false;			
$.loggedIn = false;
$.userId   = -1;
$.loginCallback = null;
$.logoutCallback = null;
$.registerCallback = null;
$.fbConnectedCallback = null;
$.guid = null;
$.token = null;
$.linksDrawn = false;
$.fbcEnabled = true;
$.fbConnected = false;

$.fn.logIn  = function(userObject) {
	
	safeLog("login");
	
	// Write Cookies
	if (userObject.remember) {
		safeLog("use persistent cookies");
		$.cookie('ft-user-id', 	 userObject.userId,	{ expires: 30});	
		$.cookie('ft-guid', 	 userObject.userGuid,	{ expires: 30});
		$.cookie('ft-user-name', userObject.userName,	{ expires: 30});
		$.cookie('ft-user-icon', userObject.imagePath,	{ expires: 30});			 
		$.cookie('ft-token', 	 userObject.sessionToken); // Always a session
		$.userId = userObject.userId;
		
	} else {
		safeLog("use session cookies");
		$.cookie('ft-user-id', 	 userObject.userId);	
		$.cookie('ft-guid', 	 userObject.userGuid);
		$.cookie('ft-token', 	 userObject.sessionToken);
		$.cookie('ft-user-name', userObject.userName);
		$.cookie('ft-user-icon', userObject.imagePath);
		$.userId = userObject.userId;
	}
	
	//destroy anonymous cookie
	$.cookie('ft-anon-guid', null); 
	
	// Load user Icon
	$().setUserIcon();
	$.guid  = userObject.userGuid;
	$.token = userObject.sessionToken;
	
	$.loggedIn = true;
	$("#header-links").fadeOut("slow", 
		function(){
			$("#header-links ul").empty();
			$().drawHeaderLinks();	
			$("#header-links").fadeIn("slow");
			$().slideTrayOut();
		});	
		
	safeLog("log in complete");
	
	if ($.loginCallback != null) {
		$.loginCallback();
	}
};

$.fn.doLogOut = function(b){
	
	if (b) { // b is either passed directly or set by facebook
		$.cookie('ft-user-id', 	 null);
		$.cookie('ft-guid', 	 null);
		$.cookie('ft-token', 	 null);
		$.cookie('ft-user-name', null);
		$.cookie('ft-user-icon', null);
	
		$.userId = -1;
		$.loggedIn = false;
		$("#header-links").fadeOut("slow", 
			function(){
				$("#header-links ul").empty();
				$().drawHeaderLinks();
				$("#header-links").fadeIn("slow");
				$().slideTrayIn();	
			});	
		
		safeLog("logged out");
		if ($.logoutCallback != null) {
			safeInfo("logout callback");
			$.logoutCallback();
		}
	}
}

$.fn.logOut = function(options) {
	
	if ($.fbConnected) {
		$.fbConnected = false;
		FB.Connect.logout($().doLogOut);
	} else {
		$().doLogOut(true);
	}
};

$.fn.slideTrayIn = function() {
		if (!$.showing) return;
		$("#tray-wrapper").animate({"left": "-=60px"}, 500);
		$("#shadow-container").fadeOut("slow");
		$.showing = false;
	
};

$.fn.slideTrayOut = function(){		
	if ($.showing) return;
	$("#shadow-container").fadeIn("slow");
	$("#tray-wrapper").show().animate({"left": "+=60px"}, 500);
	$.showing = true;
};

$.fn.showTray = function(){		
	if ($.showing) return;
	$("#shadow-container").show();
	
	var left = $("#tray-wrapper").offset().left + 85; 	// have to figure out why this is 85 
														// and not 60 as I expected
	$("#tray-wrapper").css({"left": left});
	$("#tray-wrapper").show();
	$.showing = true;
};

$.fn.drawHeaderLinks = function() {
	
	var headerLinks = $("#header-links ul");
	if (headerLinks.length > 0) {
		
		headerLinks.empty();
	
		if ($.fbcEnabled) {	
			if (($.fbConnected)) {
				headerLinks.append('<li id="fb-header-badge"><img src="assets/buttons/fb-yes.gif"/></li>');
				$("#fb-header-badge").css({'cursor':'default'}).click(function(){ return false;});
			} else {
				headerLinks.append('<li id="fb-header-badge"><a href="fbc.php" style="border: 0px none ; padding: 0px; margin-top: 0px; height: 5px;"><img src="assets/buttons/fb-connect.gif"/></a></li>');
			}
		}
		
		if ($.loggedIn) {
			// These are added in reverse order to allow them to "float-right" and require no
			// hardcoded positioning
			
			headerLinks.append('<li><a class="header-link" onClick="$().logOut();" href="#">Log Out</a></li>');
			headerLinks.append('<li><a class="header-link" href="listen.php?id='	+ $.userId +'">profile</a></li>');
			headerLinks.append('<li><a class="header-link" href="news.php">news</a></li>');
			headerLinks.append('<li><a class="header-link" href="index.php">home</a></li>');
			
		} else {
			// These are added in reverse order to allow them to "float-right" and require no
			// hardcoded positioning
			headerLinks.append('<li><a class="header-link" onClick="$().showLoginForm();" href="#">log in</a></li>');
			headerLinks.append('<li><a class="header-link" href="join.php">join us!</a></li>');
			headerLinks.append('<li><a class="header-link" href="news.php">news</a></li>');
			headerLinks.append('<li><a class="header-link" href="index.php">home</a></li>');
		}
	}
	
	$("#header-links li:first").css({'margin-right':'0px'});
	$.linksDrawn = true;
};

$.fn.autoLogin = function() {
	
	safeLog("attempting autoLogin");
	$.post("services/autologin.php", {'userGuid': $.cookie('ft-guid')},
		
		function(response){
			
			safeLog("autoLogin callback");
			if (response.errorCode != 0) {
				safeLog("autoLogin failed");
				// auto login failed for some reason
				$.loggedIn = false;
				$.cookie('ft-user-id', 	 null);
				$.cookie('ft-guid', 	 null);
				$.cookie('ft-token', 	 null);
				$.cookie('ft-user-name', null);
				$.cookie('ft-user-icon', null);
				
				$.userId = -1;
				return;
			}		
				
			safeLog("autoLogin success");
			var data = response.records[0];	
			$.guid  = data.userGuid;
			$.token = data.token;		
			
			$.cookie('ft-anon-guid', null); //destroy anonymous cookie
			$.cookie('ft-token', data.token);
			$.userId = $.cookie('ft-user-id');  // TODO - FIX - This is a hack
			$.loggedIn = true;
			$().setUserIcon();
			$().showTray();
			$("#header-links").fadeIn("slow");
			$().drawHeaderLinks();
			safeLog("autoLogin complete");
		}, "json");
	
};

$.fn.anonymousLogin = function() {
	safeInfo("anonymousLogin called");
	var guid  = $.cookie('ft-anon-guid');
	var token = $.cookie('ft-token');
	 
	if (guid == null) guid ='';
	
	if ((guid != null) && (token != null)) {
		// assumes that ft-anon-guid has been destroyed if there is a real log in.
		$.guid  = guid;
		$.token = token;
		$.userId = -1;
		return;
	}
	
	$.post("services/autologin.php", {'userGuid': guid, 'anon':1},
		
		function(response){
			
			if (response.errorCode != 0) {
				safeLog("anonymousLogin failed");
				// auto login failed for some reason
				return;
			}
			
			safeLog("anonymousLogin success");
			var data = response.records[0];	
			$.guid  = data.userGuid;
			$.token = data.token;
			$.userId = -1;
			$.cookie('ft-anon-guid',	$.guid,	{ expires: 30});
			$.cookie('ft-token',		$.token);
		
		}, "json");
	
};

$.fn.setUserIcon = function(options) {
	
	
	// Load user Icon
	var imagePath = $.cookie('ft-user-icon');
	var userName  = $.cookie('ft-user-name');
	safeLog("setUserIcon: " +"[" + imagePath + "]");
	
	var ext = imagePath.substring(imagePath.length - 3);
	if (ext !== "png" ) imagePath = 'http://cdn.finetune.com/images/no_user_100.png'; 
	$("#icon").attr({'src': imagePath});
	$("#icon-mask img").attr({'alt': "You are logged in as " + userName});	
	safeInfo(imagePath);
};

$.fn.isTheUserLoggedIn = function(options) {
	
	safeLog("is the user already logged in?");
	
	var guid 	  = $.cookie('ft-guid');
	var token	  = $.cookie('ft-token');
	
	if (guid != null && token != null) {
		safeLog("looks like it.");	
		$.loggedIn = true;
		$.userId = 	$.cookie('ft-user-id');
	
		// TODO - if userId is -1 then also return false here. -- MYKEL
		
		$.guid  = guid;
		$.token = token;
		return true;
	}
	
	safeLog("guess not.");
	return false;
};

$.fn.closeDialog = function() {
	$("#dialog-container").hide();
	$("#lightbox-backdrop").hide();
	
};	

$.fn.addLightBox = function() {
	
	var lightBox = $("lightbox");
	if (lightBox.length == 0) {
		var blob = "";
		blob += "<div id='lightbox'>";
		blob +=	"<div id='lightbox-backdrop'></div>";
		blob += "<div id='dialog-container'>";
		blob +=	"<div id='dialog-title'></div>";
		blob += "<div id='dialog-close-button'><img src='assets/buttons/btn-close-base.png'/></div>";
		blob += "<div id='dialog-content-wrapper'>";	
		blob += "<div id='dialog-content'></div>";
		blob += "</div 'dialog-content-wrapper'>";
		blob += "</div 'dialog-container'>";
		blob += "</div 'lightbox'>";
		
		$('body').append(blob);	
	}

};

$.fn.setLoginCallback = function(f) {
	$.loginCallback = f;
};

$.fn.setLogoutCallback = function(f) {
	$.logoutCallback = f;
};

$.fn.setRegisterCallback = function(f) {
	$.registerCallback = f;
};

$.fn.setFBConnectedCallback = function(f) {
	$.fbConnectedCallback = f;	
}

$.fn.showLoginForm = function() {
	
	$("#lightbox-backdrop").fadeIn("fast");
	$("#dialog-title").html("<p class='title highlight'>log in</p>");
	$("#dialog-content").load("assets/frag/loginForm.html", {}, 
		function()  {
			$("#dialog-container").height(200).fadeIn("fast");
		}
	);

};

$.fn.hideLoginForm = function() {
	$("#dialog-close-button").click();
};

$.fn.connectedLite = function() {
	safeInfo("connectedLite");
	
	if ($.loggedIn == false) {
		var current = window.location;
		$.cookie('postLoginUrl', current);
		window.location = 'fbc.php';

	} else {
		$.fbConnected = true;
		// save fb id
		//FB.ensureInit(function() {
		//	FB.Connect.showPermissionDialog("email");
		//	$.facebookId = 999; 
		//});
		
		$().drawHeaderLinks();
		if ($.fbConnectedCallback != null) {$.fbConnectedCallback();}
	}
}

$(document).ready(function() {
		
	// Logged in?
	if($().isTheUserLoggedIn()){
		
		$().setUserIcon();
		$().showTray();
		$("#header-links").fadeIn("slow");
		$().drawHeaderLinks();
		
	} else {
		
		// If we have a guid stored then we can get a new session token without prompting 
		if (($.cookie('ft-guid') != null) && ($.cookie('ft-token') == null)) {
			
			$().autoLogin();
			// TODO - If autoLogin fails for some reason the header links will not be drawn -- MYKEL
			
		} else {
			// No Guid and no Session Token ... not logged in.
			safeLog("fell all the way through.  this user is definitely not logged in.");
			$.loggedIn = false;
			$("#header-links").fadeIn("slow");
			$().drawHeaderLinks();	
			
			// Get anonymous GUID/token for logging
			$().anonymousLogin();
		}		
	}
	
	// Set up lightbox dialog
	$().addLightBox();
	
	$("#dialog-close-button").bind("mouseenter",
		function(event){
			$(this).children("img").attr({src:"assets/buttons/btn-close-over.png"});	
		}
	);
	
	$("#dialog-close-button").bind("mouseleave",
		function(event){
			$(this).children("img").attr({src:"assets/buttons/btn-close-base.png"});	
		}
	);
	
	$("#dialog-close-button").click(function(){
		$().closeDialog();
	});

	
});
