var loginWindowActive = false;
var action = new Function("void(0);");

var ALIGN_RIGHT = 1;
var ALIGN_LEFT = 2;
// the following is defined because of links displayed on multiple rows. RIGHT and LEFT do not work correctly.
var ALIGN_START = 3;

var loginWidget;

function showLoginWindow(position, align, a ){
	if (loginWindowActive) {
		hideLoginWindow();
		return;
	}
	action = a;
	loginWindowActive = true;
	var verticalPosition = findPosY(position)+position.offsetHeight-1;
	var horizontalPosition = align==ALIGN_RIGHT?'':(align==ALIGN_LEFT?findPosX(position):'');		
	
	$('#loginWindow').show();
	// this is for when we open the form after a reactivation or something else
	$('#loginAreaFields').show(); 
	if (align == ALIGN_RIGHT) {
		horizontalPosition = Number(findPosX(position)-$('#innerLoginWindow').width()+
			$(position).width()+8);
	}	
	if (align == ALIGN_START) {
		horizontalPosition = $(position).offset().left;
	}
	
	document.getElementById("innerLoginWindow").style.top=verticalPosition+'px';
	document.getElementById("innerLoginWindow").style.left=horizontalPosition+'px';
	
	$('#loginUpperArea').hide();
	$('#forgotMessage').show();
	$('#innerLoginWindow').show();
}

function showReactivationWindow(email, header) {
    //header popup
    if (header){
        $('#popupLogin form').hide();
		$('#tloginUpperArea').html(getReactivationArea(email, true));
		$('#tloginUpperArea').show();    
    }else{        
        //login window popup
		$('#loginAreaFields').hide();
		$('#loginUpperArea').html(getReactivationArea(email, false));
		$('#loginUpperArea').show();
    }   
}

function showResetPasswordWindow(header) {
    if (header){
		$('#popupLogin form').hide();
		$('#tloginUpperArea').html(getResetPasswordArea(true));
		$('#tloginUpperArea').show();
	
		$('#tloginMessage').html("");
		$('#tforgotMessage').hide();
	}else{
		$('#loginAreaFields').hide();
		$('#loginUpperArea').html(getResetPasswordArea(false));
		$('#loginUpperArea').show();
		$('#loginMessage').html("");
		$('#forgotMessage').hide();
	}	 	
}

function getRegister() {
	return '<h2>'+JSResource.login_getRegister_newUsers+'</h2>'+
	'<p><input value="'+JSResource.login_getRegister_register+'" id="submitButton" type="button" onClick="javascript:document.location.href=\''+registerURL+'\'"/></p>';
}

function getReactivationArea(email, header) {
    var newemail;
    if (header){
       	newemail = 'tnewemail';
    }else{
       	newemail = 'newemail';
    }

	return '<p><label for="' + newemail + '">'+JSResource.login_getReactivationArea_resendActivation+'</label> <input type="text" id="' + newemail + '" name="' + newemail + '" style="width: 100%" value="'+email+'"/></p>'+
	'<p><input value="'+JSResource.login_getReactivationArea_resend+'" type="button" onClick="doReactivate(true, ' + header + ')"/></p></div>';
}

function getResetPasswordArea(header) {
    var email;
    if (header){
       	email = 'temail';
    }else{
       	email = 'email';
    }
    
    return '<p><label for="' + email + '">'+JSResource.login_email+'</label> <input type="text" id="' + email + '" name="' + email + '" /></p>'+
	'<p><input value="'+JSResource.login_getResetPasswordArea_send+'" type="button" onClick="doResetPassword(' + header+ ')" style="width:218px;"/></p>'+
	'<p style="margin-top:7px;">'+JSResource.login_getResetPasswordArea_info+'</p></div>';
}


function hideLoginWindow(header) {
    if (header){              
        //restoring the default state
		if(document.getElementById("tusername")){
			document.getElementById("tusername").value="";
		}
		if(document.getElementById("tpassword")){
			document.getElementById("tpassword").value="";
		}
		$('#tloginMessage').hide();
		$('#tforgotMessage').show();
		$('#popupLogin form').show();
		$('#tloginUpperArea').html('');
		$('#tloginUpperArea').hide();	
		$('a.login').toggleClass('login-active');
		$("#popupLogin").toggle();			   	
    }else{    	
		$('#innerLoginWindow').hide();	
		$('#loginWindow').hide();
		if(document.getElementById("username")){
			document.getElementById("username").value="";
		}
		if(document.getElementById("password")){
			document.getElementById("password").value="";
		}
		$('#loginMessage').hide();
		loginWindowActive = false;
    }    
}

function doReactivate(newEmailFlag, header) {
    var lMessage;
    var newemail;
       
    if (header){
    	lMessage = $('#tloginMessage');
    	newemail = 'tnewemail';
    }else{
    	lMessage = $('#loginMessage');
    	newemail = 'newemail';
    }

	var handlerFunc = function(t) {
		var response = trim(t);
		if (response.substring(0,6)=='error:') {
			lMessage.html(response.substring(6,response.length));
		}
		else {
		 	lMessage.html(response);
		 	setTimeout('hideLoginWindow(' + header + ')',3000);		 	
		}
	}
	
	var errFunc = function(t) {
	    alert(JSResource.error);
	}
	
	lMessage.html(JSResource.login_sendingRequest);		
	lMessage.show();	
	if (newEmailFlag) {
		//FIXME adi at least awkward syntax, does it have a purpose?
		var tempValue = $((newemail)).value;
		$((newemail)).value = '';
		$((newemail)).value = tempValue;	
		//FIXME adi at least awkward syntax, does it have a purpose?
		
		$.ajax({
			url: reactivateURL,
			type: 'POST',
			data: {'newAddress':'true', 'email':$('#' + newemail).val(), 'language':loginLanguage},
			success: handlerFunc,
			error: errFunc
		});
	}
	else {	    
		$.ajax({
			url: reactivateURL,
			type: 'POST',
			data: {},
			success: handlerFunc,
			error: errFunc
		});
	}
}

function doResetPassword(header) {
    var lMessage;
    var email;
    if (header){
    	lMessage = $('#tloginMessage');
    	email = 'temail';
    }else{
    	lMessage = $('#loginMessage');
    	email = 'email';
    }

	var handlerFunc = function(t) {
		var response = trim(t);
		if (response.substring(0,6)=='error:') {
			lMessage.html(response.substring(6,response.length));
			Tracker.doTrackForgotPasswordSteps('Reset password failed');
		}
		else if (response.substring(0,2)=='ok') {
		 	lMessage.html('<p>Email '+JSResource.login_doResetPassword_sent+'</p>');
		 	Tracker.doTrackForgotPasswordSteps('Reset password sucess');
		 	setTimeout('hideLoginWindow(' + header + ')',3000);
		}
	}
	
	var errFunc = function(t) {
	    alert(JSResource.error);
	}
	
	lMessage.html(JSResource.login_sendingRequest);		
	lMessage.show();
	
	//FIXME adi at least awkward syntax, does it have a purpose?
	var tempValue = $((email)).value;
	$((email)).value = '';
	$((email)).value = tempValue;	
	//FIXME adi at least awkward syntax, does it have a purpose?
	
	$.ajax({
		url: reserpasswordURL,
		type: 'POST',
		data: {'email':$('#' + email).val(), 'language':loginLanguage},
		success: handlerFunc,
		error: errFunc
	});
}

function doLogin(loginMessageId, forgotMessageId, usernameId, passwordId, header) {
	var handlerFunc = function(t) {
		var response = trim(t);
		if (response.substring(0,6)=='error:') {
			$('#'+loginMessageId).html(response.substring(6,response.length));		
			$('#'+forgotMessageId).show();
		}
		else if (response.substring(0,2)=='ok') {
		 	$('#'+loginMessageId).html('<p>'+JSResource.login_doLogin_loginOK+'<p>');	
			loggedIn = true;
//			loginWidget = response.substring(3,response.length);
//			decoratePage();
//		 	hideLoginWindow();
			action();
			// rather refresh the page upon login as there's a login link at the bottom as well
			location.reload();
		}
	}
	
	var errFunc = function(t) {
	    alert(JSResource.error);
	}
	$('#'+forgotMessageId).hide();
	$('#'+loginMessageId).html(JSResource.login_sendingRequest);
	$('#'+loginMessageId).show();

    //FIXME adi at least awkward syntax, does it have a purpose?
	var tempValue = $((usernameId)).value;
	$((usernameId)).value = '';
	$((usernameId)).value = tempValue;
	var tempValue = $((passwordId)).value;
	$((passwordId)).value = '';
	$((passwordId)).value = tempValue;
	//FIXME adi at least awkward syntax, does it have a purpose?
	
	$.ajax({
			url: loginURL,
			type: 'POST',
			data: {'username':$('#'+usernameId).val(), 'password':$('#'+passwordId).val(), 'language':loginLanguage, 'fromHeader':header},
			success: handlerFunc,
			error: errFunc
	});
}


function decoratePage() {
	if (document.getElementById('mainLoginArea')!=null) {
		$('#mainLoginArea').html(loginWidget);
	}
	if (document.getElementById('mainCommunitiesArea')!=null) {
		$.ajax({
	        type: 'POST',
	        url: comunityWidgetUrl,
	        data: {},
	        success: updateCommunityWidget
	    });		
	}
	
}

function updateCommunityWidget(text){
	if(text != "") {
		var communityWidget = document.getElementById('communities');
		if(communityWidget){
			communityWidget.innerHTML = text;
		}
	}
	Custom.init();
}


