
/* CORE */
/**
 * Submit'ina forma, ir jeigu buvo klaidu - jas parodo, jei ne - redirektina. Daugiausiai naudojama backende.
 */ 

function setAjaxSubmit(selector) {
	
	$(document).ready(function() { 
		if (typeof(tinyMCE)=='object') {
			$(selector).bind('form-pre-serialize', function(e) {
			    tinyMCE.triggerSave();
			});		
		}
		var options = { 
			beforeSubmit : function() {
				height = $(selector).innerHeight();
				width = $(selector).innerWidth();
				$(selector).prepend('<div style="width:'+width+'px; height:'+height+'px;" class="ajax_overlay">&nbsp;<\/div>');
			},
			success: function(responseText, statusText) {
				$(selector+' .ajax_overlay').remove();
				if (responseText) {
				 	$('.field_error_message').remove();
					$(selector+' .error').removeClass('error');
					var errors = eval('('+responseText+')');
				 	for (i in errors) {
				 		el = $(selector+' [name='+i+']');
				 		el.addClass('error');
				 		el.after('<span class="field_error_message">'+errors[i].message+'<\/span>');
				 	}
				 	$(selector+' .error:first').focus();
			 	} else {
			 		document.location = $(selector+' input[name=return_url]').val();
			 	}
			}, 
			url: '?ajax_submit'  // override for form's 'action' attribute 
		}; 
		// bind form using 'ajaxForm' 
		$(selector).ajaxForm(options);
	}); 
}

/**
 * Submit'ina forma, ir atvaizduoja rezultata (template'a).
 */
 
function submitAndReplace(form_selector, area_selector, template) {
	var options = {
		beforeSubmit : function() {
			height = $(area_selector).innerHeight();
			width = $(area_selector).innerWidth();
			$(area_selector).prepend('<div style="width:'+width+'px; height:'+height+'px;" class="ajax_overlay">&nbsp;<\/div>');
		},
		success : function(responseText){
			$(area_selector).empty().before(responseText).remove();
			// $(area_selector).html(responseText);
		},
		url : '?display='+template
	};
	$(form_selector).ajaxForm(options);
}

function ajaxLinks(link_selector, area_selector, template) {
	$(function(){
		$(link_selector).click(function(){
			url = this.href;
			url += url.match('/?/') ? '&' : '?';
			url += 'display='+template;
			$.ajax({
				beforeSend : function() {
					height = $(area_selector).innerHeight();
					width = $(area_selector).innerWidth();
					$(area_selector).prepend('<div style="width:'+width+'px; height:'+height+'px;" class="ajax_overlay">&nbsp;<\/div>');
				},
				url: url,
				success: function(html){
					$(area_selector).empty().before(html).remove();
				}
			});
			return false;
		});
	});	
}
