/**
*    @file
*    API interaction functions for Gigya and BaseStation
*
*    @author Jean-Rene Auger
*/

// Unique key attributed to Gigya by Emmis
var SSOProviderKeyGigya = 'H7YSA4NKCN2F72NQ';

/**
* BaseStation login function via their API using email/password
*
* @param string email Email address
* @param string password Password
* @param bool rememberme Should be true if the login should be remembered
*/
function loginUser(email, password, rememberme) {
	if (!rememberme) rememberme = 'false';
	var memberData = "{'EmailAddress': '" + email +
	"', 'Password': '" + password +
	"', 'RememberMe': '" + rememberme + "'}";
	jQuery.ajax({
		type: "POST",
		url: "/_Shared/Content/Public/Membership.asmx/LoginMember",
		data: memberData,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			var tmp = $.fromXMLString(msg);
			if ($(tmp).find('Status').text() == 1) {
				loginRedirect();
			} else {
				$("#rfvError").css('display', 'block');
			}
		},
		error: ajaxFailed
	});
}

/**
* Called once the user has successfully logged in to redirect the user to the appropriate page
*/
function loginRedirect() {
  var destURL = querySt('Destination');
  if (destURL != '') { // page has a redirect parameter
	  document.location.href = unescape(destURL);
  } else if ((location.pathname == '/gigya/newlogin.aspx') || (location.pathname == '/gigya/newjoin.aspx') || (location.pathname == '/login.aspx') || (location.pathname == '/join.aspx')) {
	  document.location.href = '/'; // redirect to homepage to force refresh BaseStation cookie and session variables
  } else {
	  document.location.href = document.location.href.replace('#', '&refresh=1#'); // page refresh to force refresh BaseStation cookie and session variables
  }
}

/**
* BaseStation login function via their API using email/password using a single sign-on provider
*
* @param string email Email address
* @param string password Password
* @param bool rememberme Should be true if the login should be remembered
* @param string SSOProviderKey Signle sign-on provider key
*/
function SSOLoginUser(email, password, rememberme, SSOProviderKey) {
	if (!rememberme) rememberme = 'false';
	var memberData = "{'EmailAddress': '" + email +
	"', 'Password': '" + password +
	"', 'RememberMe': '" + rememberme + "', 'SSOProviderKey': '" + SSOProviderKey + "'}";
	jQuery.ajax({
		type: "POST",
		url: "/_Shared/Content/Public/Membership.asmx/SSOLoginMember",
		data: memberData,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			var tmp = $.fromXMLString(msg);
			if ($(tmp).find('Status').text() == 1) {
				setUID($(tmp).find('token').text());
			} else {
				$("#rfvError").css('display', 'block');
			}
		},
		error: ajaxFailed
	});
}

/**
* BaseStation login function via their API using the token
*
* @param string Token BaseStation unique token
* @param bool rememberme Should be true if the login should be remembered
* @param string SSOProviderKey Signle sign-on provider key
*/
function SSOLoginMemberByToken(Token, rememberme, SSOProviderKey) {
	if (!rememberme) rememberme = 'false';
	var memberData = "{'Token': '" + Token +
	"', 'RememberMe': '" + rememberme + "', 'SSOProviderKey': '" + SSOProviderKey + "'}";
	jQuery.ajax({
		type: "POST",
		url: "/_Shared/Content/Public/Membership.asmx/SSOLoginMemberByToken",
		data: memberData,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			var tmp = $.fromXMLString(msg);
			if ($(tmp).find('Status').text() == 1) {
				setUID(Token);
			} else {
				$("#rfvError").css('display', 'block');
			}
		},
		error: ajaxFailed
	});
}

/**
* Callback function if the BaseStation login fails
*/
function ajaxFailed(result, textStatus, errorThrown) {
	$(".control.uloginverify").html('');
}

/**
* Action for the login form
*
* @param string EmailAddress Email address
* @param string txtPassword Password
*/
function checkLoginForm(EmailAddress, txtPassword) {
	if (txtPassword == '') {
		$("#rfvPassword").css('display', 'inline');
	} else {
		SSOLoginUser(EmailAddress, txtPassword, "false", SSOProviderKeyGigya);
		$("#rfvPassword").css('display', 'none');
	}
	return false;
}


/**
* Add login event handler to Gigya service
*
* @param string Gigya configuration in JSON format
* @param string Function hook in JSON format
*/
gigya.services.socialize.addEventHandlers(conf, {
        onLogin: onLoginHandler
     } );

/**
* Login event handler callback used by the Gigya login
*
* @param object eventObj Gigya user object
*/
function onLoginHandler(eventObj) {
	var DOB
	eventObj.user.birthMonth = "0" + eventObj.user.birthMonth;
	eventObj.user.birthDay = "0" + eventObj.user.birthDay;
	if (eventObj.user.birthYear) {
		DOB = eventObj.user.birthYear+"-"+eventObj.user.birthMonth.substr(eventObj.user.birthMonth.length - 2)+"-"+eventObj.user.birthDay.substr(eventObj.user.birthDay.length - 2);
	}
	// The call below will also verify the signature of the sign-on object to make sure it comes from Gigya
	$.get("/EI/SharedObjects/Handlers/ProxyHandler.ashx?url=http://www.amri.ca/bsAffinity/&dartSite="+arDart.site.replace("sri.", "")+"&UID="+encodeURIComponent(eventObj.user.UID).split('%').join('%25')+"&signatureTimestamp="+encodeURIComponent(eventObj.signatureTimestamp)+"&UIDSignature="+encodeURIComponent(eventObj.UIDSignature).split('%').join('%25')+"&isSiteUID="+eventObj.user.isSiteUID+"&FirstName="+encodeURIComponent(eventObj.user.firstName)+"&LastName="+encodeURIComponent(eventObj.user.lastName)+"&EmailAddress="+encodeURIComponent(eventObj.user.email)+"&DateOfBirth="+DOB+"&Gender="+encodeURIComponent(eventObj.user.gender)+"&PostalCode="+encodeURIComponent(eventObj.user.zip)+"&City="+encodeURIComponent(eventObj.user.city)+"&Region="+encodeURIComponent(eventObj.user.state)+"&Country="+encodeURIComponent(eventObj.user.country), function(data) {
			if (data.indexOf('Token', 0) == 0) { // successfully created the account
				var Token = data.split('Token=');
				Token = Token[1];
				SSOLoginMemberByToken(Token, "false", SSOProviderKeyGigya);
			} else { // login or join form
				$(".control.uloginverify").html(data);
			}
	});
}

/**
* Display the custom join form over the BaseStation form
*
* @param string toptext Text in the original BaseStation join form
*/
function showJoinForm(toptext) {
	// The call below will also verify the signature of the sign-on object to make sure it comes from Gigya
	$.get("/EI/SharedObjects/Handlers/ProxyHandler.ashx?url=http://www.amri.ca/bsAffinity/join.php&dartSite="+arDart.site.replace("sri.", ""), function(data) {
		$(".control.uloginverify").html(data);
		$('.valueProposition').html(toptext);
	});
}

/**
* Display the custom login form over the BaseStation form
*/
function showLoginForm() {
	// The call below will also verify the signature of the sign-on object to make sure it comes from Gigya
	$.get("/EI/SharedObjects/Handlers/ProxyHandler.ashx?url=http://www.amri.ca/bsAffinity/login.php&dartSite="+arDart.site.replace("sri.", ""), function(data) {
		$(".control.uloginverify").html(data);
	});
}

/**
* Synchronize the user UID between BaseStation and Gigya
*
* @param string siteUID BaseStation UID as returned by their API
*/
function setUID(siteUID) {
	var dateStr = Math.round(new Date().getTime()/1000.0); // Current time in Unix format (i.e. the number of seconds since Jan. 1st 1970)
	$.get("/EI/SharedObjects/Handlers/ProxyHandler.ashx?url=http://www.amri.ca/bsAffinity/&dartSite="+arDart.site.replace("sri.", "")+"&UID="+encodeURIComponent(siteUID).split('%').join('%25')+"&signatureTimestamp="+encodeURIComponent(dateStr), function(data) {
			if (data.indexOf('Signature', 0) == 0) { // successfully created the signature
				var yourSig = data.split('Signature=');
				yourSig = yourSig[1];

				var params = {
					siteUID: siteUID, 
					timestamp:dateStr,
					signature:yourSig
				};

				gigya.services.socialize.setUID(conf, params); // sync UID with Gigya
			}
			loginRedirect();
	});
}

/**
* Display the Gigya login button int he 'gigyaDiv' DIV
*/
function showLogin() {
	var login_params =
    {
        showTermsLink: 'false'
        ,height: 35
        ,width: 85
        ,containerID: 'gigyaDiv'
        ,buttonsStyle: 'fullLogo'
        ,autoDetectUserProviders: ''
        ,facepilePosition: 'none'
        ,hideGigyaLink:true
    }
	gigya.services.socialize.showLoginUI(conf, login_params);
}

$(function() {
	if (ei_UserID == '') {
		if ((location.pathname == '/gigya/newjoin.aspx') || (location.pathname == '/join.aspx')) {
			showJoinForm($('.valueProposition').next().andSelf());
		} else {
			showLoginForm();
		}
	}
});
