(function(jQuery){

    $.fn.slider = function (opt) {
		slider(this, opt);
	}; 
	
	function slider(target, opt)
	{
		opt = $.extend({
			margin: 50,
			slider_content_cnt: '.slider_content_cnt',
			slider_content: '.slider_content',
			slider_item: '.slider_item',
			
			left_btn: '.slider_arrow_left img',
			right_btn: '.slider_arrow_right img',
			
			_target: target
		}, opt);
		
		var item_margin_right_px = opt.margin;
		var item_margin_right = item_margin_right_px+"px";
		
		var slider_content_margin_left = $(opt.slider_content).css('margin-left').replace('px','')-0;
		
		$(opt.slider_content + ' ' + opt.slider_item).css('margin-right', item_margin_right);
		
		function slide_left_full()
		{
			slider_animate(-100, 2000, 'linear', false, slide_left_full);
		}
		
		var items_total_width = 0;
		$(opt.slider_item, opt._target).each(function() {items_total_width += $(this).width() + item_margin_right_px});
		
		// Pradinis judejimas i desne, jei per daug elementu (netelpa)
		if (items_total_width > $(opt._target).width())
		{
			// Patrigubinam contenta, kad iskart baigusis logotipams, jie eitu vel is pradziu
			// Vaizda nustatom ties centrine dalim (kad galetume slidint i abi puses)
			var slider_items = $(opt.slider_content + ' ' + opt.slider_item);
			
			$(opt.slider_content).append(slider_items.clone());
			$(opt.slider_content).append(slider_items.clone());
			
			slide_left_full();
			
			// Buttonu kairen desnen handleriai
			$(opt.left_btn).click(function(){
				slider_animate(300, 250, 'swing', true);
			});
			
			$(opt.right_btn).click(function(){
				slider_animate(-300, 250, 'swing', true);
			});
		}
		else
		{
			// Jei telpa elementai ,tai juos tiesiog sucentruojam
			$(opt.slider_content + ' ' + opt.slider_item + ":first").css('margin-left', (($(opt._target).width() - items_total_width) / 2) + 'px');
		}
		
		
		function slider_animate(diff, time, effect, stop, callb)
		{
			if (stop)
				$(opt.slider_content).stop();
			
			if (slider_content_margin_left + diff > 0) {
				slider_content_margin_left -= items_total_width;
				$(opt.slider_content).css('margin-left', slider_content_margin_left + 'px');
			} else
			if ($(opt._target).width() - slider_content_margin_left > items_total_width * 2) {
				slider_content_margin_left += items_total_width;
				$(opt.slider_content).css('margin-left', slider_content_margin_left + 'px');
			}
			slider_content_margin_left += diff;
			
			var px = ""+(slider_content_margin_left)+"px";
			if (callb != undefined)
				$(opt.slider_content).animate({
					marginLeft:px }, time, effect, callb);
			else
				$(opt.slider_content).animate({
					marginLeft:px }, time, effect);
		}
	}

})(jQuery);
