var $search=(function($){
	var $config={
			'loading':false,
			'pagination':false
		},
		$lib={
			'ajax':function(t,p,o){
				o=$.extend(o,{});
				$.ajax({
					'url':p.url,
					'type':p.method,
					'data':p.data,
					'beforeSend':function(){
						if(o.events.beforeSend){
							o.events.beforeSend.apply(t,[o]);
						}
						if($config.loading){
							t.empty().append($config.loading);
						}
					},
					'success':function($data,$status,$jqXHR){
						t.empty().append($data);
						if(o.events.success){
							o.events.success.apply(t,[$data,o]);
						}
					}
				});
			},
			'setLoading':function(url,context){
				var img=new Image();img.src=url;
				if(!context){
					context='<div class="loading">$loading</div>';
				}
				$config.loading=context.replace('$loading',$('<div/>').append(img).html());
			}
		},
		$events={
			'beforeSend':false,
			'complete':false,
			'dataFilter':false,
			'error':false,
			'jsonpCallbackString':false,
			'success':false,
			'xhr':false
		};

	$.fn.search=function($selector,$options){
		var $this=this,
			$target=$($selector),
			$options=$.extend(true,{
			'each':false,
			'events':$.extend({},$events),
			'forms':false,
			'loading':false
		}, $options);

		if($options.each){
			this.each($options.each);
		}

		if($options.forms){
			$.each($options.forms,function(i,v){
				$('form[name=form:'+v+'] *[name='+v+']').live('change',function(){
					$this.find('*[name='+v+']').val($(this).val()).end().submit();
				});
			});
		}

		if($config.pagination){
			$config.pagination.live('click',function(){
				var obj=$(this);
				$lib.ajax($target,{
					'url':obj.attr('href'),
					'method':'get'
				},{
					'events':$.extend({},$events),
					'loading':$config.loading?$config.loading:false
				});
				return false;
			});
		}

		this.submit(function(){
			var $form=$(this);
			$lib.ajax($target,{
				'url':$form.attr('action'),
				'method':$form.attr('method'),
				'data':$form.serialize()
			},$options);
			return false;
		});
		return this;
	};

	return {
		'setLoading':$lib.setLoading,
		'setPagination':function(s){
			$config.pagination=$(s);
		},
		'setAdditionalLinks':function(t,s,up){
			$config.additional=true;t=$(t);
			$(s).live('click',function(){
				var obj=$(this);
				$lib.ajax($(t),{
					'url':(up?up:'')+obj.attr('href'),
					'method':'get'
				},{
					'events':$.extend({},$events),
					'loading':$config.loading?$config.loading:false
				});
				return false;
			});
		}
	};

})(jQuery);

