// JavaScript Document

$(document).ready(function() {
	// Account syncing through Sign In
	$("#reset_pw").click(function(){
		ShowTextModal("Please wait while we are resetting your password.");
		newemail = $("#feature-login #username").val();
		///console.log("Email: " + newemail);
//			$("#forgot_password_form #email").val($("#feature-login #username").val());
//			$("#forgot_password_form").submit();
        startPasswordRecovery();
	});	


    $("#reset_submit").click(function(){
		//$("#forgot_password_form").submit();
		newemail = $("#emailnew").val();
		///console.log("Email: " + newemail);
        startPasswordRecovery();
	});
	
	// Account syncing through Register
    $("#reset_submit1").click(function(){
		//$("#forgot_password_form").submit();
		newemail = $("#emailnew").val();
		///console.log("Email: " + newemail);
        startPasswordRecovery();
	});
	
	// Account syncing among multiple accounts through Sign In section
    $("#reset_picked_submit").click(function() {
		g_cur_process = EMAIL_CHK_SIGNIN;
		newemail = $("#feature-login #username").val();
		var picked_member_id = $('input[name=group1]:checked').val() ;
//		console.log ("Picked Member ID: " + picked_member_id) ;

		startPickedAccountSyncing(picked_member_id);
	});
	
	// Account syncing among multiple accounts through Register section
    $("#reset_picked_submit1").click(function() {
		g_cur_process = EMAIL_CHK_REGISTER;
		newemail = $("#emailnew").val();
		var picked_member_id = $('input[name=group2]:checked').val() ;
//		console.log ("Picked Member ID: " + picked_member_id) ;
        startPickedAccountSyncing(picked_member_id);
	});
	
	// Account syncing among multiple accounts through Initial System Sync section
    $("#reset_picked_submit2").click(function() {
		g_cur_process = EMAIL_SYNC;
		newemail = $("#initemail").val();
		var picked_member_id = $('input[name=group3]:checked').val() ;
//		console.log ("Picked Member ID: " + picked_member_id) ;

//        startPickedAccountSyncing(picked_member_id);
	});
	
    $('#initSyncClick').click(function() {
		g_cur_process = EMAIL_SYNC;
		var x = $("#initemail").val();
//		console.log ("Email for Init: " + x);

		emailValidation(x);
    });

	// Email check through Register
    $('#emailnew').blur(function() {
		g_cur_process = EMAIL_CHK_REGISTER;
		var x = $("#emailnew").val();
//		console.log ("New Email: " + x);

		emailValidation(x);
    });

	// Email check through Sign In
//    $('#username').blur(function() {
    $('#feature-login #username').blur(function() {
		g_cur_process = EMAIL_CHK_SIGNIN;
		var x = $("#feature-login #username").val();
//		console.log ("Username: " + x);

		emailValidation(x);
    });

    $('#firstnamenew').blur(function() {
		if (
			($('#firstnamenew').val().indexOf("&")!=-1) || 
			($('#firstnamenew').val().indexOf(" and ")!=-1) || 
			($('#firstnamenew').val().indexOf(" And ")!=-1) ||
			($('#firstnamenew').val().indexOf(" AND ")!=-1)
			){
				///console.log("and!");
				$("#firstnamenew").focus();
				
			}else{
				$("#lastnamenew").focus();
			}
	});
	$('#lastnamenew').blur(function() {
		if ($('#lastnamenew').val()=="") {
			$("#lastnamenew").focus();
				///console.log("Blank");
		}else{
			$("#passwordnew").focus();
		}
	});
	$('#password_confirmnew').blur(function() {
		if ($('#password_confirmnew').val() != $('#passwordnew').val()){
			$("#passwordnew").focus();
		}
	});

    $('#emailnew1').blur(function() {
		var x = $("#emailnew1").val();
        if (!isValidEmail(x)) {
            ///console.log("Please enter valid Email address.");
            ShowTextModal("Please enter a valid e-mail address.");
         } else {
			///console.log("email address: " + x);
			$.ajax({
					url: '/scripts/check_email_unique.php',
					data: "email=" + x,
					success: function(data) { 
						if(data == 0) {
							canEmailProcess =true;
							///console.log("You can use email address.");
						} else {
							canEmailProcess = false;
							///console.log(duplicateEmail);
							ShowTextModal(duplicateEmail); 
						}
					}, 
					error: function() { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister."); }
			});
		}
    });

    $('#registerClick').click(function(event) {
		d1 = new Date(); 
		var errors = new Array();

        if (!isValidEmail($("#emailnew").val())) {
            ///console.log("Please enter valid Email address.");
            errors.push("Please enter valid Email address.");
        }
        if(isEmpty($("#firstnamenew").val())) {
            ///console.log("Firstname is required.");
            errors.push("Firstname is required.");
        }
        if(isEmpty($("#lastnamenew").val())) {
            ///console.log("Lastname is required.");
            errors.push("Lastname is required.");
        }
        if(isEmpty($("#passwordnew").val())) {
            ///console.log("Password is required.");
            errors.push("Password is required.");
        }
        if(!$("#accept_termsnew").attr('checked')) {
            ///console.log("Accept Terms has to be checked.");
            errors.push("Accept Terms has to be checked.");
        }
		if (!canEmailProcess) {
            ///console.log(duplicateEmail);
            errors.push(duplicateEmail);
		}

        newfirstname 	= $("#firstnamenew").val();
        newlastname 	= $("#lastnamenew").val();
        newemail 		= $("#emailnew").val();
        newpassword 	= $("#passwordnew").val();
        newconfirmpassword 	= $("#password_confirmnew").val();
        acceptTerms 	= $("#accept_termsnew").val();
		
		if(newpassword != newconfirmpassword) {
		    ///console.log("The password did not match.");
            errors.push("The password did not match.");
		}

        if (errors.length > 0) {
    	    ShowTextModal(errors.join("\n"));
	        return false;
        }

		// Create Individual account in CCB
        $.ajax({
                type: "POST",
                url: site_url+'/_component/ccb_create_individual2/',
                data: "first_name="+newfirstname+"&last_name="+newlastname+"&email="+newemail,
                async: false,
                success: xmlParserCreate,             // name of the function to call upon success
                error: function() { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister."); }
        });

//		autoLogin("Called manually");
    });

    $('#registerClick1').click(function(event) {
		d1 = new Date(); 
		var errors = new Array();

        if (!isValidEmail($("#emailnew1").val())) {
            ///console.log("Please enter valid Email address.");
            errors.push("Please enter valid Email address.");
        }
        if(isEmpty($("#firstnamenew1").val())) {
            ///console.log("Firstname is required.");
            errors.push("Firstname is required.");
        }
        if(isEmpty($("#lastnamenew1").val())) {
            ///console.log("Lastname is required.");
            errors.push("Lastname is required.");
        }
        if(isEmpty($("#passwordnew1").val())) {
            ///console.log("Password is required.");
            errors.push("Password is required.");
        }
        if(!$("#accept_termsnew1").attr('checked')) {
            ///console.log("Accept Terms has to be checked.");
            errors.push("Accept Terms has to be checked.");
        }
		if (!canEmailProcess) {
            ///console.log(duplicateEmail);
            errors.push(duplicateEmail);
		}

        newfirstname 	= $("#firstnamenew1").val();
        newlastname 	= $("#lastnamenew1").val();
        newemail 		= $("#emailnew1").val();
        newpassword 	= $("#passwordnew1").val();
        newconfirmpassword 	= $("#password_confirmnew1").val();
        acceptTerms 	= $("#accept_termsnew1").val();
		
		if(newpassword != newconfirmpassword) {
		    ///console.log("The password did not match.");
            errors.push("The password did not match.");
		}

        if (errors.length > 0) {
    	    ShowTextModal(errors.join("\n"));
	        return false;
        }

		// Create Individual account in CCB
        $.ajax({
                type: "POST",
                url: site_url+'/_component/ccb_create_individual2/',
                data: "first_name="+newfirstname+"&last_name="+newlastname+"&email="+newemail,
                async: false,
                success: xmlParserCreate,             // name of the function to call upon success
                error: function() { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister."); }
        });

//		autoLogin("Called manually");
    });


/* ***************************************************************************** */
//	Editing Profile Section
/* ***************************************************************************** */
    $('#editNameClick').click(function(event) {
		g_cur_process = UPDATE_NAME;
		eememberid = $("#ee_member_id").val();
//		console.log("EE Member ID: " + eememberid);

		var errors = new Array();

        newfirstname 	= $.trim($("#editfirstnamenew").val());
        newlastname 	= $.trim($("#editlastnamenew").val());

        if(isEmpty(newfirstname)) {
            ///console.log("Firstname is required.");
            errors.push("First name is required.");
        }
        if(isEmpty(newlastname)) {
            ///console.log("Firstname is required.");
            errors.push("Last name is required.");
        }

        if (errors.length > 0) {
    	    ShowTextModal(errors.join("\n"));
	        return false;
        }

		// Get CCB ID from EE Member ID through Hub table
		$.ajax({
			url: '/scripts/get_ccb_id_for_ee_member_id.php',
			data: "memberid=" + eememberid,
			dataType: 'json',
			async: false,
			success: processIndividualChange,
			error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister and tell him the error was: " + textStatus); }
		});


    });

    $('#editEmailClick').click(function(event) {
		g_cur_process = UPDATE_EMAIL;
        eememberid = $("#ee_member_id").val();
//		console.log("EE Member ID: " + eememberid);

		var x = $("#editemailnew").val().toLowerCase();
		var curEmail = $("#current_email").val().toLowerCase();

//		console.log("New Email: " + x);
//		console.log("Current Email: " + curEmail);

        if (!isValidEmail(x)) {
            ///console.log("Please enter valid Email address.");
            ShowTextModal("Please enter a valid e-mail address.");
			return false;
        } else {
			if (x != curEmail) {
				// Check email duplicate				
				$.ajax({
						url: '/scripts/check_email_unique.php',
						data: "email=" + x,
						async: false,
						success: function(data) { 
							if(data == 0) {
								//console.log("You can use email address.");
								canEmailProcess =true;
						        newemail = x;
								
								// Get CCB ID from EE Member ID through Hub table
								$.ajax({
									url: '/scripts/get_ccb_id_for_ee_member_id.php',
									data: "memberid=" + eememberid,
									dataType: 'json',
									async: false,
									success: processIndividualChange,
									error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something went wrong. Please contact the web minister and tell them the error was: " + textStatus); }
								});
								
							} else {
								canEmailProcess = false;
								//console.log(duplicateEmail);
								ShowTextModal(duplicateEmail2); 
//								return false;
							}
						}, 
						error: function() { ShowTextModal("Oops, something appears to have gone wrong."); }
				});
			} else {
				// Do not update since current email and new email are same
			}
		}

    });

    $('#editPasswordClick').click(function(event) {
		g_cur_process = UPDATE_PASSWD;
        eememberid = $("#ee_member_id").val();
//		console.log("EE Member ID: " + eememberid);

		var errors = new Array();

        newpassword 	= $("#editnewpassword").val();
        oldpassword		= $("#editcurpassword").val();
        var confirmpassword	= $("#editconfirmpassword").val();

        if(isEmpty(oldpassword)) {
            ///console.log("Lastname is required.");
            errors.push("You have to enter current password to change password");
        }
        if(isEmpty(newpassword)) {
            ///console.log("Firstname is required.");
            errors.push("New password is required.");
        }
        if(newpassword.length < 5) {
            ///console.log("Firstname is required.");
            errors.push("The minimum password length is 5.");
        }
		if(newpassword != confirmpassword) {
		    ///console.log("The password did not match.");
            errors.push("The password did not match.");
		}

        if (errors.length > 0) {
    	    ShowTextModal(errors.join("\n"));
	        return false;
        }

		// Get CCB ID from EE Member ID through Hub table
		$.ajax({
			url: '/scripts/get_ccb_id_for_ee_member_id.php',
			data: "memberid=" + eememberid,
			dataType: 'json',
			async: false,
			success: processIndividualChange,
			error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
		});

    });

/* ***************************************************************************** */
//	End of Editing Profile Section
/* ***************************************************************************** */


});	


/* ***************************************************************************** */
// Functions for Edit Profile
/* ***************************************************************************** */
// process data (JSON object) to get CCB User ID
// Then, call CCB api to update Individual based on input field
function processIndividualChange(data) { 

    if(data.result == "success") {
		newccbuid = data.ccbuid;
//		console.log("CCB Member ID: " + newccbuid);

		switch (g_cur_process)
		{
			case EMAIL_CHK_SIGNIN:			// Email Check in SignIn
			case EMAIL_CHK_REGISTER:		// Email Check in Register
				// Call CCB api in order to update nothing for this CCB User ID to make it sync
				$.ajax({
						type: "POST",
						url: site_url+'/_component/ccb_update_individual/',
						data: "individual_id="+newccbuid,
						async: false,
						success: xmlParserUpdateIndividual,             // name of the function to call upon success
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_NAME:		// UPDATE_NAME
				// Call CCB api to update First & Last name for this CCB User ID
				$.ajax({
						type: "POST",
						url: site_url+'/_component/ccb_update_individual/',
						data: "individual_id="+newccbuid+"&first_name="+newfirstname+"&last_name="+newlastname,
						async: false,
						success: xmlParserUpdateIndividual,             // name of the function to call upon success
						error: function(jqXHR, textStatus, errorThrown) {ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_EMAIL:		// UPDATE_EMAIL
				// Call CCB api to retrieve login & password for this CCB User ID
				$.ajax({
						type: "POST",
						url: site_url+'/_component/ccb_individual_credentials/',
						data: "id="+newccbuid,
						async: false,
						success: xmlParserIndividualCredential,             // name of the function to call upon success
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_PASSWD:		// UPDATE_PASSWD
				// Call CCB api to retrieve login & password for this CCB User ID
				$.ajax({
						type: "POST",
						url: site_url+'/_component/ccb_individual_credentials/',
						data: "id="+newccbuid,
						async: false,
						success: xmlParserIndividualCredential,             // name of the function to call upon success
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			default:
				break;
		}

	} else {
		ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + data.message);
	}

//	return false;
}

// Called after succeeding in individual_credentials_from_id CCB api
// Display messages when it encounters error
// Trying to set username & password for CCB User ID, otherwise
function xmlParserIndividualCredential(str)
{
    var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	///console.log(errors.join("\n"));
    	ShowTextModal(errors.join("\n"));
    } else {
		newccbuid = $(xml).find("individual").attr("id");
		switch (g_cur_process)
		{
			case UPDATE_EMAIL:		// UPDATE_EMAIL
				// Update login with new email and same password
				var ccblogin = newemail;
				newpassword = $(xml).find("individual").find("password").text();
		
				///console.log('CCB User ID: '+ ccbuid);
//				console.log('CCB Login: '+ ccblogin);
//				console.log("CCB Password: " + newpassword);
				
				// Call CCB api to set username & password
				$.ajax({
						type: "POST",
						url: site_url+'/_component/ccb_set_individual_credential/',
						data: "id="+newccbuid+"&username="+ccblogin+"&password="+newpassword,
						async: false,
						success: xmlParserUpdateCredential,             // name of the function to call upon success
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_PASSWD:		// UPDATE_PASSWD
				// Update login with same email and new password
				var ccblogin 	= $(xml).find("individual").find("login").text();
				var ccbpassword 	= $(xml).find("individual").find("password").text();
		
				///console.log('CCB User ID: '+ ccbuid);
//				console.log('CCB Login: '+ ccblogin);
//				console.log("CCB Password: " + ccbpassword);
				
				if (oldpassword != ccbpassword) {
					///console.log("The password did not match.");
					ShowTextModal("The password you entered is incorrect. Please try again.");
					return false;
				} else {
					// Call CCB api to set username & password
					$.ajax({
							type: "POST",
							url: site_url+'/_component/ccb_set_individual_credential/',
							data: "id="+newccbuid+"&username="+ccblogin+"&password="+newpassword,
							async: false,
							success: xmlParserUpdateIndividual,             // name of the function to call upon success
							error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
					});
				}
				break;
			default:
				break;
		}
	}
}

// Called after succeeding in set_individual_credentials CCB api
// Display messages when it encounters error
// Trying to update email address, otherwise
function xmlParserUpdateCredential(str)
{
	var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	///console.log(errors.join("\n"));
    	ShowTextModal(errors.join("\n"));
    } else {
	
		$(xml).find("individual").each(function() {
			var ccbuid = $(this).attr("id");
			var ccblogin = $(this).find("login").text();
//			console.log('Succeed to set username and password for: '+ ccblogin);
//			alert('Success to set username and password for: '+ ccblogin);
	
			// Call CCB api to update Email for this CCB User ID
			$.ajax({
					type: "POST",
					url: site_url+'/_component/ccb_update_individual/',
					data: "individual_id="+newccbuid+"&email="+newemail,
					async: false,
					success: xmlParserUpdateIndividual,             // name of the function to call upon success
					error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
			});
	
		});
	}

}

// Called after succeeding in update_individual CCB api
function xmlParserUpdateIndividual(str)
{
    var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	ShowTextModal(errors.join("\n"));
    	///console.log(errors.join("\n"));
    } else {
//		console.log('Calling Hub Sync Scripts...');

		switch (g_cur_process)
		{
			case EMAIL_CHK_SIGNIN:		// Email Check in Signin
			case EMAIL_CHK_REGISTER:		// Email Check in Register
				// Call Hub sync script
				$.ajax({
						type: "GET",
						url: '/scripts/exec_hub_sync.php',
						async: false,
						success: sendResetPassword,  
/*
						success: function(data) { 
							alert("Your information for re-syncing has been successfully done.");
		//						window.location.reload();
						}, 
*/
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_NAME:		// UPDATE_NAME
				// Call Hub sync script
				$.ajax({
						type: "GET",
						url: '/scripts/exec_hub_sync.php',
						async: false,
						success: function(data) { 
							ShowTextModal("Your name has been successfully changed.");
		//						window.location.reload();
						}, 
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_EMAIL:		// UPDATE_EMAIL
				// Call Hub sync script
				$.ajax({
						type: "GET",
						url: '/scripts/exec_hub_sync.php',
						async: false,
						success: function(data) { 
							alert("Your Email has been successfully changed.");
		//						window.location.reload();
						}, 
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			case UPDATE_PASSWD:		// UPDATE_PASSWD
				// Call Hub sync script
				$.ajax({
						type: "GET",
						url: '/scripts/exec_hub_sync.php',
						async: false,
						success: function(data) { 
							alert("Your Password has been successfully changed.");
		//						window.location.reload();
						}, 
						error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
				});
				break;
			default:
				break;
		}

	}
}

/* ***************************************************************************** */
// End of Functions for Edit Profile
/* ***************************************************************************** */

function startPickedAccountSyncing(pickedMemId) {
    $.ajax({
			url: '/scripts/get_ee_members_for_email.php',
			data: "email=" + newemail,
			dataType: 'json',
			success: function(data) { 
				var jsonObj = $.parseJSON(data);

				if(jsonObj.result == "success") 
				{
					for(var i=0; i<jsonObj.members.length; i++) 
					{
						var eememId = jsonObj.members[i].memberid;
//						console.log(eememId);

						if(pickedMemId == eememId) 
						{
							$.ajax({
									url: '/scripts/get_ccb_id_for_ee_member_id.php',
									data: "memberid=" + eememId,
									dataType: 'json',
//									success: processIndividualChange,
									success: processForgotPassword,
									error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
							});
						} 
						else 
						{
							// Retrieve CCB ID for EE Member ID from Hub table
							$.ajax({
									url: '/scripts/get_ccb_id_for_ee_member_id.php',
									data: "memberid=" + eememId,
									dataType: 'json',
									success: changeHubEmailAddresBySystem,
									error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
							});

							// Update EE Email address (prefixed with 'nacd_disabled_') in EE table
							$.ajax({
									url: '/scripts/update_ee_email_for_id.php',
									data: "memberid=" + eememId + "&email=" + newemail,
									dataType: 'json',
									success: function(data) { 
//										console.log("Pre-fixed(nacd_disabled) Email in EE update done.");
									}, 
									error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
							});
						}
					}

				} else {
					alert("Error: " + data.message);
				}
			}, 
			error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
	});
}

// Update Email address in Hub table 
function changeHubEmailAddresBySystem(data) 
{ 
	if(data.result == "success") 
	{
		var nonPickedCCBId = data.ccbuid;

		// Call PHP script to update email address in sync_members table at HUB. 
		$.ajax({
				url: '/scripts/update_hub_email_for_id.php',
				data: "memberid=" + nonPickedCCBId + "&email=" + newemail,
				dataType: 'json',
				success: function(data) { 
//					console.log("Pre-fixed(nacd_disabled) Email in HUB update done.");
				}, 
				error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
		});

	} else {
		ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + data.message);
	}
}


function startPasswordRecovery() {
    $.ajax({
			url: '/scripts/get_ee_member_id_for_email.php',
			data: "email=" + newemail,
			dataType: 'json',
			success: function(data) { 
				if(data.result == "success") {
					eememberid = data.memberid;
					///console.log("EE Member ID: " + eememberid);
					
						$.ajax({
								url: '/scripts/get_ccb_id_for_ee_member_id.php',
								data: "memberid=" + eememberid,
								dataType: 'json',
								success: processForgotPassword,
								error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
						});
				} else {
					alert("Error: " + data.message);
				}
			}, 
			error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
	});
}

// process data (JSON object) to get CCB User ID
// Then, call CCB api to retrieve login & password from ccb user id
function processForgotPassword(data) { 
	if(data.result == "success") {
		newccbuid = data.ccbuid;
		///console.log("CCB Member ID: " + newccbuid);

		// Call CCB api to retrieve login & password for this CCB User ID
		$.ajax({
				type: "POST",
				url: site_url+'/_component/ccb_individual_credentials/',
				data: "id="+newccbuid,
//				async: false,
				success: xmlParserCredential,             // name of the function to call upon success
				error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
		});

	} else {
		ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + data.message);
	}
}

// Called after succeeding in individual_credentials_from_id CCB api
// Display messages when it encounters error
// Trying to set login & random password for CCB User ID, otherwise
function xmlParserCredential(str)
{
//    alert(str);
    var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	///console.log(errors.join("\n"));
    	ShowTextModal(errors.join("\n"));
    } else {
        if ($(xml).find("individuals").attr("count") == 0) {
            ShowTextModal("This email does not exist in CCB. Please contact the web minister with this error.");
        } else {
		// Create random password and assign login
		var ccbuid = $(xml).find("individual").attr("id");
		var ccblogin = $(xml).find("individual").find("login").text();
		newpassword = randomString();

		if (ccblogin == null || ccblogin == "")  {
			ccblogin = newemail;
		}
		///console.log('CCB User ID: '+ ccbuid);
		///console.log('CCB Login: '+ ccblogin);
		///console.log("New Random Password: " + newpassword);
		
		// Call CCB api to set username & password
		$.ajax({
				type: "POST",
				url: site_url+'/_component/ccb_set_individual_credential/',
				data: "id="+newccbuid+"&username="+ccblogin+"&password="+newpassword,
//					async: false,
				success: xmlParserCredentialForForgotPassword,             // name of the function to call upon success
				error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
		});
	}
    }
}

// Called after succeeding in set_individual_credentials CCB api
// Display messages when it encounters error
// Trying to call Hub Sync Scripts, otherwise
function xmlParserCredentialForForgotPassword(str)
{
//    alert(str);

	var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	///console.log(errors.join("\n"));
    	ShowTextModal(errors.join("\n"));
    } else {
	
		$(xml).find("individual").each(function() {
			var ccbuid = $(this).attr("id");
			var ccblogin = $(this).find("login").text();
			///console.log('Succeed to set username and password for: '+ ccblogin);
//			alert('Success to set username and password for: '+ ccblogin);
	
			///console.log('Calling Hub Sync Scripts...');
			// Call Hub sync script
			$.ajax({
					type: "GET",
					url: '/scripts/exec_hub_sync.php',
					async: false,
					success: sendResetPassword,  
//					success: function(data) { 
//						alert("Reset password sent to " + newemail + ".\nPlease check your email and try logging in.");
//						window.location.reload();
//					}, 
					error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the error: " + textStatus); }
			});
	
		});
	}

}


function sendResetPassword(str) {
	var datastr = 'mailto=' + newemail + '&resetpw=' + newpassword;	
	setTimeout("sendPWResetEmail('"+datastr+"')", 1000);
}

function sendPWResetEmail(datastr) {
//$("#show_text_modal").trigger('click');
	$.ajax({
		type: "POST",
		url: '/scripts/nacd_pw_reset_mail.php',
		data: datastr, 
		cache: false,
		success: function(html) {	
			ShowTextModal("Reset password sent to " + newemail + ".\nPlease check your email and try logging in.");
			//alert("Reset password sent to " + newemail + ".\nPlease check your email and try logging in.");
//			window.location.reload();
		},
		error: function() { ShowTextModal("Oops, something went wrong. Please contact us and we will check out the problem for you."); }
	});
	
}

// Called after succeeding in create_individual CCB api
// Then, assign Username & Password in CCB
function xmlParserCreate(str)
{
//    alert(str);
    var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });


    if (errors.length > 0) {
    	ShowTextModal(errors.join("\n"));
    	///console.log(errors.join("\n"));
    } else {

		$(xml).find("individual").each(function() {
			newccbuid = $(this).attr("id");

			// Call CCB api to set username & password
			$.ajax({
					type: "POST",
					url: site_url+'/_component/ccb_set_individual_credential/',
					data: "id="+newccbuid+"&username="+newemail+"&password="+newpassword,
					async: false,
					success: xmlParserSetCredential,             // name of the function to call upon success
					error: function() { ShowTextModal("Oops, something seems to have gone wrong."); }
			});
		});
	}
}

// Called after succeeding in set_individual_credentials CCB api
// Inactive individual when it contains error
// Trying to call Hub Sync Scripts, otherwise
function xmlParserSetCredential(str)
{
//    alert(str);
    var xml = parseXml(str);
	var errors 	= new Array();
	
    $(xml).find("error").each(function() {
	    var msg = $(this).text();
	    errors.push(msg);
    });

    if (errors.length > 0) {
    	ShowTextModal(errors.join("\n"));
    	///console.log(errors.join("\n"));
		
		// Call CCB api to make this inidividual inactive
        $.ajax({
                type: "POST",
                url: site_url+'/_component/ccb_inactivate_individual/',
                data: "id="+newccbuid,
                async: false,
				success: xmlParserInactivate, 
                error: function() { ShowTextModal("Oops, something seems to have gone wrong."); }
        });
		
    } else {
	
		$(xml).find("individual").each(function() {
			var ccbuid = $(this).attr("id");
			var ccblogin = $(this).find("login").text();
			///console.log('Success to set username and password for: '+ ccblogin);
//			alert('Success to set username and password for: '+ ccblogin);
	
			///console.log('Calling Hub Sync Scripts...');
			// Call Hub sync script
			$.ajax({
					type: "GET",
					url: '/scripts/exec_hub_sync.php',
					async: false,
					success: autoLogin, 
					error: function() { ShowTextModal("Oops, something seems to have gone wrong."); }
			});
	
		});
	}
}

function xmlParserInactivate(str)
{
//    alert(str);
    var xml = parseXml(str);

    $(xml).find("individual").each(function() {
        var elName = $(this).find('name').text();
        var elInactive = $(this).find('inactive').text();
        var elSuccess = $(this).find("success").text();

		if (elInactive == 'true' && elSuccess == 'true') {
			///console.log(elName + '(' + newccbuid + ') has been inactivated in CCB.');
			ShowTextModal(elName + '(' + newccbuid + ') has been inactivated in CCB.');
		} else {
			///console.log(elName + '(' + newccbuid + ') can not been inactivated in CCB.');
			ShowTextModal(elName + '(' + newccbuid + ') can not been inactivated in CCB.');
		}
    });

}

var currentLoginTrial = 0;
var maxLoginTrial = 2;
// Called after succeeding in Hub Sync Scripts
// Then, try auto-login
function autoLogin(data) {

	currentLoginTrial++;
	///console.log(currentLoginTrial + ' time(s) trial\n' + data);
/*	
	// Test data
	if (currentLoginTrial < maxLoginTrial) {
		newemail = 'khpang@earthlink.net';
		newpassword = '111111';
	} else {
		newemail = 'khpang@earthlink.net';
		newpassword = '111111';
	}
	newfirstname = 'KeeTest';
	newlastname = 'Pang';
	// Test data
*/
	$.ajax({
			type: "POST",
			url: site_url + '/index.php',
			data: "username="+newemail+"&password="+newpassword+"&ACT=9"+"&RET='"+site_url+"/index.php/prelaunchmain/register_success"+"&site_id=1",
			async: false,
			success: processAutoLogin,
			error: function() { ShowTextModal("Oops, something seems to have gone wrong."); }
	});

}

// Called after succeeding in auto-login
// Try maxLoginTrial times, 
// If can not login, then create an EE account directly
function processAutoLogin(data) { 

	d2 = new Date(); 
	diff = d2 - d1;
//	///console.log(data);
	///console.log("Processing time: " + diff + " milliseconds");

	var locTitle = data.search(/<title>/);
	var titleContent = data.substr(locTitle+7, 5);
	if(titleContent == 'Error')
	{
		// if errors
		var err = "There were errors found in your entry:\n";
		$(data).find('li').each(function() {
			err += "\t" + $(this).text() + "\n";
		});
		///console.log(err); // Alert the error which will detail all the values of the <li> (i.e the errors!)
		
		if (currentLoginTrial < maxLoginTrial) {
			// Try more until it reaches maxLoginTrial
			autoLogin ("Try again");
		} else if (currentLoginTrial == maxLoginTrial) {
			// Can not login due to Hub Sync problem. Create an account in EE
			///console.log("Failed to auto-login due to system failure in Hub Server. Now, creating user account in EE and let this user login.");
			// Create an EE acount and try auto-login again
			createEEAccount();
		} else {
			// Can not even create an EE account due to some problem. You can check error message.
			ShowTextModal(err + "Not able to login EE after creating an EE acount. Please contact the web minister.");
		}
	}
	else
	{
		// There was no error, so we're going to redirect the user to the next step now 
		// (set in the RETURN_URL form field)				
		//alert("Logged in");
		
		
		//anon_faves scoped in the header file as an array holding all the favorites made when the user was anonymous.
		//this copies those to the new user's account. No garbage cleanup now - going to institure rolling cleanup going forward
		///console.log(anon_faves[0]);
		for (var i = 0; i < anon_faves.length; i++){
			$.ajax({
				url: "/_component/favorite-add/"+anon_faves[i]+"/"
			});
		}
		
//		location.replace( "http://www.northlandchurch.net"); 
	}

}

function createEEAccount() {

	newusername = newemail.replace("@", "_");
	$.ajax({
			type: "POST",
			url: site_url+'/index.php',
			data: "username="+newusername+"&email="+newemail+"&password="+newpassword+"&password_confirm="+newpassword+"&accept_terms="+acceptTerms+"&screen_name="+newfirstname + " " + newlastname +"&ACT=98"+"&RET='"+site_url+"/index.php/prelaunchmain/register_success'"+"&group_id='11'"+"&site_id=1",
			async: false,
			success: afterCreateEEAccount,
			error: function() { ShowTextModal("Oops, something seems to have gone wrong"); }
	});
}

function afterCreateEEAccount(data) { 

	d2 = new Date(); 
	diff = d2 - d1;
//	///console.log(data);
	///console.log("Processing time: " + diff + " milliseconds");

	var locTitle = data.search(/<title>/);
	var titleContent = data.substr(locTitle+7, 5);
	if(titleContent == 'Error')
	{
		var err = "There were errors found in your entry:\n";
		$(data).find('li').each(function() {
			// the error which will detail all the values of the <li> (i.e the errors!)
			err += "\t" + $(this).text() + "\n";
		});
		// Can not even create an EE account due to some problem. You can check error message.
		///console.log(err); 
		ShowTextModal("Not able to create an EE account. Please contact the web minister and tell them the error you got was: " + err);
	}
	else
	{
		///console.log("Success to create an EE account");
		autoLogin("After creating an EE account");
//					location.replace( "http://www.northlandchurch.net"); 
	}

}


function emailValidation(x) 
{
	switch (g_cur_process)
	{
		case EMAIL_CHK_SIGNIN:		// EMAIL_CHK_SIGNIN
			if (!isValidEmail(x)) {
//				console.log("We need a valid email to proceed in Sign In");
				$("#no-email").hide();				
				$("#multiple_account1").hide();
				$("#multiple_account2").hide();
				$("#email_invalid").show();
				$("#username").focus();
			} else {
//				console.log("Valid email address through Sing In, dupe checking...");

				$.ajax({
					url: '/scripts/check_email_unique_v2.php',
					data: "email=" + x,
					dataType: 'json',					
					success: parseEmailCheck, 
					error: function() { ShowTextModal("Error in email duplicate checking..."); }
				});
			}
			break;
		case EMAIL_CHK_REGISTER:		// EMAIL_CHK_REGISTER
			if (!isValidEmail(x)) {
//				console.log("We need a valid email to proceed in Register");
				$("#existing_account1").hide();
				$("#existing_multiple_account1").hide();
				$("#existing_multiple_account2").hide();
				$("#email_invalid1").show();
				$("#wrap_email").addClass('form_error');
				$("#emailnew").focus();
			} else {
//				console.log("Valid email address through Register, dupe checking...");
				$("#wrap_email").removeClass('form_error');
				$("#email_invalid1").hide();

				$.ajax({
					url: '/scripts/check_email_unique_v2.php',
					data: "email=" + x,
					dataType: 'json',					
					success: parseEmailCheck, 
					error: function() { ShowTextModal("Error in email duplicate checking..."); }
				});
			}
			break;
		case EMAIL_SYNC:		
			if (!isValidEmail(x)) {
//				console.log("We need a valid email to proceed in Sync");
//				$("#existing_account1").hide();
				$("#init_multiple_account1").hide();
				$("#init_multiple_account2").hide();
				$("#email_invalid2").show();
				$("#initemail").focus();
			} else {
//				console.log("Valid email address through Sync, dupe checking...");
				$("#email_invalid2").hide();

				$.ajax({
					url: '/scripts/check_email_unique_v2.php',
					data: "email=" + x,
					dataType: 'json',					
					success: parseEmailCheck, 
					error: function() { ShowTextModal("Error in email duplicate checking..."); }
				});

			}
			break;
		default:
			break;
	}

}


function parseEmailCheck(data) 
{ 
	var jsonObj = $.parseJSON(data);

	switch (g_cur_process)
	{
		case EMAIL_CHK_SIGNIN:		// EMAIL_CHK_SIGNIN
			var x = $("#username").val();
			
			if(jsonObj.result == "unique") 
			{
				canEmailProcess =true;
				$("#email_invalid").hide();
				$("#login-forgot-pass").hide();
				$("#multiple_account1").hide();
				$("#multiple_account2").hide();
				$("#no-email").show();				
				$("#password").focus();
//				console.log("This email address doesn't exist in our system.");
			} 
			else if (jsonObj.result == "duplicate") 
			{
				canEmailProcess = false;
				if (jsonObj.count == 1) 
				{
//					$("#your_email").html(x);
					$("#email").val(x);
					$("#no-email").hide();				
					$("#email_invalid").hide();
					$("#multiple_account1").hide();
					$("#multiple_account2").hide();
					$("#login-forgot-pass").hide();
//					console.log("There is only 1 account in our system.");
				} 
				else if (jsonObj.count > 1) 
				{
					$("#your_email").html(x);
					$("#no-email").hide();				
					$("#email_invalid").hide();
					$("#login-forgot-pass").hide();

					var htmlEntity = '<br />Choose your name below: <br />';
					for(var i=0; i<jsonObj.count; i++) {
//						console.log(i + ": " + jsonObj.members[i].screen_name);
						htmlEntity +=  '<input type="radio" name="group1" value="' + jsonObj.members[i].member_id+ '">' + jsonObj.members[i].screen_name;
					}
					htmlEntity += '</p>';
					$("#multiple_account2").html(htmlEntity);

					$("#multiple_account1").show();
					$("#multiple_account2").show();
				} 
				else 
				{
		//			console.log("Unknown number of email accounts.");
					ShowTextModal("Unknown number of email accounts.");
				}
			} else {
		//		console.log("No result returned.");
				ShowTextModal("No return for e-mail check. Please contact the web minister.");
			}
			break;
		case EMAIL_CHK_REGISTER:		// EMAIL_CHK_REGISTER
			var x = $("#emailnew").val();
			
			if(jsonObj.result == "unique") 
			{
				canEmailProcess =true;
				$("#existing_account1").hide();
				$("#existing_multiple_account1").hide();
				$("#existing_multiple_account2").hide();
				$("#email_invalid").hide();
				$("#firstnamenew").focus();
//				console.log("You can use email address.");
			} 
			else if (jsonObj.result == "duplicate") 
			{
				canEmailProcess = false;
				if (jsonObj.count == 1) 
				{
//					console.log("the number of email: " + jsonObj.count);
					$("#your_email1").html(x);
					$("#email").val(x);
					$("#email_invalid").hide();
					$("#existing_multiple_account1").hide();
					$("#existing_multiple_account2").hide();
					$("#existing_account1").show();
				} 
				else if (jsonObj.count > 1) 
				{
//					console.log("the number of email: " + jsonObj.count);
					$("#your_email2").html(x);
					$("#email").val(x);
					$("#email_invalid").hide();
					$("#existing_account1").hide();

					var htmlEntity = '<br />Choose your name below: <br />';
					for(var i=0; i<jsonObj.count; i++) {
//						console.log(i + ": " + jsonObj.members[i].screen_name);
						htmlEntity +=  '<input type="radio" name="group2" value="' + jsonObj.members[i].member_id+ '">' + jsonObj.members[i].screen_name;
					}
					htmlEntity += '</p>';
					$("#existing_multiple_account2").html(htmlEntity);

					$("#existing_multiple_account1").show();
					$("#existing_multiple_account2").show();
				} 
				else 
				{
		//			console.log("Unknown number of email accounts.");
					ShowTextModal("Unknown number of email accounts.");
				}
			} 
			else 
			{
		//		console.log("No result returned.");
				ShowTextModal("No return for e-mail check. Please contact the web minister.");
			}
			break;
		case EMAIL_SYNC:		// 
			var x = $("#initemail").val();
			
			if(jsonObj.result == "unique") 
			{
//				console.log("This email address doesn't exist in our system.");
				canEmailProcess =true;
				$("#email_invalid2").hide();
//				$("#login-forgot-pass").hide();
				$("#init_multiple_account1").hide();
				$("#init_multiple_account2").hide();
				$("#no-email2").show();				
				$("#initemail").focus();
			} 
			else if (jsonObj.result == "duplicate") 
			{
				canEmailProcess = false;
				if (jsonObj.count == 1) 
				{
//					console.log("There is only 1 account in our system.");
//					$("#your_email2").html(x);
//					$("#email").val(x);
					$("#no-email2").hide();				
					$("#email_invalid2").hide();
					$("#init_multiple_account1").hide();
					$("#init_multiple_account2").hide();
					eememberid = jsonObj.members[0].member_id

					// Checking email existence in InSite system
					$.ajax({
						url: '/scripts/check_email_insite.php',
						data: "email=" + x,
						dataType: 'json',					
						success: parseEmailCheckInsite,
						error: function() { ShowTextModal("Error in email duplicate checking..."); }
					});
					
				} 
				else if (jsonObj.count > 1) 
				{
					$("#init_email").html(x);
					$("#no-email2").hide();				
					$("#email_invalid2").hide();

					var htmlEntity = '<br />Choose your name below: <br />';
					for(var i=0; i<jsonObj.count; i++) {
//						console.log(i + ": " + jsonObj.members[i].screen_name);
						htmlEntity +=  '<input type="radio" name="group3" value="' + jsonObj.members[i].member_id+ '">' + jsonObj.members[i].screen_name;
					}
					htmlEntity += '</p>';
					$("#init_multiple_account2").html(htmlEntity);

					$("#init_multiple_account1").show();
					$("#init_multiple_account2").show();
				} 
				else 
				{
		//			console.log("Unknown number of email accounts.");
					ShowTextModal("Unknown number of email accounts.");
				}
			} else {
		//		console.log("No result returned.");
				ShowTextModal("No return for e-mail check. Please contact the web minister.");
			}
			break;
			default:
			break;
	}
}

function parseEmailCheckInsite(data) 
{ 
	var jsonObj = $.parseJSON(data);

	switch (g_cur_process)
	{
		case EMAIL_SYNC:		// 
//			var x = $("#initemail").val();
			newemail = $("#initemail").val();
			
			if(jsonObj.result == "not found") 
			{
//				console.log("This email address doesn't exist in InSite system.");
				canEmailProcess = true;
				$("#email_invalid2").hide();
//				$("#login-forgot-pass").hide();
				$("#init_multiple_account1").hide();
				$("#init_multiple_account2").hide();
				$("#no-email2").hide();				
//				$("#initemail").focus();
				
				// Create a new account in InSite
			} 
			else if (jsonObj.result == "found") 
			{
				canEmailProcess = false;
				if (jsonObj.count == 1) 
				{
//					console.log("There is only 1 account in InSite system.");

					var personid = jsonObj.emails[0].person_id;
					$("#no-email2").hide();				
					$("#email_invalid2").hide();
					$("#init_multiple_account1").hide();
					$("#init_multiple_account2").hide();

					// Tie this EE/CCB member into InSite
					$.ajax({
							url: '/scripts/update_insite_appuser_eeid.php',
							data: "memberid=" + eememberid + "&personid=" + personid,
							dataType: 'json',
							success: function(data) { 
//								console.log("EE ID in Insite update done.");

								startPasswordRecovery();
//								alert("Your account has been synced.");
							}, 
							error: function(jqXHR, textStatus, errorThrown) { ShowTextModal("Oops, something seems to have gone wrong. Please contact the web minister with the following info: " + textStatus); }
					});
					
				} 
				else 
				{
		//			console.log("Unknown number of email accounts.");
					ShowTextModal("Unknown number of email accounts.");
				}
			} else {
		//		console.log("No result returned.");
				ShowTextModal("No return for e-mail check. Please contact the web minister.");
			}
			break;
			default:
			break;
	}


}




