/**
 * handler, which is executed when the ajax response from "get challenge" URL
 * comes.
 * @param XMLHttpRequest xmlhttp ajax object
 * @param array f submitted form with passwords/usernames
 * @param string u url for nette action
 * @param string a action name for nette action
 */
function challenge(xmlhttp, f, u, a) {
	//ajax response OK.
	if (xmlhttp.readyState == 4) {
		if (xmlhttp.responseText.substr(0,5) != "Error") {
			oldChallenge = xmlhttp.responseText;

			f['us_secret_old'].value =
				hex_hmac_md5(hex_md5(f['us_pwd'].value),
						oldChallenge);

			//if form field with new password is presented, calc secret from this field
			//otherwise from password field
			if (f['us_pwd_new']) {
				f['us_secret_new'].value = hex_md5(hex_hmac_md5(hex_md5(f['us_pwd_new'].value),
						f['us_challenge'].value));
			} else {
				f['us_secret_new'].value = hex_md5(hex_hmac_md5(hex_md5(f['us_pwd'].value),
						f['us_challenge'].value));
			}

			//disable password fields, it prevents sending these to server
			f['us_pwd'].disabled = true;
			if (f['us_pwd_new']) f['us_pwd_new'].disabled=true;
			if (f['us_pwd_new_conf']) f['us_pwd_new_conf'].disabled=true;

			if(!u) {
				f.submit();
			} else if (typeof(u) == "function") {
				u();
			} else {
				p = "sid=" + escape(f['sid'].value) + "&"
					+ "us_name=" + escape(f['us_name'].value) + "&"
					+ "us_challenge=" + escape(f['us_challenge'].value) + "&"
					+ "us_secret_old=" + escape(f['us_secret_old'].value) + "&"
					+ "us_secret_new=" + escape(f['us_secret_new'].value) + "&"
					+ "us_login_permanently=" + (f['us_login_permanently'].checked
							? "1" : "0");
				new Nette().action(u, f, p, a);
			}

			//enable password fields
			f['us_pwd'].disabled = false;
			if (f['us_pwd_new']) f['us_pwd_new'].disabled=false;
			if (f['us_pwd_new_conf']) f['us_pwd_new_conf'].disabled=false;
		} else {
			// error getting challenge
			alert('Chyba serveru: Nepodařilo se ověřit jméno a heslo.');
			f['us_pwd'].disabled = false;
		}
	}
}

/**
 * Makes challenges for form via ajax, challenge function is used as ajax event
 * handler
 * u,n,a - params for nette action
 * @param f submitted form
 * @param u url for action
 * @param a action name
 */
function md5form(f,u,a) {
	var xmlhttp = (window.XMLHttpRequest
			? new XMLHttpRequest
			: (window.ActiveXObject
				? new ActiveXObject("Microsoft.XMLHTTP")
				: false));
	if (!xmlhttp) {
		return true;
	}
	xmlhttp.open('GET', baseUrl + 'old-challenge/?us_name='
			+ encodeURIComponent(f['us_name'].value));
	xmlhttp.onreadystatechange = function() {
		challenge(xmlhttp, f, u, a);
	};
	xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	xmlhttp.send('');
	f['us_pwd'].disabled = true;
	return false;
}

/**
 * Makes challenges for registration form, same principle as md5form
 * @param f submitted form
 */
function md5register(f) {
	f['us_secret_new'].value = hex_md5(hex_hmac_md5(hex_md5(f['us_pwd'].value), f['us_challenge'].value));
	//disable password fields, it prevents sending these to server
	f['us_pwd'].disabled = f['us_pwd2'].disabled = true;
	f.submit();
	return false;
}

/**
 * Makes challenges for change password form, same principle as md5form
 * @see md5form
 * @param f submitted form
 */
function md5PasswdChangeForm(f) {
	if (f['us_pwd'].value == "" || f['us_pwd_new'].value == ""
			|| f['us_pwd_new'].value != f['us_pwd_new_conf'].value) {
		alert("Hesla jsou prázdná nebo se neschodují");
		return false;
	}
	return md5form(f,null,null,null);
}

function md5button(f, buttonName) {
	var field = document.createElement("input");
	field.setAttribute("type", "hidden");
	field.setAttribute("name", buttonName);
	field.setAttribute("value", "1");
	f.appendChild(field);
	md5form(f);
	return false;
}

login_page_url = '/prihlasit/?simple=1';
register_page_url = '/registrace/?simple=1';

function swapForms() {
	var a = $('#login-page-form > div');
	var b = $('#login-box > div');
	if(a.length && b.length) {
		$('#login-box').empty().append(a);
		$('#login-page-form').empty().append(b);
	}
}

function switchTab(tab, callback) {
	$('#login-layer > ul > li > a').each( function(i) { $(this).removeClass("selected"); });
	var url = login_page_url
	if($('#login-tab-'+tab).length > 0) {
		$('#login-tab-'+tab)[0].className = 'selected';
		url = $('#login-tab-'+tab)[0].href;
	}
	$('#login-area').load(url, null, callback );
}

function showLoginLayer(tab, callback, params) {
	if($('#login-layer').length == 0) {
		var h = '<div id="login-layer">';
		h += '<ul>';
		h += '<li><a id="login-tab-login" href="'+login_page_url+'" title="Přihlásit">Přihlásit</a></li>';
		h += '<li><a id="login-tab-register" href="'+register_page_url+'" title="Registrovat">Registrovat</a></li>';
		h += '</ul>';
		h += '<div id="login-area"></div>';
		h += '</div>';
		$('body').append(h);
	}
	$('#login-layer').modal({
		overlay: 40,
		onShow: function() {
			switchTab(tab, function() { swapForms(); });
		},
		onClose: function (dialog) {
			swapForms();

			/* pomale animovane zavirani */
	/*
			dialog.data.fadeOut('fast', function () {
				dialog.container.slideUp('fast', function () {
					dialog.overlay.fadeOut('fast', function () {
						$.modal.close();
						dialog.container.remove();
						dialog.overlay.remove();
						if (dialog.iframe) { dialog.iframe.remove(); }
						$('#login-layer').remove();
					});
				});
			});
	*/
			/* rychle zavreni layeru */
			dialog.data.remove();
			$.modal.close();
			dialog.container.remove();
			dialog.overlay.remove();
			if (dialog.iframe) { dialog.iframe.remove(); }
			$('#login-layer').remove();
			/* konec rychle varianty zavreni layeru */

			if(callback) {
				if(params) {
					callback(params);
				} else {
					callback();
				}
			}
		}
	});
	$('#modalOverlay')[0].onclick = function () {
		swapForms();
		$.modal.close();
		$('#login-layer').remove();
	}
	$('#login-tab-login').click( function () {
			swapForms();
			switchTab('login', function() { swapForms(); });
			return false;
	});
	$('#login-tab-register').click( function () {
			swapForms();
			switchTab('register', null);
			return false;
	});
}

