//JAVASCRIPT MODULE CORRESPONDING TO THE PHP LOGIN MODULE

var timeout=3;
var logout = null;

function renderLogoutDialog()
{
	//get the login visual content from ajax;
//	hideSelectBoxes();			
	//use ajax to load the contents of the dialog
	var pars = 'rpc=ajax_dialog_logout';
		var myAjax = new Ajax.Request(
			mod_login_datafeed, 
			{
				method:'post', 
				postBody:pars, 
				onComplete:function(transport,json)
				{
					//alert(transport.responseText);
					if (json.status=='success')
					{

						logout_render(json);
					}
				}

			});	
}



/************** NEW LOGIN ********************/
function get_login_screen()
{
	open_window('ajax_get_login_screen','','',mod_login_datafeed);
}
function ajax_logmein()
{
	core_rpc('ajax_do_login',mod_login_datafeed,'&'+Form.serialize('signupForm'));
}
/***********************************************/


function showsplashscreen()
{
	open_window2('ajax_splashscreen','','',mod_login_datafeed);
}



function logout_render(json)
{
	//debug('Logout Window Loaded',true);

	logout = Dialog.confirm
	(
		json_decode(json.dialog), 
		{	
			windowParameters: 
			{
				className:"mac_os_x",resizable: true,closable:true,title: "Logout of Reactive360.com",height:json.dialogheight,width:json.dialogwidth,
					showEffect:Element.show,hideEffect:Element.hide
			},
			okLabel: json_decode(json.okLabel), 
			cancelLabel:json_decode(json.cancelLabel),
			ok:function(win)
			{
				//perform the logout via ajax
				perform_logout();
				
			}
		}
	);
	logout.setStatusBar(json.statusBar);
}




function perform_logout()
{
	var pars = 'rpc=ajax_perform_logout';
		var myAjax = new Ajax.Request(
			mod_login_datafeed, 
			{
				method:'post', 
				postBody:pars, 
				onComplete:function(transport,json){
					if (json.status=='success')
					{
						//alert('here');
						//logout.closeInfo();
						//alert();
						if (json.execute)
						{
							eval(json_decode(json.execute));
						}
						else
						{
							window.location.href=decodeURIComponent(json.url);
						}
						

					}
					else
					{
						$(json.notifyid).update(json_decode(json.notifymsg));
						new Effect.Shake('modal_dialog'); 
					}
				}
			});	
}



function new_verify()
{
	// loads new verify image
	if(document.getElementById)
	{
		// extract image name from image source (i.e. cut off ?randomness)
		thesrc = document.getElementById("verify").src;
		thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
		// add ?(random) to prevent browser/isp caching
		document.getElementById("verify").src = thesrc+"?"+Math.round(Math.random()*100000);
	} else {
		alert("Please refresh this page");
	}
}

function signupform()
{
	//	$('thisForm').submit();
	
	var savestring = Form.serialize('signupForm');

	/*Form.getElements($('thisForm')).each(function(input) 
	{
		//alert(question.getAttribute('id'));
		saveString=saveString+'&'+question.getAttribute('id')+'=__'+encodeURIComponent($F(question.getAttribute('id')));
		Event.observe(input, 'blur', function(ev) { $V(Event.element(ev).id) });
});*/
	
	
	
	if ($F('ajax_firstName').length<2)
	{
		alert('Your first name must be over 1 character long');
	}
	else
	{
		if ($F('ajax_lastName').length<2)
		{
			alert('Your last name must be over 1 character long');
		}
		else
		{
			if (!(emailCheck($F('ajax_email'))))
			{
				//alert('Your email address must be of a valid format');
			}
			else
			{
				if (typeof($F('ajax_verify_accept'))!='undefined')
				{
					core_load_rpc('ajax_signup_user',mod_wizard_datafeed,'&'+savestring,'signupdiv',0,1);
				}
				else
					{
						alert('You must accept the Terms and Privacy Policy in order to use reactive360.com');
					}
			}
		}
	}
	return false;
}


function signupform2()
{
	//	$('thisForm').submit();
	var savestring = Form.serialize('signupForm');

	/*Form.getElements($('thisForm')).each(function(input) 
	{
		//alert(question.getAttribute('id'));
		saveString=saveString+'&'+question.getAttribute('id')+'=__'+encodeURIComponent($F(question.getAttribute('id')));
		Event.observe(input, 'blur', function(ev) { $V(Event.element(ev).id) });
});*/
	
	
	
	if ($F('ajax_firstName').length<2)
	{
		alert('Your first name must be over 1 character long');
	}
	else
	{
		if ($F('ajax_lastName').length<2)
		{
			alert('Your last name must be over 1 character long');
		}
		else
		{
			if (!(emailCheck($F('ajax_email'))))
			{
				//alert('Your email address must be of a valid format');
			}
			else
			{
				if (typeof($F('ajax_verify_accept'))!='undefined')
				{
					
					core_rpc('ajax_signup_user',mod_wizard_datafeed,'&from=ca2&'+savestring,1);
				}
				else
					{
						alert('You must accept the Terms and Privacy Policy in order to use reactive360.com');
					}
			}
		}
	}
	return false;
}


function convertaccount()
{
	var savestring = Form.serialize('signupForm');

	if ($F('ajax_firstName').length<2)
	{
		alert('Your first name must be over 1 character long');
	}
	else
	{
		if ($F('ajax_lastName').length<2)
		{
			alert('Your last name must be over 1 character long');
		}
		else
		{
			if (!(emailCheck($F('ajax_email'))))
			{
				//alert('Your email address must be of a valid format');
			}
			else
			{
					core_rpc('ajax_performconvert',mod_wizard_datafeed,'&'+savestring,0);
			}
		}
	}
	return false;
}


function isValidEmail(str) {
   return (str.indexOf(".") > 0) && (str.indexOf("@") > 0);
 
}

function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("The name in the email address doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name (text after the @) doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The address must end in a three-letter domain (e.g. .com), or two letter country. (e.g. .uk)")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a domain name (text normally after the @)"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}

