/*
/////////////////////////////
///// Mindbloom Library /////
/////////////////////////////

Here are basic functions for session management.

Please see mb.load_sample_header() for an example of how to use session management functions.

Here are basic documentation.

----------------------------------------------
mb.signIn(user_name, password, success_callback(data), error_callback())

success_callback = function to be triggered when the sign in is successful.
	data has property called user which contains all user info (e.g. user.first_name, user_last_name ...)
error_callback = function to be triggered when the sign in is not successful.


mb.signInFB(success_callback(data), error_callback())


mb.signOut(callback())


mb.resetPassword(pr_email_address, callback(message))

pr_email_address = string of email address where we need to send the reset password link to
callback = function to be called after the ajax call. message is the response text from the server.


mb.checkSession(found(data), not_found())

found = function to be triggered if user session has been found. data.user has user info.
not_found = function to be triggered if no user session has been found.
*/


try {
	document.domain = 'mindbloom.com';
} catch (err) {}

var mb = {};

mb.logToConsole = function(msg)
{
	try 
	{
		if(console && console.log)
		{
			console.log("Javascript: " + msg);
		}
	} catch (err) { }
}

mb.libDomain = function()
{
	var sub_domain = window.location.host.split(".")[0];
	if(window.location.host.indexOf("csus.edu")>-1) {
		return "http://mindbloom.thewellatsacstate.com";
	}

    if (window.location.host.indexOf("abbott") != -1) {
        return "http://abbott.mindbloom.com";
    }

    if (window.location.host.indexOf("gs.") != -1) {
        return "http://gs.mindbloom.com";
    }

	if(sub_domain=="local"||sub_domain=="dev") {
		return "http://local.mindbloom.com";
	}
	if(sub_domain=="stage"||sub_domain=="corp-stage") {
		return "http://stage.mindbloom.com";
	}
	return "http://www.mindbloom.com";
}

mb.blackoutOpen = function(clickCallback)
{
	$(".mb_blackout").remove();
	$("body").append(
		$("<div/>")
			.attr("class", "mb_blackout")
			.bind("click", clickCallback)
	);
	$(".mb_blackout").fadeIn("slow");
}

mb.blackoutClose = function() 
{
	$(".mb_blackout,#mb_spinner").fadeOut("fast", function () {$(".mb_blackout,#mb_spinner").remove();});
}

mb.spinnerOpen = function()
{
	$("#mb_spinner").remove();
	$("body").append(
		$("<div/>")
			.attr("id", "mb_spinner")
	);
	$("#mb_spinner").fadeIn("fast");
}


mb.openDiscovery = function(window_type)
{
	if(window_type===undefined)
	{
		window_type = "oad";
	}
	mb.blackoutOpen(mb.closeDiscovery);
	mb.spinnerOpen();
	$("body").append(
		'<iframe id="mb_discovery" name="discovery_frame" frameborder=0 marginwidth="0" marginheight="0" scrolling="no" backgroundcolor="transparent" allowtransparency="true" '
		+ ' src="' + mb.libDomain() + '/apps/discovery/index.html?window_type=' + window_type + '&utm_source=' + window_type + '&utm_medium=web&utm_campaign=discovery_' + window_type + '" '
		+ ' class="' + window_type + '" '
		+ '></iframe>'
	);
	return false;	
};

mb.closeDiscovery = function()
{
	mb.blackoutClose();
	$("#mb_discovery").fadeOut("fast", function () {$("#mb_discovery").remove();});
	return false;
};

mb.embedDiscovery = function(window_type, cls, width, height){
	// Legacy code support
	mb.embedMB(window_type, cls, width, height);
};

mb.embedMB = function(window_type, cls, width, height)
{
	if ( $("#mb_container").length > 0){
		if (width === null){ width = 1024;}
		if (height === null) { height = 600;}
		var goto_q;
		jQuery.getScript(
				mb.libDomain() + "/lib/jquery/jquery.querystring.js",
				function()
				{
					goto_q = $.getQueryString({ ID:"goto" });
				}
		);
		$("#mb_container").append(
			'<iframe id="mb_iframe" name="mb_frame" frameborder=0 marginwidth="0" marginheight="0" scrolling="no" backgroundcolor="transparent" allowtransparency="true" '
			+ ' src="' + mb.libDomain() + '?window_type=' + window_type + '&utm_source=' + cls + '&utm_medium=web&utm_campaign=discovery_' + cls + ' &goto=' + goto_q+'" '
			+ ' class="' + cls + '" '
			+ ' style=" width:' + width+'px; height:'+ height+'px;"></iframe>'
		);
	}
};

mb.createSession = function() 
{
	window.location = mb.libDomain() + "/session/create";
};


mb.FBappid = null;

mb.getParameterByName = function( key )
{
    var user_data = $.cookie('fbs_'+mb.FBappid).substring(1);
    var user_data = '?'+user_data.substring(0, user_data.length-1);
    var name = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( user_data );
    if( results == null )
        return "";
    else
        return results[1];
}

mb.initializeFB = function(){
	window.facebook_init = function(){
			var appid;
			var sub_domain = window.location.host.split(".")[0];
			switch(sub_domain){
				case 'local': appid = '129240513780828';break;
				case 'stage': appid = '126192750756115';break;
				case 'tree': appid = '140164679332734';break;
				default: appid = '140164679332734';break;
			}
			mb.FBappid = appid;
			mb.logToConsole('mb.initializeFB() appid = '+appid);
			FB.init({ appId: appid, status: true, cookie: true, xfbml: true });
	}
	window.fbAsyncInit = function() {
		facebook_init();
	};
	(function() {
		var e = document.createElement('script'); e.async = true;
		e.src = document.location.protocol +
		'//connect.facebook.net/en_US/all.js';
		document.getElementById('fb-root').appendChild(e);
	}());
};

/*///////////////////////////////////////////////////
/////Support functions for user session management///
///////////////////////////////////////////////////*/

// sign in function that takes either user_name or facebook and try to log that person in.
// success_callback or error_callback functions must be specified.
mb.signIn = function(user_name, password, success_callback, error_callback)
{
	// assert correct args
	if (user_name === null && facebook_uid === null){
		throw "Argument error: either user_name or facebook_uid should be provided";
	}
	if (error_callback === null){
		error_callback = function(){};
	}
	if (success_callback === null){
		success_callback = function(){};
	}
	
	var postTo = "/session/login";
	var postType = "POST";
	var postData = {};
	
	postData['password'] = password;
	postData['user_name'] = user_name;
	postData['goto'] = $.getQueryString({ ID:"goto" });
	
	$.ajax( {	url: postTo,
				type: postType,
				data: (postData),
				dataType: "json",
				success: function(data)
				{
					if(data['logged-in'] === true)
					{
						success_callback(data);
					}
					else{
						error_callback(data);
					}
				}
			}
		)
		
	return false;
};

mb.signInFB = function(success_callback, error_callback){
	FB.login(function(response) {
		if (response.authResponse) {
			mb.logToConsole('user is logged in');
			$.ajax( {	url: "/facebook/login",
					type: 'POST',
					data: ({session:response.authResponse}),
					dataType: "json",
					success: function(data)
					{
						if(data['logged-in'] === true)
						{
							success_callback(data);
						}
						else{
							error_callback();
						}
					}
				}
			);
		} else {
			mb.logToConsole('user is NOT logged in');
			error_callback();
		}
	});
};

// Checks if there is already a session. Callback functions should be provided as args.
mb.checkSession = function(found, not_found){
	$.ajax({	
		url: "/session/mb_user_session",
		type: "GET",
		dataType: "json",
		success: function(data)
		{
			if (data.user.terms_accepted_date && data.user.first_name){
				found(data);
			}
			else{
				not_found();
			}
		},
		error: function()
		{
			not_found();
		}
	});
};

// Sign the user out and executes the function specified by its caller.
mb.signOut = function(callback)
{
	if (callback===null){
		throw "Argument Error: callback function should be provided.";
	}
	$.ajax( {	url: "/session/logout",
				type: "GET",
				data: ({}),
			success: function(data)
			{
				callback();
			}
		}
	)
};

// Sends a reset password email. It returns the response from the server.
// The callback function will be called with one argument. String of whether it was a success or not.
mb.resetPassword = function(pr_email_address, callback)
{
	var postTo = "/api/password_reset_request";
	var postType = "POST";
	var postData = {};
	
	postData['email_address'] = pr_email_address;
	postData['goto'] = pr_email_address;
	
	$.ajax({
		url: postTo,
		type: postType,
		data: (postData),
		dataType: "json",
		success: function(data)
		{
			callback(data["response_message"]);
		}
	});
};

mb.load_sample_header = function(){
	mb.logToConsole("mb.load_sample_header()");
	var header_div = $('#mb_header');
	
	var sign_in_email = function(){
		mb.signIn( 
			$('#user_name').val(),
			$('#password').val(),
			check_session,
			function(data){
				alert('Either the email address or the password you provided is wrong.');
				$('#password').val('');
			}
		);
	};
	
	var sign_in_fb = function(){
		mb.signInFB( 
			check_session,
			function(){
				alert('You either are not logged into Facebook or do not have a Mindbloom account associated with your facebook account.');
			}
		);
	};
	
	var password_reset = function(){
		mb.resetPassword(
			$('#pr_email_address').val(),
			function(response){
				alert(response);
				$('#forgot_password').hide();
				$('#session_not_found').show();
			}
		)
	};
	
	var sign_out = function(){
		mb.signOut(
			function(){
				window.location.reload(true);
			}
		);
	};
	
	var check_session = function(){	
		mb.checkSession(function(data){
			$('#session_found .welcome')
				.html('You are logged in as '+data.user.first_name+' '+data.user.last_name+'')
			$('#session_found .log_out')
				.html('(not '+data.user.first_name+'?)')
				.unbind('click')
				.bind('click', sign_out)
			$('#session_found').show();
			$('#session_not_found').hide();
		}, function(){
			$('#session_not_found').show();
			$('#session_found').hide();
		});
	};
	
	$(header_div)
		.append( $('<div/>')
			.attr('id', 'session_found')
			.append( $('<span/>')
				.attr('class', 'welcome')
			)
			.append( $('<a/>')
				.attr('class', 'log_out')
				.attr('href', '#')
			)
			.hide()
		)
		.append( $('<div/>')
			.attr('id', 'session_not_found')
			.append( $('<span/>')
				.html('Email:')
			)
			.append( $('<input/>')
				.attr('type', 'text')
				.attr('id', 'user_name')
			)
			.append( $('<span/>')
				.html('Password:')
			)
			.append( $('<input/>')
				.attr('type', 'password')
				.attr('id', 'password')
			)
			.append( $('<a/>')
				.html('(forgot?)')
				.attr('class', 'forgot_password_link')
				.attr('href', '#')
				.bind('click', function(e){
					$('#session_not_found').hide();
					$('#forgot_password').show();
				})
			)
			.append( $('<input/>')
				.attr('type', 'button')
				.val('Sign In')
				.bind('click', sign_in_email)
			)
			.append( $('<span/>')
				.html('or')
			)
			.append( $('<input/>')
				.attr('type', 'button')
				.val('Sign In via Facebook')
				.bind('click', sign_in_fb)
			)
			.hide()
		)
		.append( $('<div/>')
			.attr('id', 'forgot_password')
			.append( $('<span/>')
				.html('Type in your email address and we will send you a link to reset your password.')
			)
			.append( $('<input/>')
				.attr('type', 'text')
				.attr('id', 'pr_email_address')
			)
			.append( $('<input/>')
				.attr('type', 'button')
				.val('Submit')
				.bind('click', password_reset)
			)
			.append( $('<input/>')
				.attr('type', 'button')
				.val('Cancel')
				.bind('click', function(e){
					$('#session_not_found').show();
					$('#forgot_password').hide();
				})
			)
			.hide()
		);
	
	check_session();
	
};


