var loginUrl = rewriteBase + "/ajax/login/";
var isUser = false;
var lastLink = null;

$(document).ready(function(){
	setTimeout('afterReady()', 200);
});

function afterReady() {
	isUser = ($('p[@class=user]').contains('Přihlášen:').size() == 1);
	$('a[@class=print-coupon],a[@class=print-coupon-detail]').click(function() {
		onPrintCouponClick(this.href); 
		return false;
	});
}

function afterLoginLoaded() {
	$('form#modalloginForm').submit(function() {
		$('#modal #loading').show();
		$('#modal #message').empty();
		$('#modal #message').addClass('error-string');
		
		username = $('#modal_login').val();
		password = $('#modal_password').val();

		$.post(loginUrl,
			{
				action: 'login',
				email: username,
				password: password
			}, function(xml) {					
				onLoginResult(xml);
			}
		);	
		return false;
	});
}

function onPrintCouponClick(link) {

	if(isUser) {
		window.location.href = link;
	} else {
		lastLink = link;
		url = rewriteBase + '/login.html?height=220&width=250&modal=true';
		tb_show(null, url, null);
	}
}

function onModalWindowClose() {
	$("p").unbind('submit');
}

function onLoginResult(xml) {
	$('#modal #loading').hide();
	$('#modal #message').show();
	
	status = $('status', xml).text();
	if(status == 1) {
		tb_remove();
		window.location.href = lastLink;
	} else {
		$('#modal #message').text($('error', xml).text());
	}
}
