
//Signup form javascript

signup_ajax_time = new Array();
signup_ajax_pars = new Array();
signup_ajax_callback = new Array();
signup_ajax_timeouts = new Array();
urlUname = new Array();

//Uses ajax to check if the value of the id of inputID is available 
function checkURL(inputID) {
	
	//Get the value of the inputID field
	var URLInput = YAHOO.util.Dom.get(inputID);
	//Get the value of the SUdomains field
	var Domain = YAHOO.util.Dom.get('SUdomains').value;
	
	if(URLInput.value.match(/[^A-Za-z0-9-]+/g)){
		URLInput.value = URLInput.value.replace(/[^A-Za-z0-9-]+/g, '');
	}
	
	if(URLInput.value.match(/[A-Z]+/g)){
		URLInput.value = URLInput.value.toLowerCase();
	}
	
	//Edit the div specified in the 2nd argument to say the value in the first argument
	updateStatus(URLInput.value+'.'+Domain, 'signupYourURL', 'DisplayURL');
	
	//Check length of the input
	if (URLInput.value.length < 3) {
		updateStatus(subDomLenErr, 'signupURLAvailability', 'NotAvailable');
		return;
	}
	
	//Make sure no characters that would affect the get variables are present.
	if (URLInput.value.match(/(#|&|\?|=)/)) {
		updateStatus(subDomValErr+' '+URLInput.value, 'signupURLAvailability', 'NotAvailable');
		return;
	}
	
	updateStatus(checkAvailMsg, 'signupURLAvailability', 'Processing');
	
	var url = 'ajax/signup_service.one';
	var method = 'method=subdomaincheck';
	var args = 'domain='+URLInput.value+'.'+Domain;
	var pars = method + '&' + args + '&ms=' + new Date().getTime();;
	
	// schedule ajax request
	signupAjax('checkurl', pars);		
};

function signupAjax(method, pars, callback) {
	
	// exit if the time for this method was updated less than 1 seconds ago
	if (typeof signup_ajax_time[method] != "undefined") {
		if ((new Date().getTime() - signup_ajax_time[method]) < 800) {
			clearTimeout(signup_ajax_timeouts[method]);
		}
	}
	
	// save pars
	signup_ajax_pars[method] = pars;
	
	if (callback) {
		signup_ajax_callback[method] = callback;
	}
	
	// save current time
	signup_ajax_time[method] = new Date().getTime();
	
	// set timeout to do ajax request
	signup_ajax_timeouts[method] = setTimeout('doSignupAjax("' + method + '");', 800); };

function doSignupAjax(method) {
	// get callback fn
	if (method == 'checkurl' || method == 'checkurldir') {
		var callback_fn = 'signupURLAvailability';
	}
	else if (method == 'checkuser') {
		var callback_fn = 'signupUserAvailability';
	}
	
	// get method's pars
	var pars = signup_ajax_pars[method];
	
	YAHOO.util.Connect.asyncRequest(
		'GET',
		'ajax/signup_service.one?' + pars,
		{
			failure  : reportURLError,
			success  : (signup_ajax_callback[method]) ? signup_ajax_callback[method] : updateContainer,
			argument : (callback_fn) ? callback_fn : ''
		}
	);
};

/**
 * Updates a signup availability container with the AJAX response.
 * 
 * @param object response  the AJAX response
 */
function updateContainer(response)
{
	YAHOO.util.Dom.get(response.argument).innerHTML = response.responseText;
}

function checkURLdir(inputID) {

	//Get the value of the inputID field
	var URLInput = YAHOO.util.Dom.get(inputID);
	//Get the value of the SUdomains field
	var Domain = YAHOO.util.Dom.get('SUdomains').value;

	if (URLInput.value.match(/[^A-Za-z0-9-\._@]+/g)){
		URLInput.value = URLInput.value.replace(/[^A-Za-z0-9-\._@]+/g, '');
	}
	
	if(URLInput.value.match(/[A-Z]+/g)){
		URLInput.value = URLInput.value.toLowerCase();
	}
	
	//Edit the div specified in the 2nd argument to say the value in the first argument
	updateStatus(Domain+'/'+URLInput.value+'/', 'signupYourURL', 'DisplayURL');
	
	if (URLInput.value.length < 3) {
		updateStatus(subDirLenErr, 'signupURLAvailability', 'NotAvailable');
		return;
	}
	
	if (URLInput.value.match(/(#|&|\?|=)/)) {
		updateStatus(subDirValErr+' '+URLInput.value, 'signupURLAvailability', 'NotAvailable');
		return;
	}
	
	updateStatus(checkAvailMsg, 'signupURLAvailability', 'Processing');
	
	var url = 'ajax/signup_service.one';
	var method = 'method=subdircheck';
	var args = 'domain='+Domain+'&'+'subdir='+URLInput.value;
	var pars = method + '&' + args + '&ms=' + new Date().getTime();;
	
	// schedule ajax request
	signupAjax('checkurldir', pars);	
};

function reportURLError(request) {
	updateStatus(checkAvailFail, 'signupURLAvailability', 'NotAvailable'); };

function checkUser(inputID) {

	//Get the value of the inputID field
	var UserInput = YAHOO.util.Dom.get(inputID);

	if (UserInput.value.match(/[^A-Za-z0-9-\._@\+]+/g)){
		UserInput.value = UserInput.value.replace(/[^A-Za-z0-9-\._@\+]+/g, '');
	}
	
	if (UserInput.value.length < 3) {
		updateStatus(userNameLenErr, 'signupUserAvailability', 'NotAvailable');
		return;
	}
	
	if (UserInput.value.match(/(#|&|\?|=)/)) {
		updateStatus(userNameValErr+' '+UserInput.value, 'signupUserAvailability', 'NotAvailable');
		return;
	}
	
	//Edit the div specified in the 2nd argument to say the value in the first argument
	updateStatus(checkAvailMsg, 'signupUserAvailability', 'Processing');
	
	var url = 'ajax/signup_service.one';
	var method = 'method=usercheck';
	var args = 'username='+encodeURIComponent(UserInput.value);
	var pars = method + '&' + args + '&ms=' + new Date().getTime();
	
	// schedule ajax request
	signupAjax('checkuser', pars);
};

var checkUrlUname = function(inputID, dir) {
	
	//Get the value of the inputID field
	var UserInput = YAHOO.util.Dom.get(inputID);
	
	if (UserInput.value.match(/[^A-Za-z0-9-\._@\+]+/g)){
		UserInput.value = UserInput.value.replace(/[^A-Za-z0-9-\._@\+]+/g, '');
	}
	
	if (UserInput.value.length < 3) {
		updateStatus(userNameLenErr, 'signupUserAvailability', 'NotAvailable');
		return;
	}
	
	if (UserInput.value.match(/(#|&|\?|=)/)) {
		updateStatus(userNameValErr+' '+UserInput.value, 'signupUserAvailability', 'NotAvailable');
		return;
	}
	
	//Edit the div specified in the 2nd argument to say the value in the first argument
	updateStatus(checkAvailMsg, 'signupUserAvailability', 'Processing');
	
	var url = 'ajax/signup_service.one';
	var method = 'method=usercheck';
	var args = 'username='+encodeURIComponent(UserInput.value);
	var pars = method + '&' + args + '&ms=' + new Date().getTime();
	
	urlUname = [inputID, dir];
	
	// schedule ajax request
	signupAjax('checkUrlUname', pars, checkUrlUnameTwo);
	
};

var checkUrlUnameTwo = function(o) {
	
	if (typeof o != 'undefined') {
		if (typeof o.responseText != "undefined") {
			if (o.responseText.match('NotAvailable')) {
				YAHOO.util.Dom.get('signupUserAvailability').innerHTML = o.responseText;
				return;
			}
		}
	}
	
	updateStatus(checkAvailMsg, 'signupUserAvailability', 'Processing');
	
	var inputID = urlUname[0];
	
	//Get the value of the inputID field
	var UserInput = YAHOO.util.Dom.get(inputID);
	
	var lowerURL = UserInput.value.toLowerCase();
	
	//Get the value of the SUdomains field
	var Domain = YAHOO.util.Dom.get('SUdomains').value;
	
	var url = 'ajax/signup_service.one';
	
	if (urlUname[1]) {
		var method = 'method=subdircheck';
		var args = 'domain='+Domain+'&'+'subdir='+lowerURL;
		var pars = method + '&' + args + '&ms=' + new Date().getTime();
	}
	else {
		var method = 'method=subdomaincheck';
		var args = 'domain='+lowerURL+'.'+Domain;
		var pars = method + '&' + args + '&ms=' + new Date().getTime();
	}
	
	// schedule ajax request
	signupAjax('checkuser', pars);
	
};

function reportUserError(request) {
	updateStatus(checkAvailFail, 'signupUserAvailability', 'NotAvailable'); };

function loadNewCaptcha() {

	showChatLoading('captcha');
	
	var pars = 'printForm=1' + '&ms=' + new Date().getTime();
	
	YAHOO.util.Connect.asyncRequest(
		'GET',
		'captcha/onesite_captcha.one?' + pars,
		{
			failure  : reportCaptchaError,
			success  : updateContainer,
			argument : 'captchaFormLoadArea'
		}
	);
};

function reportCaptchaError(request) {
	
	updateStatus(imageLoadErr, 'captchaFormLoadArea', 'NotAvailable'); };

function checkPassword(inputID, matchName) {

	//Get the value of the inputID field
	var PassInput = YAHOO.util.Dom.get(inputID).value;
	var VerPassInput = YAHOO.util.Dom.get(matchName).value;
	
	var wakka_reg = new RegExp("(\<|&lt;|&#60;|%3c|\>|&gt;|&#62;|%3e)");
	
	if ( PassInput.match( wakka_reg ) ){
		updateStatus(passCharErr, 'signupPasswordCheck', 'NotAvailable');
		return;
	}
	
	if (PassInput.length < 6) {
		updateStatus(passLenErr, 'signupPasswordCheck', 'NotAvailable');
		return;
	}
	
	var numCheck = PassInput.match(/\d/);
	if (!numCheck) {
		updateStatus(passNumErr, 'signupPasswordCheck', 'NotAvailable');
		return;
	}

	if (VerPassInput != PassInput && VerPassInput != '') {
		updateStatus(passMatchErr, 'signupPasswordCheck', 'NotAvailable');
		return;
	}

	//Clear the alert so that nothing will be displayed if the input is valid.
	updateStatus(passOK, 'signupPasswordCheck', 'Available');

};

function updateStatus(StatusText, divName ,textType) {
	var errorRep = document.createElement('div');
	errorRep.className = 'signup'+textType+'Text';
	errorRep.innerHTML = StatusText;
	
	var div = YAHOO.util.Dom.get(divName);
	var child = YAHOO.util.Dom.getFirstChild(div);
	
	if (child) {
		div.removeChild(child);
	}
	
	div.appendChild(errorRep);
};

function runAjaxChecks(jmn) {
	
	//Run all the ajax checking functions to make sure everything is correct.

	//This will try running each of these funtions until one works since the page will only have a subdomain or a subdir
	Try.these(
		function() { checkURLdir("SUsubdir"); },
		function() { checkURL("SUsubdomain"); }
	);

	if (!jmn) {
		checkUser("SUusername");
		checkPassword("SUpassword", "SUverifypassword");
	}
	
	return;
};

function checkSubmit(form) {
	
	//Define variables for the div elements we need to check.
	var URLAvail = YAHOO.util.Dom.get('signupURLAvailability');
	var userAvail = YAHOO.util.Dom.get('signupUserAvailability');
	var passCheck = YAHOO.util.Dom.get('signupPasswordCheck');
	
	//Make sure all the ajax fields are not NotAvailable
	// Make sure the URL field exists before checking the value.
	if (URLAvail && typeof(URLAvail) != "undefined") {
		if (URLAvail.innerHTML.match('NotAvailable')) {
			alert(userURLErr);
			return false;
		}
	}
	if (userAvail.innerHTML.match('NotAvailable')) {
		alert(userUserErr);
		return false;
	}
	if (passCheck.innerHTML.match('NotAvailable')) {
		alert(userPassErr);
		return false;
	}
	
	//Make sure all the required fields are filled in.
	var emailEl = YAHOO.util.Dom.get('SUemail');
	
	// Make sure the email field exists before checking the value;
	if (emailEl && typeof(emailEl) != "undefined") {
		email = emailEl.value;
	}
	else {
		// Check the username field.
		emailEl = YAHOO.util.Dom.get('SUusername');
		
		if (emailEl && typeof(emailEl) != "undefined") {
			email = emailEl.value;
		}
		else {
			email = 'pass@pass.com';
		}
	}
	
	var TOS = YAHOO.util.Dom.get('SUTOS');
	var firstname = YAHOO.util.Dom.get('SUfirstname').value;
	
	if (document.getElementById('recaptcha_response_field')) {
		var captchaEnabled = true;
		var captcha = YAHOO.util.Dom.get('recaptcha_response_field').value;
	}
	else {
		var captchaEnabled = false;
		var captcha = false;
	}
	
	if(email == '') {
		alert(userEmailErr);
		return false;
	}
	emailRegExp = new RegExp("^[a-zA-Z0-9!#%`~&'=_\\|\\$\\*\\/\\?\\^\\{\\}\\-\\+][a-zA-Z0-9!#%`~&'=_\\|\\$\\*\\/\\?\\^\\{\\}\\-\\+\\.]*@[a-zA-Z0-9\\-\\.]+\\.[a-zA-Z0-9]{2,6}$");
	if (!email.match(emailRegExp)) {
		alert(userEmailValErr);
		return false;
	}
	emailRegExp2 = new RegExp("^[^@\\.]*?\\.{2,}[^@\\.]*?@.*$");
	if (email.match(emailRegExp2)) {
		alert(userEmailValErr);
		return false;
	}
	emailRegExp3 = new RegExp("^[^@]*?\\.@.*$");
	if (email.match(emailRegExp3)) {
		alert(userEmailValErr);
		return false;
	}
	if (!checkEmailDomain(email)) {
		if (typeof emailDomainWarningFunction != "undefined" && emailDomainWarningFunction != '') {
			var res = eval(emailDomainWarningFunction + "();");
			return res;
		}
		alert(userEmailValErr);
		return false;
	}
	if(TOS.checked == false) {
		alert(userTOSErr);
		return false;
	}
	if(firstname == '') {
		alert(userFNameErr);
		return false;
	}
	if (firstname.match(/.*?@.*?\..{1,6}/)) {
		alert(userFNEmailErr);
		return false;
	}
	if(captchaEnabled && captcha == '') {
		alert(userWordErr);
		return false;
	}
	
	if (typeof underageWarningFunction != "undefined" && underageWarningFunction != '') {
		var res = eval(underageWarningFunction + "();");
		return res;
	}
	
	return true;

};

function checkJmnSubmit(form) {

	//Define variables for the div elements we need to check.
	var URLAvail = YAHOO.util.Dom.get('signupURLAvailability');
	
	//Make sure all the ajax fields are not NotAvailable
	if (URLAvail.innerHTML.match('NotAvailable')) {
		alert(userURLErr);
		return false;
	}
	
	//Make sure all the required fields are filled in.
	var TOS = YAHOO.util.Dom.get('SUTOS');
	
	if (document.getElementById('recaptcha_response_field')) {
		var captchaEnabled = true;
		var captcha = YAHOO.util.Dom.get('recaptcha_response_field').value;
	}
	else {
		var captchaEnabled = false;
		var captcha = false;
	}

	if(TOS.checked == false) {
		alert(userTOSErr);
		return false;
	}
	if(captchaEnabled && captcha == '') {
		alert(userWordErr);
		return false;
	}
	
	return true;

};

/*******************************************************************************
* Displays the loading screen and image while waiting for an ajax request.
*/
function showChatLoading(parentElmId) {

var loading_image_url = '/resources/images/admin/ajax-loader1.gif';

var parentElm = document.getElementById(parentElmId);
var coordinates = getElementCoordinates(parentElm); 
  
var loadingdiv = document.createElement("div"); loadingdiv.style.background = 'white'; loadingdiv.style.filter = 'alpha(opacity=50)'; loadingdiv.style.opacity = '.8'; loadingdiv.style.width = parentElm.offsetWidth + 'px'; loadingdiv.style.height = parentElm.offsetHeight + 'px'; loadingdiv.style.position = 'absolute'; loadingdiv.style.top = coordinates.y + 'px'; loadingdiv.style.left = coordinates.x + 'px'; loadingdiv.style.verticalAlign = 'middle'; loadingdiv.style.textAlign = 'center'; loadingdiv.innerHTML = '<img src="' + loading_image_url + '" ' + 'style="position:relative; top:20px;" />'; 
  
//add to container
parentElm.appendChild(loadingdiv);
} ;
  

/*******************************************************************************
* Get the x and y coordinates of the given element.
*/
function getElementCoordinates(obj) {
var point = { x: 0, y: 0 }; 
  
while(obj) {
    point.x += obj.offsetLeft ;
    point.y += obj.offsetTop;
    obj = obj.offsetParent;
} 
  
return point;
};

/**
 * Redirects to the previous URL stored in history. 
 * If no history available, sends to network home.
 */
function cancelSignup()
{
	if (window.history.length > 1) {
		window.history.back();
	}
	else {
		window.location = window.location.protocol + '//' + window.location.hostname;
	}
}

/**
 * Checks the passed email for a valid domain defined by the network.
 * 
 * @param string email  the email address
 * @return boolean      true if email domain is valid
 */
function checkEmailDomain(email)
{
	// If no email or all domains are allowed.
	if (email == 'pass@pass.com' || !validEmailDomains.length) {
		return true;
	}
	
	var domains = validEmailDomains.split(',');
	
	var emailDomain = email.substring(email.lastIndexOf('@', email.length) + 1);
	
	// Check each domain.
	for (var i=0; i<domains.length; i++) {
		if (emailDomain == domains[i]) {
			return true;
		}
	}
	
	return false;
}