/**
 * @author tehek
 */

$WRONG_LOGIN = false;			// hide 

/**
 * The magic trick function to load ajaxy comments
 */
function bindPaginators() {
	hidePreloader();
	
	// and rebind buttons :)
	$('.paginator a').click(function (f){
		f.preventDefault();
		// perform ajax trick:
		showPreloader();
		$('#comments').load(f.target.href + " #comments", {}, function () {
			bindPaginators()
		});
	});		
		
	if ($WRONG_LOGIN) {
		$('.leave_comment .login_error').show();
		$('.leave_comment').show();
	}	
}

/**
 * Preloader utilities
 */
function showPreloader () {
	$('#spinner').show();
}

function hidePreloader () {
	$('#spinner').hide();
}	

/**
 * submits comment form
 */
function submitComment (form) {
	showPreloader();
	$WRONG_LOGIN = false;
	$(form).ajaxSubmit({
		//iframe: true,
	    beforeSend: function(xhrObj){
            //xhrObj.setRequestHeader("Aber", "cadaber");
			//console.debug(arguments);
			return xhrObj;
        },
		success: function () {
			hidePreloader();
			// yay! another cheat to get current ajax-page
			var first_page_ajax_url = $('.first_page_ajax_url')[0].href;
			
			// refresh page on success
			$('#comments').load(first_page_ajax_url + " #comments", {}, function () {
				bindPaginators()
			});
		}
	});
	
	return false;
}

function submitLogin (form) {
	showPreloader();
	$.ajaxSetup({
		scriptCharset: 'utf-8'
	});
	$(form).ajaxSubmit({
		iframe: true,
	    success: function () {
			hidePreloader();
			// yay! another cheat to get current ajax-page
			var current_ajax_url = $('.current_ajax_url')[0].href;
			
			// refresh page on success
			$('#comments').load(current_ajax_url + " #comments", {}, function () {
				bindPaginators();
			});
			
			// show wrong login message (the form hides otherwise anyway)
			$WRONG_LOGIN = true;
		}
	});
}	

/**
 * Loads comments from url
 * @param {Object} url
 */
function loadComments(url) {
	$('#comments').load(url + ' #comments', null, bindPaginators); 
	showPreloader(); 	
}

//Bind it
jQuery(function () {
	bindPaginators();
});

