(function($, undefined) {
	$.widget( "ui.quickview", {
		_init: function() {
			var that = this;
			this.element.click(function(){
				//remove existing quickviews
				$('#quickview-wrapper').remove();
				//remove existing active states
				$('.quickview-active').removeClass('quickview-active');
				that._coordinates();
				that._insert();
				return false;
			});
        },
		
		destroy: function() {
			$.Widget.prototype.destroy.call(this);
		},
	        
        _coordinates: function() {
        	//determine position of quickview
        	this.options.product = this.element.parents('.si-product');
        	this.options.position = this.options.product.position();
        	this.options.width = this.options.product.outerWidth(true);
        	this.options.parentWidth = this.options.product.parent().width();
        	this.options.remainder = this.options.parentWidth - this.options.position.left;
        	this.options.insertPoint = Math.floor(this.options.remainder/this.options.width) - 1;
        	
        },
        
        _insert: function() {
        	//check if position exists and insert quickview, or insert after clicked element
        	this.options.insertTarget = this.options.product.nextAll().eq(this.options.insertPoint -1);
        	this.options.product.addClass('quickview-active');
        	var wrapper = '<div id="quickview-wrapper" class="loading" style="display:none;"></div>';
        	var that = this;
        	
        	if (!this.options.product.is(':last-child') && this.options.insertPoint != 0) {
        		this.options.insertTarget.length > 0 ? this.options.insertTarget.after(wrapper) : this.options.product.nextAll().last().after(wrapper);
        	} else {
        		this.options.product.after(wrapper);
        	}
        	
        	$('#quickview-wrapper').slideDown(function() {
        		that._load(that.element.attr('href'));
        	});
        },
        
        _load: function(url) {
        	var that = this;
        	//load content
        	$('#quickview-wrapper').load(url, function(data) {
        		$(this).removeClass('loading').prepend('<a href="#" class="si-remove-link">close</a>').trigger('render');
        		$(this).find('.si-remove-link').click(function() {
        			that._close();
        			return false;
        		});
			});
        },
        
        _close: function() {
        	//remove existing quick-views;
        	var that = this;
    		$('#quickview-wrapper').slideUp(function() {
				$(this).remove();
				//remove active class
				$('.quickview-active').removeClass('quickview-active');
			});
        }
		
	});
})(jQuery);


