// *********************
//  LOGIN FUNCTIONS
// *********************
(function() { 
	document.observe("dom:loaded", function (){
		debug('DOM Loaded: base_login');
		var err = grabQueryValue('err');
		if (err != false){
			displayErr(unescape(err));	
		}
		
		if (!checkLogin()){
			for (n=0; n < arrayProtectedPages.length; n++){
				if (location.pathname.indexOf(arrayProtectedPages[n]) != -1){		
					topWin.location.href = 'login_force.php?destination=' + escape(location.pathname);
				}
			}
		}
	})	
})();


//checks if the user is logged in or not
function checkLogin(){
	var cookie 	= readCookie('vdata' + vokiEnv);
	//no cookie set not logged in
	if (!cookie){
		return false;
	}

	//read Chip
	var	accChip	= parseInt(readChip(cookie, 'acc'));

	//chip is not in the cookie not logged in
	if (isNaN(accChip)){
		return false;
	}

	//read the env chip to make sure that both match up
	var envChk 	= readChip(cookie, 'env');
	envChk 		= envChk.toString();

	if (envChk != vokiEnv){
		return false;
	}

	return true;
}

function logoutUser(){
	location = dynamicDomain + 'login_status.php?logout=1';
	return true;
}

function submitLoginForm(){	
	dest			= grabQueryValue('destination');
	
	if (dest.toString() == 'false')
		 dest	= 'mywebsite.php';
   
	var display  = grabQueryValue('useLong');
	display    	= parseInt(display);
   
	
	email		= $('email').value;
	pass		= $('password').value;
	remember	= $('rememberMe').value;


	err			= $('loginError');

	errorStr	= '';

	//check the fields to avoid submitting to the page all the time
	formOk	= true;
	if (!emailPat.test(email)) {
		errorStr = "You did not enter a valid email address.\n";
		formOk = false;
	}else if (pass == "") {
		errorStr = "You did not enter your password.\n";
		formOk = false;
	}

	if (!formOk){
		if (err){
			displayErr(errorStr);
		}else{			
			topWin.openLogin(dest, errorStr);			
		}
		return false;
	}
	
	var url = 'login_action.php';
	debug(url);
	var	pars = '?email=' + escape(email) + '&password=' + escape(pass) + '&rememberMe=' + escape(remember);
	pars 	+='&rand=' + Math.floor(Math.random() * 1000000000);	
	
	new Ajax.Request(url, {
		parameters:   	pars,
		asynchronous: 	true,
		onSuccess:		processLoginResponse,
		onFailure:		processLoginFail,
		onCreate:		function () {$('Processing').show(); debug('processing PROCESSING!!');}
	});

	return false;
}

function displayErr(msg){
	$('Processing').hide();
	$('loginDiv').hide();
	$('loginError').show();	
	$('errMsg').innerHTML	= unescape(msg);	
}

function hideErr(){
	$('loginError').hide();
	$('loginDiv').style.display ='block';	
	$('errMsg').innerHTML	= '';	
}

function processLoginResponse(aResp){
	debug('processLoginResponse');
	dest		= grabQueryValue('destination');
	
	if (dest.toString() == 'false')
		 dest	= 'mywebsite.php';
	
	
	response	= aResp.responseText.split("||");
	code		= parseInt(response[0]);
	action		= response[1];
	
	var errMsg		= '';	
	var resOk		= true;
	
	
	if (isNaN(code)){
		errorStr 	= 'We Apologize, But there was an internal Error. Please Try again later.';
		resOk	= false;
	}else{
		switch (code){
			//params where not submitted properly
			case 7:
				errorStr 		= 'Please check your login information and try again.';
				resOk			= false;
				break;
			//login succeeds but more steps are required (DEPECRATING)
			case 6:
				top.openModalIframe(action, 350, 400);
				return false;
				break;
			//"error" with logging in from the php script
			case 5:
				topWin.resetPass(response[2],response[1], dest);
				return false;
				break;
			case 4:
				errorStr		= response[1];
				resOk			= false;
				break;
			//no problems
			case 0:
				
				if (top.location.pathname == '/vokiCommentEditor.php'){
					top.location.reload();
				}else{
					top.location	=  cachedDomain + dest;
				}
				return false;
				break;
			//we should never get a default.  There might be something wrong
			default:
				errorStr 	= 'We Apologize, But there was an internal Error. Please Try again later.';
				resOk		= false;
		}
	}
	
	//properly display the error message if applies
	if (!resOk){
		if (err){
			displayErr(errorStr);
		}else{
			$('Processing').hide();
			topWin.openLogin(dest, errorStr);				
		}
		return false;
	}
}

//if the ajax call fails, display an error
function processLoginFail(aResp){
	debug('processLoginFail');
	$('Processing').hide();
	displayErr('We Apologize, But there was an internal Error. Please Try again later.');
}

function accessMyVoki(url){
	if (readChip(readCookie('vdata' + vokiEnv), 'acc'))
		location.href = url;
	else
		Login(url);
}

function checkResetForm(){
	uPswd 			= $("new_password");
	uPswdConfirm 	= $("new_password");
	if ($("old_password")){
		uOldPass		= $("old_password");
	}
	
	
	formOk			= true;	
	if (uPswd.value.length < 6) {
		errorStr 	= "Your New password must be at least 6 characters.<br />";
		formOk		= false;
	} else {
		if (uPswdConfirm.value != uPswd.value) {
			errorStr 	= "Your New passwords did not match.<br />";
			formOk		= false;
		} 
	}
	if (!formOk){
		$('loginError').innerHTML = errorStr;
		$('loginError').style.display='block';
		return false;
	}
	return true;
}