var QuickLook = {
 
	initialize : function(container) {
		this.container = container;
		this.ajaxRenderQuickLookHandler = this.ajaxRenderQuickLook.bind(QuickLook);
		this.ajaxAddToCartHandler = this.ajaxAddToCart.bind(QuickLook);

		$$('div.quicklook-link[productId]').each(
			function(e) { e.observe('click', QuickLook.showPopup.bind(QuickLook)); }
		);
	},

	showPopup : function(event) {
		this.firingElement = event.element();
		if (this.firingElement) {
			this.ajaxUrl = "/WebServices/RenderControls.aspx?control=QuickLookActions&action=Get&P=" + this.firingElement.attributes["productId"].value;
		}

		//Stop Anchor Tag from firing off HREF.
		//event.preventDefault();

		this.showLoadingContent();
		var dialog = new QLDialog.Box($("quickLook-outer-wrapper"));
		dialog.show();

		this.ajaxRenderQuickLookHandler();
	},

	ajaxRenderQuickLook : function() {
		new Ajax.Request(
			this.ajaxUrl,
			{
				evalScripts: true,
				method:'get',
				onComplete : function(transport) { 
					var result = CleanAjaxResponse(transport.responseText);
					if(transport.status == 200) {
						this.container.update(result);
						this.renderQuickLookPostProcessing(); 
					}
				}.bind(this),
				onFailure : function() { 
					this.renderAjaxFailure(); 
				}.bind(this)
			}
		);
	},
	
	renderQuickLookPostProcessing : function() {
		//Wire up behavior for changing the color (product).
		if ($$('select.color-select').length > 0) {
			$$('select.color-select').first().observe('change', QuickLook.changeProduct.bind(QuickLook)); 
		}
		this.showContent();
		this.addToRecentlyViewed();
	},
	
	renderAjaxFailure : function() {
		var markup = "<div>An Error Has Occurred.</div><div onclick=$('quickLook-outer-wrapper').hide();>Close Window</div>";
		this.container.update(markup);
		this.showContent();
	},
	
	ajaxAddToCart : function() {
		var url = '/WebServices/RenderControls.aspx?control=QuickLookActions&action=Add&p=' + this.productId + '&sku=' + this.skuVariantId;
		new Ajax.Request(
			url, 
			{
				evalScripts: true,
				method:'post',
				onComplete : function(transport) {
					var result = CleanAjaxResponse(transport.responseText);
					if(transport.status == 200) {
						this.container.update(result);
						this.hideTabs();
					} 
				}.bind(this),
				onFailure : function(transport) { 
					this.renderAjaxFailiure(); 
					this.hideTabs();
				}.bind(this)
			}
		);
	},

	addToCart : function(productId, skuVariantId) {

		//Make sure the user has selected a size/width.
		if (skuVariantId != " ") {
			this.productId = productId;
			this.skuVariantId = skuVariantId;
			this.ajaxAddToCartHandler();
			
			var ajaxButton = $$(".add-to-cart-button").first();
			ajaxButton.onclick = '';
			ajaxButton.update("Adding To Cart...");
			ajaxButton.removeClassName('add-to-cart-button').addClassName('adding-to-cart');
			
			this.hideTabs();
		} 
		else {
//			$('ql-size-width-error').show();
			QuickLook.switchToQuickLookTab();
			alert("Please select a size and width before clicking on the Add To Cart button.");
		}
	},
	
	// Function to add the product to the recently viewed product cookie.  This function will put the
	// current product at the top of the list.
	addToRecentlyViewed : function() {
		var cookies = new CookieManager();
		var productIds = cookies.getValueIgnoreCase("RecentlyViewedProductIds" );
		var currentProductId = $$('select.color-select').first().value;
		var newProductIds = "";
		
		if (productIds) {
			var productIdArray = productIds.split(',');
			productIdArray.unshift(currentProductId)
			newProductIds = productIdArray.uniq().slice(0,4).join(',');
		} else {
			newProductIds = currentProductId;
		}

		document.cookie = "RecentlyViewedProductIds=" + newProductIds + ";path=/;domain=" + document.domain;
	},

	changeProduct : function() {
		if ($$('select.color-select').length > 0) {
			this.showLoadingContent();
			this.ajaxUrl = "/WebServices/RenderControls.aspx?control=QuickLookActions&action=Get&p=" + $$('select.color-select').first().value;
			this.ajaxRenderQuickLookHandler(); 
		}
	},

	showContent : function() {
		$('ql-loading-wrapper').hide();
		$('ql-content-wrapper').show();
	},

	showLoadingContent : function() {
		$('ql-loading-wrapper').show();
		$('ql-content-wrapper').hide();
	},

	switchToQuickLookTab : function() {
		$$("#ql-tab-description div").first().removeClassName("ql-tab-description-on").addClassName("ql-tab-description-off");
		$$("#ql-tab-quicklook div").first().removeClassName("ql-tab-quicklook-off").addClassName("ql-tab-quicklook-on");
		$("ql-content-description").hide();
		$("ql-selection").show();
	},

	switchToDescriptionTab : function() {
		$$("#ql-tab-quicklook div").first().removeClassName("ql-tab-quicklook-on").addClassName("ql-tab-quicklook-off");
		$$("#ql-tab-description div").first().removeClassName("ql-tab-description-off").addClassName("ql-tab-description-on");
		$("ql-selection").hide();
		$("ql-content-description").show();
	},
	
	hideTabs : function() {
		$('ql-tab-quicklook').hide();
		$('ql-tab-description').hide();
	}
};



Position.GetWindowSize = function(w) {
        w = w ? w : window;
        var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
        var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
        return [width, height]
}

var QLDialog = {};
QLDialog.Box = Class.create();
Object.extend(QLDialog.Box.prototype, {
	initialize: function(id) {
		this.createOverlay();
		this.dialog_box = $(id);
		this.dialog_box.show = this.show.bind(this);
		this.dialog_box.hide = this.hide.bind(this);
		this.parent_element = this.dialog_box.parentNode;
		this.dialog_box.style.position = "absolute";
		this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1;
		
		//Center the dialog in the window.
		var d = Element.getDimensions(this.dialog_box);
		Position.prepare();
		var ws = Position.GetWindowSize();
		pw = ws[0];
		ph = ws[1];
		this.dialog_box.style.top = (ph/2) - (d.height/2) + Position.deltaY + "px";
		this.dialog_box.style.left = (pw/2) - (d.width/2) + Position.deltaX + "px";
	},
	createOverlay: function() {
		if($('dialog_overlay')) {
			this.overlay = $('dialog_overlay');
		} else {
			this.overlay = document.createElement('div');
			this.overlay.id = 'dialog_overlay';
			Object.extend(this.overlay.style, {
				position: 'absolute',
				top: 0,
				left: 0,
				zIndex: 9999,
				width: '100%',
				backgroundColor: '#000',
				display: 'none'
			});
			document.body.insertBefore(this.overlay, document.body.childNodes[0]);
		}
	},
	moveDialogBox: function(where) {
		Element.remove(this.dialog_box);
		if(where == 'back')
		this.dialog_box = this.parent_element.appendChild(this.dialog_box);
		else
		this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay);
	},
	show: function() {
		this.overlay.style.height = Element.getDimensions(document.body).height+'px';
		this.moveDialogBox('out');
		this.selectBoxes('hide');
		new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3});
		this.dialog_box.style.display = '';
	},
	hide: function() {
		this.selectBoxes('show');
		new Effect.Fade(this.overlay, {duration: 0.1});
		this.dialog_box.style.display = 'none';
		this.moveDialogBox('back');
		$A(this.dialog_box.getElementsByTagName('input')).each(function(e){if(e.type!='submit')e.value=''});
	},
	selectBoxes: function(what) {
		$A(document.getElementsByTagName('select')).each(function(select) {
			Element[what](select);
		});
		if(what == 'hide')
			$A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)})
	},
	winWidth: function() { 
		return document.body.offsetWidth || window.innerWidth || document.documentElement.clientWidth || 0; 
	},
	winHeight: function() { 
		return document.body.offsetHeight || window.innerHeight || document.documentElement.clientHeight || 0; 
	}
});

//JQuery code for hovering over the main image.
//jQuery(document).ready(function()
//{
//	jQuery('div.productImage a').hover(
//		function(event) {
////			event.stopPropagation();
//			jQuery(this).find('.quicklook-link').show();
//			event.returnValue = false;
//		},
//		function(event) {
//			jQuery(this).find('.quicklook-link').hide();
//			event.returnValue = false;
//		}
//	);
//});
