/**
 * Show info message
 * 
 * @param $lvl (0 - info, 1 - error)
 * 
 * @return
 */ 
 
function showInfo(msg, lvl) {
	color = (lvl == 0) ? '#cbec9b' : '#f8606b';
	el = document.getElementById("infopanel");
	$(el).css({	'background-color' : color }).html(msg).show();
	setTimeout(function() {	$(el).fadeOut('slow') }, 5000);
}

$(document).ready(function() {
	
	$.ajaxSetup({
        global: false,
        beforeSend: function () {
            ICOMMON.progressShow();
        },
        complete: function (req, status) {
            ICOMMON.progressHide();            
        },
        error: function(o,t,e) {
        	ICOMMON.wl('Error connection to server');
        }
    });

	$('#login-link').click(function() {

		params = {
			cmd : 'login',
			login : $('#login').val(),
			pass : $('#password').val()
		};

		$.post('/api', params, function(i) {
			if (i.res == 'ok') {
				location.replace('/cockpit');
			} else {
				showInfo('auth failed', 1);
                $('#forgot-pass-href').show();
			}
		}, 'json');
	});

	$('#logout-link').click(function() {
		$.post('/api', {cmd: 'logout'}, function(i) {
			if (i.res == 'ok') {
				location.replace('/');
			}
		}, 'json');
	});
			
	$('#forgot-pass-link').click(function() {
		if (!$('#login').val().length) {
			showInfo('Please, enter your e-mail in first box, and try again', 1);
			return;
		}

		params = {
			cmd : 'resetpass',
			login : $('#login').val()
		};
		$.post('/api', params, function(i) {
			if (i.res == 'ok') {
				showInfo('ok, please check you e-mail box for new password', 0);
			} else if (i.res == 'error') {
				showInfo('No account could be found for this login', 1);
			}
		}, 'json');
	});
	
	$('#language-select').change(function() {
		$.post('/api', {cmd: 'changeLang', lang: $(this).val()}, 
			function(i) {
				if (i.res == 'ok') {
					location.reload();
				} else {
					showInfo('sorry, but this language is not currently supported', 0);
				}
			}, 'json');		
	});
	
	$('#password').keypress(function(e) {
		if (e.keyCode == 13) {
			$('#login-link').click();
		}
	});
    
	$('#login').keypress(function(e) {
		if (e.keyCode == 13) {
			$('#login-link').click();
		}
	});
    
    LangSelector.load({renderTo: 'language-select'});
    $('#language-select').show();
});
