$(document).ready(function() {

	$('#modalWindow').css({'display': 'none', 'opacity': 0});

	// Set up modal
	$('#modalWindow').jqm({
        overlay: 70,
        modal: true,
        target: '#modalContent'
    });

	// Bind open to login link
	$("a.login").click(function() {
		showModal($(this).attr('href'));
		return false;
	});
	// Bind open to logout link
	$("a.logout").click(function() {
		showModal($(this).attr('href'));
		return false;
	});
	// Bind close to close button in modal
	$("a.modalClose").click(function() {
		closeModal();
		return false;
	});

});

// Open
function showModal(url) {

	$modal = $('#modalWindow');
	$modal.css({'display': 'block', 'opacity': 1});

	$modal.css({ left: Math.floor(parseInt($(window).width() / 2) - parseInt($modal.width()) / 2)});
	$modal.css({ top: Math.floor(parseInt($(window).height() / 2) - parseInt($modal.height()) / 2)});

	var $modalContent = $("iframe", $modal);

	$modalContent.html('').attr('src', url);

	//$modal.jqmShow();

	if (url == "/user/logout" || url == "/user/logout/") {
		$("#modalWindow").css({ height: '90px' });
		$("#modalContent").css({ height: '90px' });
	} else {
		$("#modalWindow").css({ height: '190px' });
		$("#modalContent").css({ height: '190px' });
	}

	$modal.css({
        opacity: 0
    }).jqmShow().animate({
        opacity: 1,
		display: 'none'
    }, 'fast');

}
// For Flash
function userLogin() {showModal('/user/login/');}
function userLogout() {showModal('/user/logout/');}


// Close
function closeModal() {
	var $modal = $('#modalWindow');
	var $modalContent = $("iframe", $modal);

	$modal.css({
        opacity: 1
    }).jqmHide().animate({
        opacity: 0
    }, 'fast');
	$modal.css({'display': 'none'});

	$modalContent.html('').attr('src', '');
}
// Close/Login
function closeAndLogin() {
	$(".loggedin").text('true');

	$('a.favetrigger').each(function() {

		var $el = $(this);
		var rel = $el.attr('rel');
		var url = "/_function/check_fave/" + rel;
		
		console.log(url);

		$.getJSON(url, function(data) {

			if (data.result == "true") {
				$el.html('Unfav! - '+ data.count);
				$el.addClass('faved');
				$el.attr('href', '/_function/save_favorite/' + rel + '/delete');
			} else if (data.result == "false") {
				$el.html('Fav! - '+ data.count);
				$el.removeClass('faved');
				$el.attr('href', '/_function/save_favorite/' + rel);
			}

		});
	});

	window.document.header.userLoginStatus(true);
	closeModal();
}

// Close/Logout
function closeAndLogout() {
	$(".loggedin").text('false');
	
	$('a.favetrigger').each(function() {$(this).removeClass('faved');});
	
	window.document.header.userLoginStatus(false);
	closeModal();
}

$(window).resize(function() {
	var $modal = $('#modalWindow');
	$modal.css({ left: Math.floor(parseInt($(window).width() / 2) - parseInt($modal.width()) / 2)});
	$modal.css({ top: Math.floor(parseInt($(window).height() / 2) - parseInt($modal.height()) / 2)});
});
