var QuickLook = function(options) {
	var that = this;
	this._options = options || {};
	
	this.Layer.setAjaxUrl(this._options.ajaxLayer || "ajax.quicklook.php");
	this.Layer.Dropdowns.setAjaxUrl(this._options.ajaxPrice || "ajax.quicklook_update_price.php");
	this.Layer.Submit.setAjaxUrl(this._options.ajaxCart || "ajax.quicklook_update_cart.php");
	
	this._preload();
	this._initDebugger();
	window.__debug("initialized...");
	
	$(document).ready(function() {
		that._wrap();
		that._insertButton();
		that._observe();
	});
};

QuickLook.prototype = {
	_preload: function() {
		new Image().src = this._options.buttonUrl;
	},
	_wrap: function() {
		window.__debug("wrapping...");
		
		var $wrapper = $(document.createElement("div"))
			.attr({className: "quicklook-item-container"})
			.css({
				display: "inline",
				position: "relative"
			});
		
		$("img.quicklook-item").wrap($wrapper);
	},
	_insertButton: function() {
		window.__debug("insert buttons...");
		
		var that = this;
		var $button = $(new Image())
			.attr({
				src: this._options.buttonUrl,
				className: "quicklook-item-button"
			})
			.css({
				display: "none",
				position: "absolute",
				bottom: "10px"
			})
			.click(function(event) {
				var img = $(this).prev("img.quicklook-item");
				var path = img.attr("src");
				var productId = parseInt(path.substring(path.search(/[0-9]*_[0-9]*\.jpg/g)));
				productId = !isNaN(productId) ? productId : function() {
					var parentLink = img.parents("a[href*='info=']").attr("href");
					return parentLink ? parentLink.match(/info[=|\/](.*).html/i)[1] : 0;
				}();
				that.Layer.open(
					productId, event
				);
				
				event.preventDefault();
			});
		
		this._$imgContainer = $("div.quicklook-item-container")
			.append($button);
	},
	_observe: function() {
		window.__debug("observing...");
		
		var that = this;
		this._$imgContainer.hover(
			function() { that._showButton($(this)); },
			function() { that._hideButton($(this)); }
		);
	},
	_showButton: function($container) {
		window.__debug("show button...");
		
		var $img = $container.find("img.quicklook-item-button");
		$img.css({marginLeft: "-" + ($img.width()/2) + "px", left: $container.width()/2 + "px"}).fadeIn("fast");
		$img.fadeIn("fast");
	},
	_hideButton: function($container) {
		window.__debug("hide button...");
		$container.find("img.quicklook-item-button").fadeOut("fast");
	},
	_initDebugger: function() {
		window.__debug = this._options.debug ? function(info) {
				try { console.log(info); } catch(e) {};
		} : function() {};
	}
};

QuickLook.prototype.Layer = {
	open: function(productId, event) {
		window.__debug("open layer...");
		var that = this;
		this._$layer = this._createLayer();
		this._event = event || window.event;
		if (this._opened) {
			this._hide(function() { that.open(productId, event); });
		} else {
			this._ajax(productId, function(data) {
				that._$layer.html(data);
				that._$layer
					.find("img.close-button")
					.click(function(event) { that.close(); event.preventDefault(); });
				
				that._$layer.draggable({handle: that._$layer.find("img.move-button")});
				that._show();
				that.Images.init(that._$layer);
				that.Tabs.init(that._$layer);
				that.Dropdowns.init(that._$layer, productId);
				that.Submit.init(that._$layer, productId);
			});
		}
	},
	close: function(callback) {
		window.__debug("close layer...");
		this._hide();
	},
	setAjaxUrl: function(url) {
		this._ajaxUrl = url;
	},
	_show: function(callback) {
		var that = this, callback = callback || function() {};
		this._setPosition();
		this._$layer.fadeIn("def", function() {
			that._opened = true;
			callback();
		});
	},
	_hide: function(callback) {
		var that = this, callback = callback || function() {};
		this._$layer.fadeOut("def", function() {
			that._opened = false;
			callback();
		});
	},
	_createLayer: function() {
		var $quicklookLayer = $("#quicklook-layer");
		return $quicklookLayer.length > 0 ? $quicklookLayer : function() {
			var $newQuicklookLayer = $(document.createElement("div"))
				.attr({id: "quicklook-layer"})
				.css({display: "none"});
			$("body").append($newQuicklookLayer);
			return $newQuicklookLayer;
		}();
	},
	_setPosition: function() {
		var height = this._$layer.height(),
			width = this._$layer.width(),
			mouseX = this._event.pageX || (this._event.clientX + document.body.scrollTop),
			mouseY = this._event.pageY || (this._event.clientY + document.body.scrollLeft);
		var cssLeft = mouseX - (width / 2),
			cssTop = mouseY - (height / 2);
		cssLeft = cssLeft < 20 ? 20 : cssLeft;
		cssTop = cssTop < 20 ? 20 : cssTop;
		this._$layer.css({left: cssLeft, top: cssTop});
	},
	_ajax: function(productId, callback) {
		$("body").css({cursor: "wait"});
		window.__debug("ajax request for:" + productId);
		$.get(this._ajaxUrl, {info: productId}, function(html) {
			$("body").css({cursor: "default"});
			callback(html);
		});
	}
};

QuickLook.prototype.Layer.Images = {
	init: function($layer) {
		var $image = $layer.find("div.quicklayer-img-container");
		$layer.find("div.quicklayer-thumbnails-container img").mouseover(function() {
			$image.find("a").attr("href", $(this).attr("rel"));
			$image.find("img").attr("src", $(this).attr("src"));
		});
	}
};

QuickLook.prototype.Layer.Tabs = {
	init: function($layer) {
		var $tabs = $layer.find("a.tab");
		$tabs.click(function(e) {
			e && e.preventDefault();
			$tabs.removeClass("selected");
			$(this).addClass("selected");
			$layer.find("div.tab-content").hide();
			$layer.find("#tab-" + this.rel).show();
		});
	}
};

QuickLook.prototype.Layer.Dropdowns = {
	init: function($layer, productId) {
		var that = this;
		this._productId = productId;
		this._$price = $layer.find("span.product-price");
		this._$indicator = $layer.find("span.price-indicator");
		
		this._$select = $layer.find("select");
		this._$select.change(function() { that._updatePrice(); });
	},
	setAjaxUrl: function(url) {
		this._ajaxUrl = url;
	},
	_stripPrice: function(price) {
		return price.replace(/\b[^0-9]*/, "");
	},
	_updatePrice: function() {
		var that = this;
		this._$indicator.show();
		$.get("ajax.quicklook_update_price.php", {
			info: this._productId,
			opt_ids: this._$select.map(function() {
				return $(this).attr("name").replace(/[^0-9]/g, "");
			}).get().join("|"),
			att_ids: this._$select.map(function() {
				return $(this).attr("value");
			}).get().join("|")
		}, function(response) {
			that._$indicator.hide();
			setTimeout(function() { that._$price.html(that._stripPrice(response)).effect("highlight", {}, 1000); }, 100);
		});
	}
};

QuickLook.prototype.Layer.Submit = {
	init: function($layer, productId) {
		var that = this;
		this._productId = productId;
		this._enabled = true;
		this._$layer = $layer;
		this._$form = $layer.find("form").attr("action", this._ajaxUrl.replace("[pid]", productId));
		this._$tabAttributes = this._$layer.find("#tab-attributes");
		this._$button = $layer.find("span.add-cart-button input");
		this._$form.submit(function(event) { return that._submit(event); });
	},
	setAjaxUrl: function(url) {
		this._ajaxUrl = url;
	},
	_submit: function(event) {
		var that = this;
		(event && event.preventDefault());
		
		if (!this._enabled) {
			return false;
		}
		this._enabled = false;
		
		if (this._attributesValid()) {
			new DynamicCart({
				$form: this._$form,
				callback: function() { that._enabled = true; that._$layer.find("#quicklook-checkout-link").show().effect("highlight", {}, 500); }
			});
		} else {
			this._$layer.find("a[rel='attributes']").click();
			this._enabled = true;
			setTimeout(function() { that._$invalids.parent("td").effect("highlight", {color: "#ff0000"}, 1000); }, 100);
		}
	},
	_attributesValid: function() {
		this._$invalids = this._$tabAttributes.find("select[value='-']");
		return (this._$tabAttributes.length > 0)
			? (this._$invalids.length < 1)
			: true;
	}
};