/*
example: $('#ajaxInputSearch').ajaxInputSearch({'selectName' : 'client_id'});
*/


var to_ajax_search_elem, to_ajax_search_timeout, to_ajax_search_name;
var ajax_data_added = {};
var on_complete = {};

(function($){

	$.fn.extend({

		ajaxInputSearch: function(obj, ready){

			var html = '<img alt="ajax loader" style="float:left;margin-right:5px;display:none;" class="loader_to_ajax_search_'+obj.selectName+'" src="/templates/project/images/admin/ajax-loader.gif">'+
			'<input type="text" style="float:left;" class="input_to_ajax_search input_to_ajax_search_'+obj.selectName+'" value="" name="ajax_search">'+
			'<select class="to_ajax_search" rel="?model=cashier&page=cash_register" name="'+obj.selectName+'" style="float: left; display: none;"></select>'+
			'<img alt="close" style="float:left;margin-left:5px;cursor: pointer;display:none;" class="close_to_ajax_search" src="/templates/project/images/admin/close_enabled.png">';
			$(this.selector).html(html);
			on_complete = ready;
		}
	});

	$.extend({

		ajaxSearch: function(thisE){

			var elem = $(thisE).parents('td').find('.to_ajax_search');

			to_ajax_search_elem = elem;
			to_ajax_search_name = $(to_ajax_search_elem).attr('name');

			if( $('.input_to_ajax_search_'+to_ajax_search_name).val().length >= 3 )
				$('.loader_to_ajax_search_'+to_ajax_search_name).show();

			if(to_ajax_search_timeout) clearTimeout(to_ajax_search_timeout);
			to_ajax_search_timeout = setTimeout(function(){

				if( $('.input_to_ajax_search_'+to_ajax_search_name).val().length >= 3 ){

					$.get( '/ajax.php'+$(to_ajax_search_elem).attr('rel')+'&ajax_search='+$('.input_to_ajax_search_'+to_ajax_search_name).val(), function(jsonData){

						var option = '';
						if(on_complete) on_complete(jsonData);
						if(jsonData != 'null'){

							$.parseJSON(jsonData).each(function(k, v){

								alert(v);
							});

							$(to_ajax_search_elem).html(option);
							$('.input_to_ajax_search_'+to_ajax_search_name).hide();
							$(to_ajax_search_elem).show();
							ajax_data_added[to_ajax_search_name] = true;
							$('.loader_to_ajax_search_'+to_ajax_search_name).hide();
							$('.close_to_ajax_search').show();
						}
						else{

							$('.loader_to_ajax_search_'+to_ajax_search_name).hide();
						}
					});
				}
			}, 1000);
		}
	});
})(jQuery);

$('.input_to_ajax_search').live('keyup', function(){

	$.ajaxSearch(this);
});

$('.close_to_ajax_search').live('click', function(){

	var elem = $(this).parents('td').find('.to_ajax_search');

	to_ajax_search_elem = elem;
	to_ajax_search_name = $(to_ajax_search_elem).attr('name');

	if( $('.input_to_ajax_search_'+to_ajax_search_name).css('display') == 'block' ){

		$('.input_to_ajax_search_'+to_ajax_search_name).hide();
		$(to_ajax_search_elem).show();
	}
	else{

		$('.input_to_ajax_search_'+to_ajax_search_name).show();
		$(to_ajax_search_elem).hide();
	}
});