/**
 * 
 * inAjax
 * 
 * @version 05.02.2010
 * 
 * @author Janno Stern (www.janno.ee)
 * @author Innovatiivsed Lahendused OÜ (www.innovatiivne.ee)
 * 
**/

$.fn.inAjax = function(object)
{
	var timeout = false;

	//set window-message and create the window
	object.message = (object.message) ? object.message : 'Lehe laadimine...';
	if(jQuery('#inAjax-window').length == 0) jQuery('body').append('<div id="inAjax-window" style="display: none;">'+object.message+'</div>');

	return this.each(function(){
		object.object = this;

		//unbind previous live events
		jQuery.fn.inAjax.unbind(object);

		//autosave form, when input changed
		if(object.autosave)
		{
			if(typeof(object.autosave) != 'number') object.autosave = 1500;

			$(':input', object.object).live('keyup', function(e){
				if(timeout) clearTimeout(timeout);
				timeout = setTimeout(function(){jQuery.fn.inAjax.post(object)}, object.autosave);
			});
		}

		//submit on enter
		if(object.enter)
		{
			$(':input', object.object).live('keyup', function(e){
				if($(this).attr('tagName') && $(this).attr('tagName').toLowerCase() != 'textarea' && e.keyCode == 13) jQuery.fn.inAjax.post(object);
				return false;
			});		
		}

		//submit on change/click
		if($(object.click).attr('tagName') && $(object.click).attr('type') && ($(object.click).attr('tagName').toLowerCase() == 'select' || $(object.click).attr('type').toLowerCase() == 'radio' || $(object.click).attr('type').toLowerCase() == 'checkbox'))
		{
			$(object.click).live('change', function(){
				jQuery.fn.inAjax.post(object);
				return false;
			});
		}
		else
		{
			$(object.click).live('click', function(){
				jQuery.fn.inAjax.post(object);
				return false;
			});
		}
	});
}


$.fn.inAjax.post = function(object)
{
	var data = new Array();
	$(':input', object.object).each(function(){data[$(this).attr('name')] = $(this).val();});

	try
	{
		validation = object.validate(data);
		if(!validation) return false;
		if(typeof(validation) == 'object') object.params = validation;
	}
	catch(e){}

	if(object.click && $(object.click).attr('id').length > 0) form = $(object.click).attr('id')+'=1&'+jQuery.fn.inAjax.serialize(object.object);
	else form = jQuery.fn.inAjax.serialize(object.object)

	if(object.params) form += '&'+jQuery.param(object.params);

	jQuery('#inAjax-window').show();
	jQuery.post(object.url, form, function(data){jQuery('#inAjax-window').hide(); try{object.callback(data);}catch(e){}});
}


$.fn.inAjax.serialize = function(object)
{
	return jQuery.param($(':input', object).serializeArray());
}


$.fn.inAjax.unbind = function(object)
{
	jQuery(object.click).die('click');
	jQuery(object.click).die('change');
//	jQuery(':input', object.object).die('keyup');
}

