
(function ($, undefined) {

    $.widget( "rl.carousel", {
 
    // options
    options: { 
		btnPrev: null,
		btnNext: null,		
		auto: null,
		speed: 1000,
		diraction: 'ltr',
		value: 'px',
		vertical: false,
		circular: false,
		circular_start: false,
		visible: 4,
		start: 0,
		scroll: 1,
		number: 0,
		count: 0
    },
	
    // create function
    _create: function() {
    	var self = this;

		if ( !self.options.default_visible  ) {
			self.options.default_visible = self.options.visible;
			self.options.default_scroll = self.options.scroll;
		}

		if ( !self.options.vertical ) {
			self._elements();
			self._checkVisible();
			self.options.value = '%'; 
		}
		
		if ( self.options.scroll>self.options.visible ) {
			self.options.scroll = self.options.visible;
		}
		self._removeActionBlock();
		var media_query_cur = media_query;

		$(window).bind('resize', function(){
			if(media_query_cur != media_query) {
				self.destroy();
				media_query_cur = media_query;
			}
		});
    },

    _init: function () {
    	this._elements();
    	this._checkVisible();
		if ( this.options.circular ) {
			this._circular();
		}
		
		this._build();
		
		this._addNextPrevActions();

		if ( this.options.auto && this.elements.count > this.options.visible) {
			this._bindAutoScroll();
			$('#'+this.elements.id).hover(				
				function() {
					$(this).data('carousel')._stopSlide();
				}, function() {
					
					$(this).data('carousel')._bindAutoScroll();
				}				
			);			
		}
    },
	
	_elements: function () {
		var elems = this.elements = {};
		elems.curr =  0;
		elems.interval = 0;
		elems.running = false;
		elems.id = this.element.attr('id');
		elems.ul = this.element.children('ul');
		elems.li_first = elems.ul.children('li').eq(0);
		elems.items = elems.ul.children('li');
		elems.count = elems.items.size();
		
		return;
	},
	
	_build: function () {
		
		if ( this.options.vertical ) {
			this._vertical();
		}
		else {			
			this._horizontal();
		}
		
		return;
	},
	
	_horizontal: function (rebuild) {
		elems = this.elements;
		elems.animCss=this.options.diraction == 'rtl'?"margin-right":"margin-left";
		elems.sizeCss="width";
		this._checkVisible();		
		elems.ul.css('position', 'relative');
		position = 0;
		elems.li_first.css(elems.animCss, -position+this.options.value);
	},
	
	_vertical: function () {
		elems = this.elements;
		elems.animCss="top";
		elems.sizeCss="height";
		this._height();
		elems.divSize = elems.liSize * this.options.visible;
		elems.ulSize = elems.liSize+(this.options.number + elems.count) ;
		elems.items.css({height: elems.liRealSize});
		this.element.css(elems.sizeCss, elems.divSize+this.options.value);
		elems.ul.css(elems.sizeCss, elems.ulSize+elems.liSize+this.options.value).css(elems.animCss, 0);
		
		return;
	},
	
	_checkVisible: function () {
		var self = this, elems = this.elements, opts = this.options, val = '', item_class = '';
		item_class = $(elems.items[0]).attr("class").split(" ");

		if ( !opts.vertical ) {
			if ( $(this.element).closest('.side_block') ) {
				elems.liSize = 100;
				opts.visible = 1;
			}
			else {
				var bootstr = self._parseBootrstrap(item_class);
				if ( media_query == 'desktop' && large_desktop && bootstr['lg'] ) {
					val = bootstr['lg'];
				}
				else if ( media_query == 'desktop' && bootstr['md'] ) {
					val = bootstr['md'];
				}
				else if ( media_query == 'tablet' && bootstr['sm'] ) {
					val = bootstr['sm'];
				}
				else if ( media_query == 'mobile' ) {
					if ( bootstr['xs'] ) {
						val = bootstr['xs'];
					}
					else {
						val = 12
					}
				}
				elems.liSize = 100 / ( 12 / val );
				opts.visible = 100 / elems.liSize;
			}
		}
		else {
			if( opts.visible > elems.count ) {
				opts.visible = elems.count;
			}
		}
		
		if ( opts.scroll >= opts.visible )	{
			opts.scroll = opts.visible;
		}
		else
		{
			opts.scroll = opts.default_scroll;
		}
		return;
	},

	_parseBootrstrap: function(val) {
		var a = new Array(); 
		for(var i=0; i < val.length; i++) {
			col = val[i].split("-");
			if(col[0]=='col') {
				b = col[1];
				c = col[2];
				a[col[1]] = col[2];
			}
		}
		return a;
	},
		
	_removeActionBlock: function () {
		// remove action for content block
		$(this.element).closest('.content_block').find('[onClick]').removeAttr('onClick');
		// remove action for side block
		$(this.element).closest('.side_block').find('[onClick]').removeAttr('onClick');
		
		return;
	},
	
	_height: function () {
		var elems = this.elements;
		max_height = '';
		for ( var i = 0; i < this.options.count; i++ ) {
			this.elements.items.eq(i).removeAttr('style');
			if ( max_height < this.elements.items.eq(i).outerHeight(true) ) {
				max_height = this.elements.items.eq(i).outerHeight(true);
				elems.liRealSize = this.elements.items.eq(i).height();
			}
		}
		elems.liSize = max_height;
		
		return;
	},
	
	_circular: function () {
		if(this.elements.count < this.options.visible && !this.options.circular_start)  {
			return;
		}
		this.elements.ul.append(this.elements.items.slice(0, this.options.count).clone());
		this.options.circular_start = true;		
		this._elements();

		return;
	},
	
	_addNextPrevActions: function () {

		if( this.elements.count < this.options.visible )  {
			return;
		}

		if ( !this.options.btnPrev || !this.options.btnNext ) {
			return;
		}
		
		var self = this,
			elems = this.elements,
			opts = this.options;
		
		this.element.before('<div class="'+this.options.btnNext.replace(".", "")+' next" ></div><div class="'+this.options.btnPrev.replace(".", "")+' prev" ></div>');
		
		if ( $(this.element).closest('.ling_top_block').length > 0 ) {
			$(this.options.btnNext).css('right', '-20px');
			$(this.options.btnPrev).css('left', '-20px');
		}
		
		$(this.options.btnNext).bind('click', function() {
			self.next();
		});
		
		$(this.options.btnPrev).bind('click', function() {
			self.prev();
		});
		
		return;
	},
		
	next: function () {
		if ( this.options.auto ) {
			this._iterval();
		}
		return this._slide(this.elements.curr, 'next');
	},
	
	prev: function () {
		if ( this.options.auto ) {
			this._iterval();
		}
		return this._slide(this.elements.curr, 'prev');
	},
		
	_iterval: function () {
		var self = this, elems = this.elements, opts = this.options;		
		clearTimeout(this.elements.interval);
		this._bindAutoScroll();
	},
	
	_bindAutoScroll: function() {
		var self = this, elems = this.elements, opts = this.options;
		
		this.elements.interval = setTimeout(function() {
			self._slide(elems.curr, 'next');
		}, opts.auto);
		
		return;
	},
	
	_stopSlide: function() {
		var self = this, elems = this.elements;
			
		clearTimeout(this.elements.interval);
		
		return;
	},
	
	_beforeStart: function() {
		var self = this, elems = this.elements,	opts = this.options;
		
		if ( elems.count != elems.ul.children('li').size() ) {
			elems.items = elems.ul.children('li');
			elems.count = elems.items.size();
			
			if ( opts.vertical ) {
				elems.items.css({height: elems.liRealSize});
			}
			else {
				new_margin =  (elems.divSize - elems.items.width()*opts.visible) / (opts.visible-1);
				margin_left = opts.diraction == 'rtl' ? new_margin : 0;
				margin_right = opts.diraction != 'rtl' ? new_margin : 0;
			}
			
			if ( this.options.diraction == 'rtl' ) {
				elems.items.css('float', 'right');
			}
		}
		
	return;
	},
	
	
	_afterLoadAjax: function( block_key, add_count ) {
		var self = this, elems = this.elements,	opts = this.options;
		
		if ( block_key ) {
			if ( currencyConverter.config.currency != false ) {
				currencyConverter.convertFeatured(block_key);
			}
		}
		
		if ( !opts.circular ) {
			self._checkVisible();
			if(opts.scroll > add_count) {
				new_curr = opts.scroll - add_count;
				elems.curr = elems.curr - new_curr;
			}
		}

		self._beforeStart();
		
		if ( typeof caroselCallback == 'function' ) {
		   caroselCallback();
		}
		
		self._animate();
		
	return;
	},
	
	_slide: function (to, diraction) {
		var self = this,
			elems = this.elements,
			o = this.options;
		
		if ( !elems.running ) {
			curr = diraction=='next' ? to+this.options.scroll : to-this.options.scroll;
			
			if ( o.circular ) {
				if ( curr<=0 ) {
					// If first, then goto last	
					if ( to==0 ) {
						if ((o.diraction=='ltr' && diraction=='prev' && rlCarousel[elems.id] > 0 )|| (o.diraction=='rtl' && diraction=='prev' && rlCarousel[elems.id] > 0)) {
							return;
						}
						else {
							if ( o.vertical ) {
								elems.ul.css(elems.animCss, -((elems.count-o.count)*elems.liSize)+this.options.value);
							}
							else {
								elems.li_first.css(elems.animCss, -((elems.count-o.count)*elems.liSize)+this.options.value);
							}
							// If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements.
							curr = elems.count-o.count-o.scroll;
						}
					}
					else if ( curr<0 ) {
						curr = 0;
					}
					
				} 
				else if ( curr>=elems.count-o.count ) {
					if ( to==elems.count-o.visible ) {
						// If last, then goto first
						if ( o.vertical ) {
							elems.ul.css(elems.animCss, -(o.count-o.visible)*elems.liSize+this.options.value);
						}
						else {
							elems.li_first.css(elems.animCss, -(o.count-o.visible)*elems.liSize + this.options.value );
						}
						// If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements.
						curr = o.count-o.visible+o.scroll;
					}
					else if ( curr+o.visible > elems.count ) {
						curr =(elems.count-o.visible);
					}
				} 
			} 
			else {   
				// If non-circular and to points to first or last, we just return.
				if ( curr<0 ) {
					curr = 0;
				}
				else if(curr>elems.count-o.visible && rlCarousel[elems.id] == 0) {
					curr = elems.count-o.visible;
				}
				else {
					curr = curr;
				}
				
			}
			elems.curr = curr;
			
			if ( rlCarousel[elems.id] > 0 ) {
				if ( o.circular ) {
					carent_id = elems.count-o.count-1;
				}
				else {
					// carent_id = diraction == 'next' ? elems.count-1 : o.count-1;
					carent_id = elems.count-1;
				}
				
				elems.running = true;
				xajax_loadListings( carent_id, o.scroll, o.options, rlCarousel[elems.id], o.priceTag );
			}
			else {
				elems.running = true;
				self._animate();
			}
		}		
	},
	
	_animate: function(){
		var self = this, elems = this.elements, o = this.options;
		var first_el = elems.ul.children().eq(0);
		if ( this.options.vertical ) {
			elems.ul.animate({ top: -(elems.curr*elems.liSize) }, o.speed, o.easing,
				function() {
					elems.running = false;
				}
			);
		}
		else {
			if ( elems.animCss == "right" ) {
				elems.li_first.animate({'margin-right': -(elems.curr*elems.liSize) + this.options.value} , o.speed, o.easing,
					function() {
						elems.running = false;
					}
				);
			}
			else {
				elems.li_first.animate({'margin-left': -(elems.curr*elems.liSize) + this.options.value}, o.speed, o.easing,
					function() {
						elems.running = false;
					}
				);
			}
		}
	},

	destroy: function () {
		var self = this, elems = this.elements, o = this.options;
		this._stopSlide();
		if ( this.options.btnPrev || this.options.btnNext ) {
			$(this.options.btnPrev).remove().unbind( "click" ).remove();
			$(this.options.btnNext).remove().unbind( "click" );
		}

		if (!this.options.vertical) {
			if(o.circular_start) {
				var fake_el = elems.count - o.count;
				
				o.count = fake_el;
				for ( var i = fake_el; i < elems.count; i++ ) {
					$(this.elements.items.eq(i)).remove();
				}
				o.circular_start = false;

			}
			elems.li_first.attr('style', ''); 
		}

		elems.curr = 0;
		this._init();
	}

});

})(jQuery);