/// <reference path="../jquery-1.4-vsdoc.js" />
if(jimungo===undefined)
	var jimungo = {};

jimungo.Login = function (urlToGet, urlToRedirect, communityLoginPage) {
    ///<summary>The Login object.</summary>
    var _urlToGet = urlToGet;
    var _urlToRedirect = urlToRedirect;
    var _communityLoginPage = communityLoginPage;
    var _public = {
        authenticate: function (u, p, func) {
            if ($.browser.msie && (u.match(/\'/) || p.match(/\'/))) {
                if (confirm("Sorry we have an issue with logging your details into the site right now.\n\nPress OK to Log in from the Jimungo Community login page."))
                    window.location.replace(_communityLoginPage + "?ReturnUrl=" + _urlToRedirect);
                return;
            }

            var user = u;
            var pass = p;

            ///<summary>Calls the authentication handler</summary>
            var ops = ({
                dataType: "jsonp",
                contentType: "application/json; charset=utf-8",
                url: urlToGet,
                data: { username: user, password: pass },
                success: function (data, textStatus) {
                    if (data.result === true) {
                        if (_urlToRedirect !== undefined) {
                            location.replace(_urlToRedirect);
                        } else {
                            $("#result").addClass('CommonMessageSuccess')
							.html("You have successfully signed in to your Jimungo account.")
							.show("fast");
                        }
                    } else {
                        $("#result").addClass('CommonMessageError')
							.html("Oops, you have entered an incorrect Player name or Password. Please try entering your details again.")
							.show("fast");
                    }

                    if (func !== undefined) {
                        func();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#result").addClass('CommonMessageError').html("Oops! An error occured when attempting to sign you in. Please try again.").show("fast");

                    if (func !== undefined) {
                        func();
                    }
                }
            });
            $.ajax(ops);
        }
    };
    return _public
};

jimungo.LoginFacebook = function (urlToGet, urlToRedirect, communityLoginPage) {
	var _urlToGet = urlToGet;
	var _urlToRedirect = urlToRedirect;
	var _communityLoginPage = communityLoginPage;
	var _public = {
		authenticate: function (callback) {
			$.getJSON(urlToGet, function (data) {
				if (data == "Success") {
					if (_urlToRedirect !== undefined) {
						location.replace(_urlToRedirect);
					} else {
						$("#result").addClass('CommonMessageSuccess')
						.html("You have successfully signed in to your Jimungo account.")
						.show("fast");
					}
				}

				else if (data == "NotLoggedIn") {
					$("#result").addClass('CommonMessageError')
						.html("Oops, you have entered an incorrect Player name or Password. Please try entering your details again.")
						.show("fast");
				}

				else if (data == "NotVerified") {
					$("#result").addClass('CommonMessageError')
						.html("Sorry, you cannot use an unverified Facebook account to log in to Jimungo.")
						.show("fast");
				}

				else if (data == "NotLinked") {
					$("#result").addClass('CommonMessageSuccess')
						.html("Your Jimungo account is not linked yet. Click here to continue")
						.show("fast");
				}

				if (callback !== undefined) {
					callback();
				}
			});
		}
	};

	return _public;
}

var _fbStatus = "notReady";
var _csRootUrl;
var _returnUrl;

function initFacebook(fbAppId, csRootUrl, returnUrl) {
	_csRootUrl = csRootUrl;
	_returnUrl = returnUrl;

	// initialise Facebook API
	FB.init({
		appId: fbAppId,
		cookie: true
	});

	// get the Facebook connection status
	FB.getLoginStatus(function (response) {
		_fbStatus = response.status;
	});
}

function linkFacebook() {
	$.get("/members/clear.aspx", function() {
		window.location.href = _csRootUrl + "/FacebookLink2.aspx?ReturnUrl=" + _returnUrl;
	});
}

// once the user has logged on to Facebook, call this function to log in to the Community Server
// using the person's Facebook profile
function loginCommunity(callback) {
	$.getJSON(_csRootUrl + "/LoginFacebookHandler.ashx?c=?", function (data) {
		if (data == "Success") {
			if (_returnUrl !== undefined) {
				location.replace(_returnUrl);
			} else {
				$("#result").addClass('CommonMessageSuccess')
						.html("You have successfully signed in to your Jimungo account.")
						.show("fast");
			}
		}

		else if (data == "NotLoggedIn") {
			$("#result").addClass('CommonMessageError')
						.html("An error has occured while trying to log in with Facebook. Please try again later.")
						.show("fast");
		}

		else if (data == "NotVerified") {
			$("#result").addClass('CommonMessageError')
						.html("Sorry, you cannot use an unverified Facebook account to log in to Jimungo.")
						.show("fast");
		}

		else if (data == "NotLinked") {
			window.location.replace(_csRootUrl + "/FacebookLink.aspx?ReturnUrl=" + _returnUrl);
		}

		if (callback !== undefined) {
			callback();
		}
	});
}

$(function () {
	$("#fb-login, .fb-login").click(function (event) {
		event.preventDefault();

		if (_fbStatus == "unknown" || _fbStatus == "notConnected") {
			// show Facebook log in 
			FB.login(function (response) {
				// user sucessfully logged in to Facebook
				if (response.session) {
					loginCommunity();
				} else {
					// user abandon log in
					// do nothing
				}
			}, {
				perms: "email,user_birthday"
			});
		} else if (_fbStatus == "connected") {
			loginCommunity();
		}
	});

	$("#fb-link").click(function (event) {
		event.preventDefault();

		if (_fbStatus == "unknown" || _fbStatus == "notConnected") {

			// show Facebook log in 
			FB.login(function (response) {
				// user sucessfully logged in to Facebook
				if (response.session) {
					linkFacebook();
				} else {
					// user abandon log in
					// do nothing
				}
			}, {
				perms: "email,user_birthday"
			});
		} else if (_fbStatus == "connected") {
			linkFacebook();
		}
	});
});
