QuickHit.Gigya = {};
QuickHit.Gigya.Avatar = "";

$("#menu-logout").live("click", function() {
    logoutGigya();
    window.location = $(this).attr("href");
    return false;
});

$(document).ready(function() {
    $("#link-account-submit").click(function() {
        $("#link-account .error").remove();
        var form = $("#link-account-form");
        $.ajax({
            url: "/login/authAjax",
            data: {
                gigyaUIDLinkAccount: $("#gigyaUIDLinkAccount").val(),
                gigyaUIDSigLinkAccount: $("#gigyaUIDSigLinkAccount").val(),
                gigyaTimestampLinkAccount: $("#gigyaTimestampLinkAccount").val(),
                j_username: $("#link-username").val(),
                j_password: $("#link-password").val()
            },
            dataType: "json",
            type: "POST",
            success: function(data, status) {
                if (data.success) {
                    window.location = "/";
                } else {
                    $("#link-account").append($("<div />").addClass("error").text("Invalid username or password. Please try again."));
                }
            }
        });
    });
});

function onLogin(response)
{
    // if successful to login, then check to see if the user has a site id.
    var u = response.user;
    if (u != null && u.isSiteUID)
    {
        // This is supposed to be an existing user, let's verify on the server side.
        /*
         $.post('../login/loginFromGigya',
         {GigyaUIDSig:u.UIDSig,
         GigyaUID:u.UID,
         GigyaisSiteUID:u.isSiteUID,
         Gigyatimestamp:u.timestamp,
         GigyaloginProvider:u.loginProvider
         },
         function (data, status)
         {
         alert(data);
         },
         'json'
         )
         */
        $('#gigyaUIDLoginForm').val(u.UID);
        $('#gigyaUIDSigLoginForm').val(u.UIDSig);
        $('#gigyaTimestampLoginForm').val(u.timestamp);
        $('#loginForm').attr("action", "/login/loginFromGigya");
        $('#loginForm').submit();
    }
    else
    {
        // not recognized as an existing user, put up link account dialog box
        promptUserForLinkAccount(u.UIDSig, u.UID, u.timestamp);
    }
}

function onGetUserInfoForLinkAccount (response)
{
  if (response.errorCode == 0)
  {
    // recall login with the InviteUser flag if this was a facebook login
    var user = response.user;
    if (user != null)
    {
		var image = "/images/profile/default-photo-50x50.jpg";
        if (user.thumbnailURL && user.thumbnailURL != "") {
			image = user.thumbnailURL;
		};
        $(".name", "#link-account").text(user.nickname);
		$("#linkAvatar").html("<img height='50' width='50' src=\"" + image + "\" />");
    }
  }
}

function promptUserForLinkAccount(UIDSig, UID, timestamp)
{
    $("#login-modal-box").hide();
	$("#registration-area form input").removeAttr("disabled");
    $("#link-account").show();

    $('#gigyaUIDLinkAccount').val(UID);
    $('#gigyaUIDSigLinkAccount').val(UIDSig);
    $('#gigyaTimestampLinkAccount').val(timestamp);

    // get User Avatar if possible
    gigya.services.socialize.getUserInfo(gigyaConfig,{callback:onGetUserInfoForLinkAccount });
}

function loginGigya(provider)
{
    var params = {
        provider:provider,
        callback: onLogin,
        sessionExpiration: 0,
		cid: "on-login"
    };
    gigya.services.socialize.login(gigyaConfig, params);
}


function onLoginFromLoginAccounts(response)
{
	if (response.errorCode == 0) {
		var p = response.requestParams.provider;
		$('#login'+p).addClass('active');
	}

	if ($("#uploadAvatar:checked").length) {
		var avatarToUpload = response.user.photoURL;
		$("#socialAvatarURL").attr("value",avatarToUpload);
		$("#uploadSocialAvatar").submit();
	}
}


function connectGigyaFromLoginAccounts(provider)
{
    var params = {
        provider:provider,
        callback: onLoginFromLoginAccounts,
        sessionExpiration: 0,
		cid: "coach-settings"
    };
    gigya.services.socialize.connect(gigyaConfig, params);
}


function onLoginForRegistration(response)
{
    // if successful to login, then check to see if the user has a site id.
    var u = response.user;
    if (u != null && u.isSiteUID)
    {
        alert("An account has already been linked with this social account.");
    }
    else if (u != null)
    {

        $("#registration-social").show();
        $("#registration-splash, #registration-area").hide();
        $("#socialUsername").focus();
        $("#registration-social").addClass(u.loginProvider);

        // fill in fields where possible.
        $('#gigyaUIDForRegistration').val(u.UID);
        $('#gigyaUIDSigForRegistration').val(u.UIDSig);
        $('#gigyaTimestampForRegistration').val(u.timestamp);

        var newName = u.nickname;
        if (newName == null)
        {
            newName = "";
        }
        else
        {
            // don't use spaces in the new name coming from the social network.
            newName = newName.replace(/ /g, "");
        }
        $('#socialUsername').val(newName);
        $('#socialEmail').val(u.email);

		if (u.thumbnailURL != "") {
			$("#socialAvatar").attr("src", u.thumbnailURL);
			QuickHit.Gigya.Avatar = u.photoURL;
			$("#socialAvatarURL").attr("value",QuickHit.Gigya.Avatar);
		} else {
			$("#socialAvatarContainer").remove();
		}		
    }
}

function onPreferenceUnlinkAccount(response) {
	if (response.errorCode == 0) {
		var p = response.requestParams.provider;
		$('#login'+p).removeClass('active');
		alert("Your account has been unlinked successfully.")
	}
}

function loginGigyaForRegistration(provider)
{
    var params = {
        provider:provider,
        callback: onLoginForRegistration,
        sessionExpiration: 0,
		cid: "registration"
    };
    gigya.services.socialize.login(gigyaConfig, params);
}

function unlinkAccount(provider)
{
    var params = {
        provider: provider,
        callback: onPreferenceUnlinkAccount,
        sessionExpiration: 0,
		cid: "unlink_preferences"
    };
    gigya.services.socialize.deleteAccount(gigyaConfig, params);
}

function initLoginPopup()
{
    $("#loginFacebook").live("click", function() {
        loginGigya('facebook');
        return false;
    });

    $("#loginTwitter").live("click", function() {
        loginGigya('twitter');
        return false;
    });

    $("#loginMyspace").live("click", function() {
        loginGigya('myspace');
        return false;
    });

    $("#loginGoogle").live("click", function() {
        loginGigya('google');
        return false;
    });

    $("#loginYahoo").live("click", function() {
        loginGigya('yahoo');
        return false;
    });

    $("#loginWindows-live").live("click", function() {
        loginGigya('liveid');
        return false;
    });
}

function popupGigyaShare (message, title, description, mediaimage, mediaurl, containerID) {

    // Constructing a UserAction Object; Constructor receives an Action Template string
    var act = new gigya.services.socialize.UserAction();

    act.setUserMessage(message);   // Setting the default user message
    act.setTitle(title);  // Setting the Title
    act.setLinkBack(mediaurl);  // Setting the Link Back
    act.setDescription(description);   // Setting Description
    act.addActionLink("Play QUICKHIT", "http://www.quickhit.com");  // Adding Action Link
    // Adding a Media (image)
    if (mediaimage != null)
    {
        act.addMediaItem({ type: 'image', src: mediaimage, href: mediaurl });
    }

    var params = {
        userAction:act,
        showMoreButton: "false", // Enable the "More" button and screen
        showEmailButton: "false", // Enable the "Email" button and screen
        useHTML: true,  // Use the HTML implementation of the Plugin (rather then Flash implementation)
        enabledProviders: "facebook,twitter,messenger,yahoo,google,myspace",
        containerID: containerID,
		cid: "on-share"
    };

    // Show the "Share" dialog
    gigya.services.socialize.showShareUI(gigyaConfig, params);
}

function onGetUserInfoForLoginAccounts (response) {
    if (response.errorCode == 0) {
        // recall login with the InviteUser flag if this was a facebook login
        var user = response.user;
        if (user != null) {
            for (var i = 0; i < user.providers.length; i++) {
                var p = user.providers[i];
                $('#login'+p).addClass('active');
            }
        }
    }
}


function setupGigyaLoginAccounts ()
{
    $("#loginfacebook").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('facebook');
			return false;
		} else {
			connectGigyaFromLoginAccounts('facebook');
			return false;
		}
    });

    $("#logintwitter").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('twitter');
			return false;
		} else {
			connectGigyaFromLoginAccounts('twitter');
			return false;
		}
    });

    $("#loginmyspace").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('myspace');
			return false;
		} else {
			connectGigyaFromLoginAccounts('myspace');
			return false;
		}
    });

    $("#logingoogle").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('google');
			return false;
		} else {
			connectGigyaFromLoginAccounts('google');
			return false;
		}
    });

    $("#loginyahoo").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('yahoo');
			return false;
		} else {
			connectGigyaFromLoginAccounts('yahoo');
			return false;
		}
    });

    $("#loginliveid").live("click", function() {
		if ($(this).hasClass("active")) {
			unlinkAccount('liveid');
			return false;
		} else {
			connectGigyaFromLoginAccounts('liveid');
			return false;
		}
    });

    // this does the callback that puts the checkbox on the appropriate one.
  gigya.services.socialize.getUserInfo(gigyaConfig,{callback:onGetUserInfoForLoginAccounts });
}


function onGetUserInfoForLoginAccountsOverview (response)
{
  if (response.errorCode == 0)
  {
    // recall login with the InviteUser flag if this was a facebook login
    var user = response.user;
    if (user != null)
    {
        var p = user.loginProvider;
        $('#login' + p).removeClass('inactive');

        for (var i = 0; i < user.providers.length; i++)
        {
            var p = user.providers[i];
            $('#social'+p).addClass('active');
            $('#social'+p).removeClass('inactive');
        }
    }
  }
}


function setupGigyaLoginAccountsOverview ()
{
  gigya.services.socialize.getUserInfo(gigyaConfig,{callback:onGetUserInfoForLoginAccountsOverview });
}


function logoutGigya ()
{
  gigya.services.socialize.logout(gigyaConfig,{});
}


