﻿function initScroll() {
	var totalItems = $('div.thumbnailHolder div.thumbnail').size();

	// reset scroll to first image
	$('div#thumbnailScroll').attr('scrollTop', 0);

	// if more than 4 images, show down arrow
	if (totalItems > 4) {
		$('.scrollDown').fadeIn();
	}
}

function up() {
	var itemSize = 132;
	var pos = $('div#thumbnailScroll').attr('scrollTop');
	$('div#thumbnailScroll').animate(
            { scrollTop: pos - itemSize },
            500,
            function() {
            	$('.scrollDown').fadeIn();
            	if (pos / itemSize == 1) {
            		$('.scrollUp').fadeOut();
            	}
            }
        );
}

function down() {
	var itemSize = 132;
	var viewableItems = 4;
	var pos = $('div#thumbnailScroll').attr('scrollTop');
	var totalItems = $('div.thumbnailHolder div.thumbnail').size();
	$('div#thumbnailScroll').animate(
            { scrollTop: pos + itemSize },
            500,
            function() {
            	$('.scrollUp').fadeIn();
            	if (pos / itemSize == totalItems - viewableItems - 1) {
            		$('.scrollDown').fadeOut();
            	}
            }
        );
}

function QuickViewManager(baseImageUrl, actionUrl) {

	this._baseImageUrl = baseImageUrl;
	this._actionUrl = actionUrl;


	this.Initialize = function() {
		var $quickViewDialog = $('<div id="quickViewDialog"></div>')
			.dialog({
					autoOpen: false,
					modal: true,
					dialogClass: 'guessDialog',
					width: 694
				});

		$("div.quickView").click(function(ev) {
			ev.preventDefault();

			$quickViewDialog.html("").addClass("ui-progress").dialog("open"); ;
			var styleId = $(this).attr("styleId");

			$.post($(this).attr("action"), { id: styleId },
				function(data) {
					$quickViewDialog.html(data.Html).removeClass("ui-progress").dialog("option", "position", 'center');
					var quickView = ProductDetails($('#quickViewBox div.productGradient')
			            , styleId, baseImageUrl, actionUrl, null, true);
					initScroll();
					$('#quickViewBox div.closeBox').click(function() {
						quickView.HideCallouts();
						$quickViewDialog.dialog('close');
						$quickViewDialog.html("");
					});
				}, "json");
		});
	};

	this.Initialize();
	return this;
}




function ProductDetails(
		baseElement,
		styleId,
		baseImageUrl,
		actionUrl,
		changeImage,
		isQuickView) {

	this._baseElement = baseElement;
	this._styleId = styleId;
	this._baseImageUrl = baseImageUrl;
	this._actionUrl = actionUrl;
	this._changeImage = changeImage;
	this._isQuickView = isQuickView;

	this.ShowCallouts = function() {
		_baseElement.find('span.validationCallout').each(function() {
			var forElement = _baseElement.find('#' + $(this).attr('forElement'));
			var text = $(this).html();
			var position = 'left';
			if ($(this).attr('position') != null) {
				position = $(this).attr('position');
			}
			forElement.callout({ position: position, msg: text, css: 'guessValidationCallout' });
		});
	};

	this.HideCallouts = function() {
		_baseElement.find('span.validationCallout').each(function() {
			var forElement = _baseElement.find('#' + $(this).attr('forElement'));
			var text = $(this).html();
			forElement.callout('destroy');
		});
	};

	this.RemoveCallouts = function() {

		_baseElement.find('span.validationCallout').remove();
	};

	this.SetSku = function(sku) {
		_baseElement.find("#selectedSku").val(sku);
	};

	this.ResetSize = function() {
		_baseElement.find(".selectedSize").text("").hide();
		_baseElement.find("ul.sizes li.active").removeClass('active');

		if (_baseElement.find("ul.sizes li").length == 1) {
			SetSize(_baseElement.find("ul.sizes li a").attr("id"));
		} else {
			SetSku("");
		}
	};

	this.AddToShoppingBag = function (event) {
		HideCallouts();
		RemoveCallouts();

		var form = _baseElement.find('form')[0];
		if ($(form).find('#selectedSku').val().length == 0) {
			$("<span/>")
					.addClass("validationCallout")
					.css({ display: 'none' })
					.attr('forElement', 'sizeSelectionList')
					.text('Please select a Size before adding to bag')
					.appendTo(_baseElement);

			ShowCallouts();
		} else {
			Sys.Mvc.AsyncForm.handleSubmit(
				form,
				new Sys.UI.DomEvent(event),
				{
					insertionMode: Sys.Mvc.InsertionMode.replace,
					updateTargetId: 'qvb',
					onBegin: function () {
						if (_isQuickView) {
							showPartialProgress($('#quickViewDialog'), true);
						} else {
							showProgress(true);
						}
					},
					onSuccess: function () {
						if (_isQuickView) {
							showPartialProgress($('#quickViewDialog'), false);
							$('#quickViewDialog').dialog('close');
						} else {
							ResetSize();
							showProgress(false);
						}
						OmnitutureTag_ItemAdded();
						Certona_ItemAdded();
						showQvbDialog();
					}
				});
		}
	};

	this.SetSize = function(sku) {
		var sizeSelector = $('#' + sku);
		_baseElement.find(".selectedSize").text(sizeSelector.text()).show();
		_baseElement.find("ul.sizes li.active").removeClass('active');
		sizeSelector.parent().addClass('active');
		SetSku(sku);
		HideCallouts();
		RemoveCallouts();
	};

	this.SetColor = function(color) {
		_baseElement.find("li.selectedColor").html(color);
	};

	this.SetPrice = function(price) {
		_baseElement.find("li.price").html(price);
	};

	this.SetMineImageUrl = function(url) {
		if (_changeImage != null) {
			_changeImage(url);
		} else {
			var mainImage = _baseElement.find('div.largeImage img');
			var completeUrl = _baseImageUrl + url + '?wid=307&hei=412&fmt=jpeg&qlt=85,0&op_sharpen=1&resMode=bicub&op_usm=1.0,1.0,5,0&iccEmbed=0&crop=0,136,1686,2261';
			mainImage.attr("src", completeUrl);
		}
	};

	this.UpdateFlashObject = function(sku) {
		_baseElement.find("#selectedSku").val(sku);
	};

	this.OnSizeClick = function(e) {
		SetSize($(this).attr('id'));
		return false;
	};

	this.LoadImages = function(data) {
		var thumbmailsHolder = _baseElement.find('div.thumbnailHolder');
		thumbmailsHolder.html('');
		SetMineImageUrl(data.Images[0])
		for (var i = 0; i < data.Images.length; i++) {
			//the size of alt image in detail page and quickViewBox page is different, we might need to two different functions to load images?
			if (thumbmailsHolder.height() == 528) {
				var url = baseImageUrl + data.Images[i] + '?wid=98&hei=132&fmt=jpeg&qlt=85,0&op_sharpen=1&resMode=bicub&op_usm=1.0,1.0,5,0&iccEmbed=0&crop=0,136,1686,2261';
				thumbmailsHolder.append("<div class='thumbnail'><img id='" + data.Images[i] + "' src='" + url + "' height='132' width='98'/></div>");
			}
			else {
				var url = baseImageUrl + data.Images[i] + '?wid=77&hei=103&fmt=jpeg&qlt=85,0&op_sharpen=1&resMode=bicub&op_usm=1.0,1.0,5,0&iccEmbed=0&crop=0,136,1686,2261';
				thumbmailsHolder.append("<div class='thumbnail'><img id='" + data.Images[i] + "' src='" + url + "' height='103' width='77'/></div>");
			}
		}
		BindImagesEvents();
	};

	this.LoadSizes = function(data) {
		var sizesHolder = _baseElement.find('ul.sizes');
		sizesHolder.html('');
		for (var i = 0; i < data.Sizes.length; i++) {
			sizesHolder.append("<li><a href='#' id='" + data.Sizes[i].DataValue + "'>" + data.Sizes[i].TextValue + "</a></li>");
		}
		BindSizesEvents();
		ResetSize();
	};


	this.OnColorClick = function(e) {
		HideCallouts();
		RemoveCallouts();

		var color = $(this).attr("id");
		var colorText = $(this).attr("alt");

		$.getJSON(actionUrl,
			{
				styleId: _styleId,
				color: color
			}, function(data) {
				if (data.IsOutOfStock) {
					$("<span/>")
					.addClass("validationCallout")
					.css({ display: 'none' })
					.attr('forElement', color)
					.attr('position', 'top')
					.text('Out of Stock')
					.appendTo(_baseElement);

					ShowCallouts();
				} else {
					SetColor(colorText);
					LoadImages(data);
					LoadSizes(data);
					SetPrice(data.Price);
					initScroll();
				}
			}, "json");
		return false;
	};

	this.OnImageHover = function(e) {
		SetMineImageUrl($(this).attr("id"));
		return false;
	};

	this.BindSizesEvents = function() {
		_baseElement.find("ul.sizes li a").click(this.OnSizeClick);
	};

	this.BindImagesEvents = function() {
		_baseElement.find("div.thumbnail img").hover(this.OnImageHover);
	};

	this.BindEvents = function() {
		BindSizesEvents();
		_baseElement.find("ul.colors li a img").click(this.OnColorClick);
		BindImagesEvents();
		_baseElement.find("div.scrollUp img").click(function() {
			_baseElement.find("div.thumbnailHolder").scrollTo('-=20px', { axis: 'y' });
		});
		_baseElement.find("div.scrollDown img").click(function() {
			_baseElement.find("div.thumbnailHolder").scrollTo('+=20px', { axis: 'y' });
		});
		_baseElement.find(".addToCart a").click(function(e) {
			e.preventDefault();
			AddToShoppingBag(e);
		});
	};

	ResetSize();
	BindEvents();
	return this;
}



