﻿/**
user is trying to sign in with existing details
**/
function onSignInClick(){
	// attempt to login an existing user
	$.post("classes/Interface.php",{
		'function':'attemptLogin', 
		'username':$('#username').val(),
		'password':$('#password').val()
	}, 
	function(data){
		// data =  uid
		if (data == ""){
			alert("The username and / or password are incorrect. Please re-enter your details and try again.");
			$('#password').val("");
		}
		else {
			// alert("OK! Your uid: "+data);
			post("manageaccount.php", 
				{uid:data}
			);
		}
	}); 
}// end onSignInClick()
		
function submitLoginenter(myfield,e)	{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		onSignInClick();
		return false;
	}
	else
		return true;
}

function submitRegisterenter(myfield,e)	{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		onRegisterClick();
		return false;
	}
	else
		return true;
}

/**
user wants to create a new account - check if the name is available
**/
function onRegisterClick(){
	// basic check to ensure registration name isn't blank, or too long or too short
	if (
		$('#registername').val().length < 6 ||
		$('#registername').val().length > 16 ||
		$('#registername').val().search(' ') > -1			
	){
		//alert("Please enter your desired username in the registration field.");
		alert("Please ensure your username is more than 6 but less than 16 characters long & doesn't contain spaces.");
		return;
	}
	
	if ( !getValidUsername($('#registername').val()) ){
		alert("Please ensure your username contains only numbers and lowercase letters. Special characters and spaces are not allowed.");
		return;
	}
	
	// check if username has been taken.
	$.post("classes/Interface.php",{
		'function':'getUsernameAvailable', 
		'username':$('#registername').val()
	}, 
	function(data){
		if (data == false){
			//alert("The username IS NOT available");
			//window.location = "usernametaken.php?username="+$('#registername').val();
			post("usernametaken.php", 
				{username:$('#registername').val()}
			);
		}
		else {
			post("registration.php", 
				{username:$('#registername').val()}
			);
		}
	}); 
			
	/**
	create a temporary form and post - can't jquery do this anyway??
	good code - need to cite
	**/
	function post(URL, PARAMS) {
		var temp=document.createElement("form");
		temp.action=URL;
		temp.method="POST";
		temp.style.display="none";
		for(var x in PARAMS) {
			var opt=document.createElement("textarea");
			opt.name=x;
			opt.value=PARAMS[x];
			temp.appendChild(opt);
		}
		document.body.appendChild(temp);
		temp.submit();
		return temp;
	} // end post
	
} 
		
	
// username can only be lowercase, number or underscore:
function getValidUsername(val)
{ 
	if (val.match(/^[a-z_0-9]+$/))
		return true;
		
	else return false;

}
	
function post(URL, PARAMS) {
	var temp=document.createElement("form");
	temp.action=URL;
	temp.method="POST";
	temp.style.display="none";
	for(var x in PARAMS) {
		var opt=document.createElement("textarea");
		opt.name=x;
		opt.value=PARAMS[x];
		temp.appendChild(opt);
	}
	document.body.appendChild(temp);
	temp.submit();
	return temp;
} // end post

/**
get the details about the free, personal, busiess, or professional account:
**/
function getUserActivity($uid){
	$.getJSON("classes/Interface.php",{
		'function':'getUserActivity',
		'uid':$uid
	}, 
	
	function(data){
		$("#table-zebra").append(
				"<tr><td><b>Activity</b></td><td><b>No. Times</b></td><td><b>First Occasion</b></td><td><b>Last Occasion</b></td></tr>");
		$.each(data, function() {
			$("#table-zebra").append(
				"<tr><td>"+this.Activity+"</td><td>"+this.NumberOfTimes+"</td><td>"+this.FirstDid+"</td><td>"+this.LastDid+"</td></tr>");
		});
	});	
} // end getUserActivity()

/**
user is trying to sign in with existing details
**/
function onSignInClick(){
	// attempt to login an existing user
	$.post("classes/Interface.php",{
		'function':'attemptLogin', 
		'username':$('#username').val(),
		'password':$('#password').val()
	}, 
	function(data){
		// data =  uid
		if (data == ""){
			alert("Either your username or password were incorrect. Please check your details and try again.");
			$('#password').val("");
		}
		else {
			post("manageaccount.php", 
				{uid:data}
			);

		}
	}); 
}// end onSignInClick()
	
function submitLoginenter(myfield,e)	{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		onSignInClick();
		return false;
	}
	else
		return true;
}

function submitRegisterenter(myfield,e)	{
	var keycode;
	
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
	{
		onRegisterClick();
		return false;
	}
	else
		return true;
}

function logout(){
	$.post("classes/Interface.php",{
		'function':'logout'
		}, 
		function(data){
			alert('You have successfully logged out.');
			window.location = "login.php";
		}
	);	
}

function upgrade(){
	alert('upgrade not yet available - Business & Professional Accounts will be launched soon.');
}

/**
user wants to create account - perform checks before going any farther
**/
function onCreateClick(){

	// CHECK #01: check there are no empty fields
	if (
		$('#email').val() == "" ||
		$('#email2').val() == "" ||
		$('#password').val() == "" ||
		$('#password2').val() == "" ||
		$('#firstname').val() == "" ||
		$('#surname').val() == "" ||
		$('#mainphone').val() == "" ||
		$('#country').val() == ""
		// NB. select box is always populated 
	)
	{
		alert("Please ensure you have entered values for ALL fields.");
		return;
	}
	
	// check emails match
	if ($('#email').val() != $('#email2').val()) {
		alert("Please check the EMAIL address matches in both email fields.");
		return;
	}
	
	// email validity check
	if (!echeck($('#email').val())){
		alert("Please enter a valid EMAIL address in both email fields.");
		return;
	}
	
	// check passwords match
	if ($('#password').val() != $('#password2').val()) {
		alert("Please check the PASSWORD matches in both password fields.");
		return;
	}
	
	// basic check to ensure password isn't blank, or too long or too short
	if (
		$('#password').val().length < 6 ||
		$('#password').val().length > 16 ||
		$('#password').val().search(' ') > -1			
	){
		//alert("Please enter your desired username in the registration field.");
		alert("Please ensure your PASSWORD is more than more than 6 but less than 16 characters long & doesn't contain spaces.");
		return;
	}

	// TODO: check for basic email structure: string@string[dot]string
	createUserAccount();

} // end onCreateClick()


/**
here we send the user details off to be entered in the 
**/
function createUserAccount(){
	
	$.post("classes/Interface.php",{
		'function':'createUserAccount', 
		'username':$('#username').val(),
		'password':$('#password').val(),
		'email':$('#email').val(),
		'firstname':$('#firstname').val(),
		'surname':$('#surname').val(),
		'title':$('#title option:selected').val(),
		'country':$('#country option:selected').val(),
		'mainphone':$('#mainphone').val(),
		'companyposition':$('#companyposition').val(),
		'companyname':$('#companyname').val()


	}, 
	
	function(data){

		// with the new uid created we load the manage account page 
		post("manageaccount.php", 
			{uid:data}
		);
		
	});	
} // end createUserAccount()

/**
email validity check - http://www.smartwebby.com/dhtml/email_validation.asp
**/
function echeck(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false;
	 }

	 return true;
}

function sendFile($email,$name,$filedata){
	
}

function sendEmail($uid){
	// CHECK #01: check there are no empty fields
	if (
		$('#email').val() == "" ||
		$('#name').val() == "" ||
		$('#enquiry').val() == ""

		// NB. select box is always populated 
	) {
		alert("Please ensure you have entered values for ALL fields.");
		return;
	}

	$.post("classes/Interface.php",{
		'function':'sendEmail',
		'uid':$uid,
		'name':$('#name').val(),
		'email':$('#email').val(),
		'body':$('#enquiry').val(),				
		'title':$('#Subject option:selected').val()

	}, 
	
	function(data){
		if (!data){
			alert("There was a problem sending your email. If the problem persists please contact our support team.");
		}
		else{
			alert("Your email has been sent. Thank you for taking the time to contact us.");
			window.location = "index.php"
		}
	});	
}

// user clicked to recieive new password
function onSendClick(){
	var isValidUsername = true;
	var isValidEmail = true;
	
	if (
		$('#registername').val().length < 6 ||
		$('#registername').val().length > 16 ||
		!getValidUsername($('#registername').val())
	){
		isValidUsername = false;
	}
	
	if (!echeck($('#registername').val())){
		isValidEmail = false;
	}
	
	// if nither password or potential username - tell user & quit
	if (!isValidEmail && !isValidUsername){
		alert('The text entered is neither a valid username or password. Please try again or contact the sparkol support team.')
		return;
	}
	
	if (isValidEmail){
		tryToSendEmail();
	}
	else tryToSendEmailToMatchingUsername();
		
	
}

/**
check DB and if email exists, create new password and send to user
**/
function tryToSendEmailToMatchingUsername(){

	$.post("classes/Interface.php",{
		'function':'attemptCreateNewPassword_username', 
		'username':$('#registername').val()
	}, 
	function(data){
		// data =  uid
		
		if (!data){
			alert("This username does not exist on our system. Please double check the username entered or submit the matching email address.");
		}
		else {
			alert("Thank you. A new password has been created and sent to the email account matching the submitted username.");
			window.location = "login.php"
		}
	}); 
}

/**
check DB and if email exists, create new password and send to user
**/
function tryToSendEmail(){
	// attempt to login an existing user
	$.post("classes/Interface.php",{
		'function':'attemptCreateNewPassword_email', 
		'email':$('#registername').val()
	}, 
	function(data){
		// data =  uid
		
		if (!data){
			alert("This email address does not exist on our system. Please double check the email entered or submit your username.");
		}
		else {
			alert("Thank you. A new password has been created and sent to the submitted email account.");
			window.location = "login.php"
		}
	}); 
}

function recommendFriends($uid){
	var friend1='';
	var friend1email='';
	var fromname=$('#sendername').val(); 
	var fromemail=$('#email').text();
	var message=$('#sparkolMessage').val();
	var oneWrong=false;
	var lastemail=$('#email1').val();
	
	// loop...
	for (var i=4;i>0;i--) {
		friend1 = $('#name'+i).val();
		friend1email = $('#email'+i).val();
		
		if (friend1email=='(email)') {
			// nothing has been completed...
		} else {
			if (!echeck(friend1email)){
				oneWrong=true;
				alert("The email address "+friend1email+" is invalid, please check you entered correct details.");
			} else {
				$.post("classes/Interface.php",{
					'function':'sendAndLogInviteEmail',
					'uid':$uid,
					'name':friend1,
					'email':friend1email,
					'fromemail':fromemail,
					'fromname':fromname,
					'body':message,				
					'title':'sparkol has been recommended to you by '+fromname
					}, 
					function(data){
						if (!data){
							oneWrong = true;
							alert("There was a problem sending email to "+friend1+". Please check you entered correct details.");
						} else {
							if ((!oneWrong) && (friend1email==lastemail)) {
								window.location = "friendsent.php";
							}
						}
					});
			}
		}
	} // end loop	
}