window.SessionCounter = {
		timeOut: 0,
		sessionSec: 0,
		
		init: function(timeOut){
			this.timeOut = timeOut;
			this.sessionSec = timeOut;
			this.startCounter(timeOut);
		},
		
		count: function(){
		    if(this.timeOut != 1){
		    	this.timeOut--;
		    }
		},
		restetTimer: function(){
			this.timeOut = this.sessionSec;
		},
		startCounter: function(timeOut){
			this.timeOut = timeOut;
			intInterval = window.setInterval("window.SessionCounter.showCounter()", 1000);
		},
		showCounter: function (){
			var loginLink = '<a style="font-weight:bold;" target="blank" onclick="window.SessionCounter.showLoginForm();">Zaloguj ponownie</a>';
			if(this.timeOut != 1){
				this.timeOut--;
				$("#session_counter").html(Math.floor(this.timeOut/60)+'min '+this.timeOut%60 +'s');
				
			}else{
				$("#session_counter").html(loginLink);
			}
		},
		sessionExpand: function() {
			var oSelf = this;
			$("#session_counter").html('<img src="../repository/fileicons/ajax-loader.gif" alt=""/>');
			$.post('ajax/session_expand.php', {time: 1}, function(data){
				if (data == 'true') {
					oSelf.restetTimer();
				} 
			});
		},
		showLoginForm: function(){
			$("#dialogLogin").dialog('open');
		},
		login: function(password){
			var oSelf = this;
			$.post('/getContent.php?'+ajaxIeFix(), {
				plugin: 'PrbPanelBiblioteki',
				content: 'loginForm',
				action: 'loginSessionCounter',
				lib_password: password
			},
			function(data){
				if (data == 'true'){
					oSelf.restetTimer();
				}
				PrbMessages.getMessages();
			}
			)
		}
	}



$(function() {
	var 
		password = $("#lib_password"),
		allFields = $([]).add(password),
		tips = $("#validateTips")
		;

	function updateTips(t) {
		tips.text(t);
	}

	function checkLength(o,n,min,max) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Nazwa pliku musi mieć długość od "+min+" do "+max+" znaków.");
			return false;
		} else {
			return true;
		}
	}
	
	$("#dialogLogin").dialog({
		autoOpen: false,
		height: 150,
		dialogClass: 'renameFile',
		buttons: {
			'Zaloguj': function() {
				var bValid = true;
				allFields.removeClass('ui-state-error');
				bValid = bValid && checkLength(password,"Hasło",3,16);
				if (bValid) {
					window.SessionCounter.login(password.val());
					$(this).dialog('close');
				}				
			},
			'Anuluj': function() {
				$(this).dialog('close');
			}
		}
	});
});
