var Dom = YAHOO.util.Dom;
var Anim = YAHOO.util.Anim;
var Ev = YAHOO.util.Event;

var elOverlay = document.createElement('div');
elOverlay.id = 'loginFormOverlay';

function showTopLogin(e) {
	var documentHeight = Math.max(
		Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
		Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
		Math.max(document.body.clientHeight, document.documentElement.clientHeight)
	);
	elOverlay.style.height = documentHeight+'px';
	Dom.get('loginFormTopContainer').style.display = 'block';
	elOverlay.style.display = 'block';
	Dom.get('frmTopLogin').focus();
	if (!elOverlay.parentNode) {
		document.body.appendChild(elOverlay);
	}
	Ev.stopEvent(e);
}
function hideTopLogin() {
	Dom.get('loginFormTopContainer').style.display = 'none';
	elOverlay.style.display = 'none';
}

function sendTopLogin(){
	var sndUrl = '/_system/forms_ajax.php';
	function sndHandleFailure() {
		alert(TXT_LOGIN_FAILED_ERR);
	}
	function sndHandleSuccess(oResponse) {
		if (oResponse.responseText != '' && YAHOO.lang.JSON.isValid(oResponse.responseText)) {
			var oResult = YAHOO.lang.JSON.parse(oResponse.responseText);
			if (!oResult.status) {
				if (YAHOO.lang.isNumber(oResult.chyba)) {
					if (oResult.chyba==1) {
						alert(TXT_LOGIN_WRONG_LOGIN_DATA_ERR);
					} else {
						alert(TXT_LOGIN_FAILED_ERR);
					}
				} else {
					alert(TXT_LOGIN_FAILED_ERR);
				}
			} else {
				var jazykovaVerze = (oResult.preferovanyJazyk!='')?oResult.preferovanyJazyk:TXT_JAZYKOVA_MUTACE;
				alert(TXT_LOGIN_OK);
				hideTopLogin();
				window.location="/"+jazykovaVerze+"/";
				//window.location.reload();
			}
		} else {
			alert(TXT_LOGIN_FAILED_ERR);
		}
	}
	var sndCallback =
	{
		success: sndHandleSuccess,
		failure: sndHandleFailure,
		timeout: 10000
	};
	var sndPostData = 'form_type=loginForm&login='+encodeURIComponent(Dom.get('frmTopLogin').value)+'&password='+encodeURIComponent(Dom.get('frmTopPassword').value);
	var sndRequest = YAHOO.util.Connect.asyncRequest('POST', sndUrl, sndCallback, sndPostData);
}

function checkTopLogin(e) {
	var errSMsg ='';
	if (Dom.get('frmTopLogin').value == '') {
		errSMsg += TXT_LOGIN_VALIDATION_LOGIN_ERR+'\n';
	}
	if (Dom.get('frmTopPassword').value == '') {
		errSMsg += TXT_LOGIN_VALIDATION_PW_ERR+'\n';
	}
	if (errSMsg !='') {
		alert(errSMsg);
	} else {
		sendTopLogin();				
	}
	Ev.stopEvent(e);
}

function topLoginInit() {
	Ev.addListener(Dom.get('loginTop'),'click',showTopLogin);
	Ev.addListener(Dom.get('frmTopBtnCancel'),'click',hideTopLogin);
	Ev.addListener(Dom.get('loginFormTop'),'submit',checkTopLogin);
}

Ev.onDOMReady(topLoginInit);

