/**
* Friction TV - join.js
* 
* functions for signup page
* 
* @author 						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
*/

$(document).ready(function() 
{

	$('#signupBirthdayDay').attr('disabled', true);

	$('#signupBirthdayYear').attr('disabled', true);

	$('#signupFullName').focus();

});


/**
* @var object http
*/

var http = createRequestObject();

/**
* @var object http
*/

document.validate = false;

/**
 * Friction TV - focus.js - setFocus()
 * 
 * field to set focus of a form element (cross-browser)
 * 
 * @author						Neil Young neil@friction.tv
 * @version						0.9
 * @todo						???
 * 
 * @param string 				form
 * @param string 				field
 * @param boolean				select (Microsoft Internet Explorer only)
 * 
 */

function setFocus(form, field, select) 
{

	if (select === undefined)
	{
	
		select = false;
		
	}
	
	try 
	{
		
		var browser = navigator.appName;
		
		document.getElementById(field).focus();

		//ie6+7
		
		eval('document.' + form + '.' + field + '.focus();');
		
		if (browser == 'Microsoft Internet Explorer' && select == true)
		{
		
			eval('document.' + form + '.' + field + '.select();');
			
		}
		
	} 
	catch (ignore) {}
	
}

/**
 * Friction TV - join.js - loseFocus()
 * 
 * field to lose the focus of a form element
 * 
 * @author						Neil Young neil@friction.tv
 * @version						0.9
 * @todo						???
 * 
 * @param string 				form
 * @param string				field
 * 
 */

function loseFocus(form, field) 
{

	try 
	{
		
		document.getElementById(field).blur();
		
		//ie6+7
		
		eval('document.' + form + '.' + field + '.blur();');
		
	} 
	catch (ignore) {}

}

/**
 * Friction TV - join.js - setFieldColour()
 * 
 * sets the background color of a field
 * 
 * @author						Neil Young neil@friction.tv
 * @version						0.9
 * @todo						???
 * 
 * @param string 				form
 * @param string				field
 * @param string				colour
 * 
 */

function setFieldColour(form, field, colour) 
{

	document.getElementById(field).style.backgroundColor = colour;
	
}

/**
* Friction TV - join.js - trim(stringToTrim)
* 
* trim a string
* 
* @author Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param int stringToTrim
* 
*/

function trim(stringToTrim) 
{
	
	return stringToTrim.replace(/^\s+|\s+$/g,"");

}

/**
* Friction TV - login.js - createRequestObject
* 
* create an ajax request object
* 
* @author Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* 
*/

function createRequestObject() 
{
	
	try 
	{
		  
		if (netscape.security.PrivilegeManager.enablePrivilege) 
		{
			
			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
            netscape.security.PrivilegeManager.enablePrivilege("CapabilityPreferencesAccess ");
		  
		}
	        
	}
	catch(e)
	{
	
		
		
	}
	
	try 
	{ 
		return new XMLHttpRequest(); 
	
	} 
	catch(e)
	{
		
		//alert("There was a problem with XMLHttpRequest");
		
	}
   
	try
	{ 
		
		return new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch (e)
	{
		
		//alert("There was a problem with ActiveXObject(Msxml2.XMLHTTP)");
		
	}
   
	try 
	{ 
		
		return new ActiveXObject("Microsoft.XMLHTTP"); 
	
	} 
	catch (e) 
	{
		
		//alert("There was a problem with ActiveXObject(Microsoft.XMLHTTP)");
		
	}
   
	alert("XMLHttpRequest not supported");
   
	return null;
 
}

/**
* Friction TV - join.js - checkFullName()
* 
* trim a string
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	string				$fullName
* 
*/

function checkFullName(fullName) 
{

	fullName = trim(fullName);
	
	var names = fullName.split(" ");
	
	if (fullName == '')
	{

		var content = '<p>Please enter your full name.</p>';

		$('#fullname-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupFullName', '#FF9F9F');

		$('#signupFullName').focus();
		
		return false;
		
	}
	else if (names[1] == undefined)
	{

		var content = '<p>Please provide us with your full name.</p>';

		$('#fullname-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupFullName', '#FF9F9F');

		$('#signupFullName').focus();
		
		return false;
		
	}
	else
	{

		$('#fullname-error').removeAttr('class').html('');		

		setFieldColour('userSignup', 'signupFullName', '#B8F5B1');
		
		return true;
		
	}
	
}

/**
* Friction TV - join.js - checkUsername()
* 
* check a username entry
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	string				$username
* 
*/

function checkUsername(username) 
{

	username = trim(username);
	
	if (username == '')
	{

		var content = '<p>Please enter a username.</p>';

		$('#username-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupUsername', '#FF9F9F');

		$('#signupUsername').focus();

		return false;
		
	}
	else
	{
		
		url = 'http://' + document.location.hostname + '/ajax/?p=user-username-exists|1|' + username;
		
		http.open('POST', url, false);

		http.onreadystatechange = signupHandleResponse;

		http.send(url);

		var response = http.responseText;

		var usernameError = document.getElementById('username_error');
		
		if (response == "0") 
		{
			
			setFieldColour('userSignup', 'signupUsername', '#B8F5B1');
			
			$('#username-error').removeAttr('class').html('');

			$('#signupEmail').focus();
			
			return true;
			
		}
		else
		{

			var content = '<p>That username is already taken, please try another.</p>';

			$('#username-error').addClass('join-error').html(content)

			setFieldColour('userSignup', 'signupUsername', '#FF9F9F');

			$('#signupUsername').focus();
			
			return false;

		}

	}
	
}

/**
* Friction TV - join.js - checkEmail()
* 
* check email address
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	string				$email
* 
*/

function checkEmail(email) 
{
	
	email = trim(email);
	
	validEmailRegExp = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+$/i;
	
	if (email == '')
	{

		var content = '<p>Please enter your Email Address.</p>';

		$('#email-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupEmail', '#FF9F9F');

		$('#signupEmail').focus();

		return false;
		
	}
	else if (email.search(validEmailRegExp) == -1)
	{

		var content = '<p>Please enter a valid email address.</p>';

		$('#email-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupEmail', '#FF9F9F');

		$('#signupEmail').focus();
		
		return false;
		
	}
	else
	{
		
		url = 'http://' + document.location.hostname + '/ajax/?p=user-profile-elements-email-exists|1|' + email;

		http.open('POST', url, false);

		http.onreadystatechange = signupHandleResponse;

		http.send(url);
		
		var response = http.responseText;

		if (response == "0") 
		{
			
			$('#email-error').removeAttr('class').html('');

			setFieldColour('userSignup', 'signupEmail', '#B8F5B1');

			$('#signupPassword').focus();

			return true;

		}
		else
		{

			var content = '<p>This email address is already registered, please try another.</p>';

			$('#email-error').addClass('join-error').html(content)

			setFieldColour('userSignup', 'signupEmail', '#FF9F9F');

			$('#signupEmail').focus();
			
			return false;

		}

	}
	
}

/**
* Friction TV - join.js - checkPassword()
* 
* check the users password
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	string				$password
* 
*/

function checkPassword(password) 
{
	
	password = trim(password);
	
	validPasswordLengthRegExp = /^[a-zA-Z0-9]{8,16}?$/i;
	
	if (password == '')
	{

		var content = '<p>Please enter a password.</p>';

		$('#password-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupPassword', '#FF9F9F');

		$('#signupPassword').focus();
		
		return false;
		
	}
	else if (password.search(validPasswordLengthRegExp) == -1)
	{

		var content = '<p>Please enter a password between 8 and 16 characters.</p>';

		$('#password-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupPassword', '#FF9F9F');

		$('#signupPassword').focus();

		return false;

	}
	else
	{

		$('#password-error').removeAttr('class').html('');

		setFieldColour('userSignup', 'signupPassword', '#B8F5B1');

		$('#signupSex').focus();

		return true;

	}

}

/**
* Friction TV - join.js - checkSex()
* 
* check if a sex has been selected
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	string				$sex
* 
*/

function checkSex(sex) 
{

	if (sex == -1)
	{

		var content = '<p>Please select your sex.</p>';

		$('#sex-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupSex', '#FF9F9F');

		$('#signupSex').focus();

		return false;

	}
	else
	{

		$('#sex-error').removeAttr('class').html('');

		setFieldColour('userSignup', 'signupSex', '#B8F5B1');

		$('#signupBirthdayMonth').focus();

		return true;
		
	}
	
}


/**
* Friction TV - join.js - changeMonthDays()
* 
* trim a string
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	int					$month
* @param	int					$year 
* 
*/

function changeMonthDays(month, year) 
{
	
	var days_menu = document.getElementById('signupBirthdayDay');

	if (month == -1)
	{

		$("#signupBirthdayMonth").focus();
		
		return false;
		
	}
	else if (year == -1)
	{

		$("#signupBirthdayYear").attr("disabled", false);
		
		$("#signupBirthdayYear").focus();

	}
	else
	{

		$("#signupBirthdayDay").attr("disabled", false);
		
		$("#signupBirthdayDay").focus();
		
		url = 'http://' + document.location.hostname + '/ajax/?p=calendar-days|1|' + month + '|' + year;
				
		var dataString = $.ajax({type: "POST", url: url, async: false}).responseText;

		var data = eval(dataString);

		if (data == "0") 
		{

			populateDays(31);
				
		}
		else
		{
				
			populateDays(data);

		}
		
	}

}

/**
* Friction TV - join.js - checkBirthday()
* 
* check if a sex has been selected
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	int				$month
* @param	int				$day
* @param	int				$year
* 
*/

function checkBirthday(month, day, year)
{
	
	if (month > -1 && day > -1 && year > -1)
	{
		
		setFieldColour('userSignup', 'signupBirthdayMonth', '#B8F5B1');
		
		setFieldColour('userSignup', 'signupBirthdayDay', '#B8F5B1');
		
		setFieldColour('userSignup', 'signupBirthdayYear', '#B8F5B1');

		return true;
		
	}
	else
	{
		
		if (month == -1)
		{
			
			setFieldColour('userSignup', 'signupBirthdayMonth', '#FF9F9F');
			
		}
		else
		{
			
			setFieldColour('userSignup', 'signupBirthdayMonth', '#B8F5B1');
			
		}
		
		if (day == -1)
		{
			
			setFieldColour('userSignup', 'signupBirthdayDay', '#FF9F9F');
			
		}
		else
		{
			
			setFieldColour('userSignup', 'signupBirthdayDay', '#B8F5B1');
			
		}
		
		if (year == -1)
		{
			
			setFieldColour('userSignup', 'signupBirthdayYear', '#FF9F9F');
			
		}
		else
		{
			
			setFieldColour('userSignup', 'signupBirthdayYear', '#B8F5B1');
			
		}

		var content = '<p>Please correct the errors in your birth date.</p>';

		$('#birthday-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupSex', '#FF9F9F');
		
		return false;

	}
	
}

/**
* Friction TV - join.js - checkTerms()
* 
* check if terms box has been ticked
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param 	boolean				checked
* 
*/

function checkTerms(checked)
{
	
	if (checked)
	{
	
		return true;
		
	}
	else
	{

		var content = '<p>Please agree to our terms and conditions.</p>';

		$('#terms-error').addClass('join-error').html(content)

		setFieldColour('userSignup', 'signupTerms', '#FF9F9F');

		$('#signupTerms').focus();
			
		return false;
		
	}
	
}


/**
* Friction TV - join.js -  signupHandleResponse()
* 
* handle the signup ajax response
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* @param string					data
* 
* @return object 				http
* 
*/

function signupHandleResponse(data)
{
	
	if (http.readyState == 4)
	{ 

		var responseArray = http.responseText;

		var responseSplit = responseArray.split("||");
	
		var responseType = responseSplit[0];
		
		responseType = trim(responseType);
	
		var response = responseSplit[1];
		
		if (responseType == "get_days")   
		{

			if (response == "0") 
			{
		
				days = 31;
				
				populateDays(days);
				
			}
			else
			{

				days = response;
				
				populateDays(days);

			}

		}
		
	}
	
}

/**
* Friction TV - join.js - validateSignup()
* 
* final check before user is signed up
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
*/

function validateSignup()
{
	
	document.validate = true;
	
	var validateFullName = $('#signupFullName').val();
	
	var validateUsername = $('#signupUsername').val();
	
	var validateEmail = $('#signupEmail').val();
	
	var validatePassword = $('#signupPassword').val();
	
	var validateSex = $('#signupSex').val();
	
	var validateMonth = $('#signupBirthdayMonth').val();
	
	var validateDay = $('#signupBirthdayDay').val();

	var validateYear = $('#signupBirthdayYear').val();

	var validateTerms = $('#signupTerms').is(':checked');
	
	validateFullName = trim(validateFullName);
	
	validateUsername = trim(validateUsername);
	
	validateEmail = trim(validateEmail);
	
	validatePassword = trim(validatePassword);
	
	if (!checkFullName(validateFullName))
	{
		
		validateFullNameError = true;
		
	}
	else
	{
	
		validateFullNameError = false;
		
	}
	
	if (!checkUsername(validateUsername))
	{
		
		validateUsernameError = true;
		
	}
	else
	{
	
		validateUsernameError = false;
		
	}
	
	if (!checkEmail(validateEmail))
	{
		
		validateEmailError = true;
		
	}
	else
	{
	
		validateEmailError = false;
		
	}
	
	if (!checkPassword(validatePassword))
	{
		
		validatePasswordError = true;
		
	}
	else
	{
	
		validatePasswordError = false;
		
	}
	
	if (!checkSex(validateSex))
	{
		
		validateSexError = true;
		
	}
	else
	{
	
		validateSexError = false;
		
	}
	
	if (!checkBirthday(validateMonth, validateDay, validateYear))
	{
		
		validateBirthdayError = true;
		
	}
	else
	{
	
		validateBirthdayError = false;
		
	}
	
	if (!checkTerms(validateTerms))
	{
	
		validateTermsError = true;
		
	}
	else
	{
		
		validateTermsError = false;
		
	}
	
	document.validate = false;
	
	if (validateFullNameError == false && validateUsernameError == false && validateEmailError == false && validatePasswordError == false && validateSexError == false && validateBirthdayError == false && validateTermsError == false)
	{
		
		// further processing
		
		var validateNames = validateFullName.split(" ");
		
		firstName = validateNames[0];
		
		surname = '';
		
		for (var i = 1; i < validateNames.length; i++)
		{
			
			surname += validateNames[i] + ' ';
			
		}
		
		surname = surname.slice(0, surname.length-1);
		
		birthday = validateYear + '-' + validateMonth + '-' + validateDay;
		
		url = 'http://' + document.location.hostname + '/ajax/?p=user-add|1|' + firstName + '|' + surname + '|' + validateUsername + '|' + validateEmail + '|' + validatePassword + '|' + validateSex + '|' + birthday;
		
		http.open('POST', url, false);

		http.onreadystatechange = signupHandleResponse;

		http.send(url);
		
		var response = http.responseText;

		var signupContent = document.getElementById('signup_content');
		
		if (response == "1") 
		{

			$('#signupFullName').val('').css('background-color', '#FFF');

			$('#signupUsername').val('').css('background-color', '#FFF');

			$('#signupEmail').val('').css('background-color', '#FFF');

			$('#signupPassword').val('').css('background-color', '#FFF');

			$('#signupSex').val('').css('background-color', '#FFF');
 
			$('#signupBirthdayYear').val('').css('background-color', '#FFF');

			$('#signupBirthdayMonth').val('').css('background-color', '#FFF');

			$('#signupBirthdayDay').val('').css('background-color', '#FFF');

			$('#signupTerms').attr('checked', false);

			var content = '<p>Account created! Please follow the instructions in the confirmation email we have sent you, to activate your account.</p>';

			$('#signup-result').addClass('join-success').html(content);

		}
		else
		{

			var content = '<p>There was a problem signing you up to Friction TV.</p>';

			$('#signup-result').addClass('join-error').html(content);

		}

	}
		
}

/**
* Friction TV - join.js - populateDays()
* 
* populate days for a month
* 
* @author						Neil Young neil@friction.tv
* @version						0.9
* @todo							???
* 
* 
* @param 	int					$days
* 
*/

function populateDays(days)
{
	
	var selectedDays = document.getElementById('signupBirthdayDay').value;
	
	days_menu = document.getElementById('signupBirthdayDay');
	
	days_menu.options.length = 0
	
	var option = document.createElement('option');
	
	option.setAttribute('value', -1);
	
	option.innerHTML = 'Days:';
	
	days_menu.appendChild(option);

	for (var i = 1; i <= days; i++)
	{

		var option = document.createElement('option');
	
		option.setAttribute('value', i);
		
		if (selectedDays == i)
		{
			
			option.setAttribute('selected', 'selected');
			
		}
		
		option.innerHTML = i;
		
		days_menu.appendChild(option);
	
	}
	
}

// done