﻿(function($) {

$.widget("ui.pricebox", {
	_timer: null,

	_init: function() {
		var self = this;
		this.element.parents('dl:first')
			.mouseout(function(ev) { self._onMouseOut(ev); })
			.mouseover(function(ev) { self._onMouseOver(ev); });
	},

	show: function() {
		this.element.removeClass(this.options.classHidden);
	},

	hide: function() {
		this.element.addClass(this.options.classHidden);
	},

	_onMouseOut: function(e) {
		var self = this;
		if (!this.element.is('.' + this.options.classHidden))
			this._timer = setTimeout(function() { self.hide() }, this.options.hideDelay);
	},

	_onMouseOver: function(e) {
		if (this._timer) {
			clearTimeout(this._timer);
			this._timer = null;
		}
	}
});

$.ui.pricebox.defaults = {
	classHidden: "hidden",
	hideDelay: 3000
};

$.widget("ui.gallery", {
	_timer: null,

	_init: function(element) {
		var self = this;
		this.element
			.mouseout(function(ev) { self._onMouseOut(ev); })
			.mouseover(function(ev) { self._onMouseOver(ev); });
	},

	_setImage: function(element) {
		var url = $(element || this.element).attr('url');
		if (url)
			$(this.options.productImgElement).attr('src', url);
	},

	_onMouseOut: function(ev) {
		var self = this;
		this._timer = setTimeout(function() { self._setImage(null); }, this.options.hideDelay);
	},

	_onMouseOver: function(ev) {
		this._setImage(ev.target);
		if (this._timer) {
			clearTimeout(this._timer);
			this._timer = null;
		}
	}
});

$.ui.gallery.defaults = {
	productImgElement: "#imgProduct",
	hideDelay: 3000
};

$.widget("ui.ajaxUpdater", {
	_init: function() {
		this._template = $.template(this.options.url);
	},

	invoke: function(parameters) {
		if (!this.options.hideLoader)
			this.element.addClass(this.options.classAlpha).ajaxIndicator({className: this.options.classLoader});
		var self = this;
		$.ajax({
			type: "GET",
			url: this._template.evaluate(parameters),
			cache: false,
			complete: function(request, status) {
				if (!self.options.hideLoader)
					self.element.removeClass(self.options.classAlpha).ajaxIndicator('destroy');
				if (request.status == 200)
					self.element.html(request.responseText);
				else
					self.element.addClass(self.options.classAlpha).ajaxIndicator({className: self.options.classError});
			}
		});
	}
});

$.ui.ajaxUpdater.defaults = {
	url: null,
	hideLoader: false,
	classAlpha: "alpha40",
	classLoader: "icon-loader",
	classError: "icon-error"
};

var TabManager = function(tabs) {
	this.tabs = tabs;
	this.switchTab();
	var self = this;
	setInterval(function() {
		if (self._tabId != document.location.hash)
			self.switchTab();
	}, 20);
}

TabManager.prototype = {
	_tabId: null,
	_prefix: "div",
	_classWrite: "write",
	_classActive: "active",
	_attributeId: "tabid",

	switchTab: function() {
		var id = (this._tabId = document.location.hash).toLowerCase();
		var tabReview = $('#' + this._prefix + "TabReviews");
		if (id == "#writereview") {
			id = "#tabreviews";
			tabReview.addClass(this._classWrite);
		} else
			tabReview.removeClass(this._classWrite);
		var defaultTab = null;
		var hasSelectedTab = false;
		for (var i = 0; i < this.tabs.length; i++) {
			var tab = $(this.tabs[i]);
			with (this.configureTab(id, tab)) {
				hasSelectedTab |= selected;
				if (isDefault) defaultTab = tab;
			}
		}
		if (!hasSelectedTab && defaultTab)
			this.configureTab(null, defaultTab);
	},

	configureTab: function(id, tab) {
		var isDefault = tab.attr("default");
		var tabPage = $('#' + this._prefix + tab.attr(this._attributeId));
		var result = {
			selected: tabPage.attr('id').replace(this._prefix, "#").toLowerCase() == id || !id && isDefault,
			isDefault: isDefault
		};
		if (result.selected) {
			var updater = tabPage.attr('updater');
			if (updater) {
				$('#' + updater).ajaxUpdater('invoke', {});
				tabPage.removeAttr('updater');
			}
			tabPage.show();
			tab.addClass(this._classActive);
		} else {
			tabPage.hide();
			tab.removeClass(this._classActive);
		}
		return result;
	}
};

$.extend({
	tabManager: function(tabs) {
		return new TabManager(tabs);
	}
});

})(jQuery);

function setQtyBox(cb) {
	$('#qty_' + $(cb).val()).disabled(!cb.checked).val(cb.checked ? '1' : '0');
}

var ytPlayer = null;

function onYouTubePlayerReady(playerId) {
	if (ytPlayer)
		$(ytPlayer).remove();
	ytPlayer = document.getElementById(playerId);
}

function showGallery(selectedIndex) {
	$('#newgallery').show();
	if ($('#newgallery').attr('initialized'))
		$('#thumbnails > a').each(function (index) {
			if (index == selectedIndex)
				$(this).click();
		});
	else {
		$('#newgallery').attr('initialized', true);
		initGallery(selectedIndex);
	}
}

function hideGallery() {
	if (ytPlayer)
		ytPlayer.stopVideo();

	$('#newgallery').hide();
}

function initGallery(selectedIndex) {
	function showImage(image) {
		if (!image)
			return;
		var originalWidth = parseInt(image.attr('originalWidth'));
		var originalHeight = parseInt(image.attr('originalHeight'));
		var aspect = image.attr('aspect');
		if (originalWidth && originalHeight && aspect) {
			var disabled = image.draggable('option', 'disabled');
			var viewPortWidth = viewPort.width();
			var viewPortHeight = viewPort.height();
			var dragAreaLeft, dragAreaTop, dragAreaWidth, dragAreaHeight;
			if (disabled) {
				dragAreaWidth = originalWidth;
				dragAreaHeight = originalHeight;
				if (dragAreaWidth > viewPortWidth)
					dragAreaHeight = Math.round((dragAreaWidth = viewPortWidth) / aspect, 0);
				if (dragAreaHeight > viewPortHeight)
					dragAreaWidth = Math.round((dragAreaHeight = viewPortHeight) * aspect, 0);
				dragAreaLeft = Math.round((viewPortWidth - dragAreaWidth) / 2);
				dragAreaTop = Math.round((viewPortHeight - dragAreaHeight) / 2);
				image
					.css('left', 0)
					.css('top', 0)
					.width(dragAreaWidth)
					.height(dragAreaHeight);
			} else {
				dragAreaLeft = viewPortWidth - originalWidth;
				dragAreaTop = viewPortHeight - originalHeight;
				if (dragAreaLeft > 0) {
					dragAreaLeft = Math.round(dragAreaLeft / 2);
					dragAreaWidth = originalWidth;
				} else
					dragAreaWidth = originalWidth - dragAreaLeft;
				if (dragAreaTop > 0) {
					dragAreaTop = Math.round(dragAreaTop / 2);
					dragAreaHeight = originalHeight;
				} else
					dragAreaHeight = originalHeight - dragAreaTop;
			}
			dragArea
				.css('left', dragAreaLeft + 'px')
				.css('top', dragAreaTop + 'px')
				.width(dragAreaWidth)
				.height(dragAreaHeight);
			viewPort.removeClass('zoomin zoomout').addClass(disabled ? 'zoomin' : 'zoomout');
			image.fadeIn('fast');
		}
	}

	function clearViewPort() {
		if (selectedImage) {
			selectedImage.hide();
			selectedImage = null;
		}
	}

	var selectedImage = null;
	var viewPort = $('.viewport').addClass('loading');
	var dragArea = $('<div/>').css('position', 'absolute').appendTo(viewPort);

	$(window).resize(function () {
		showImage(selectedImage);
	});

	$('#mediaTypeBox').change(function () {
		var mediaType = $(this).val();
		var invalidate = false;
		var thumbnails = $('#thumbnails')
			.children('a')
			.each(function () {
				invalidate |= $(this)[!mediaType || $(this).is('.' + mediaType) ? 'show' : 'hide']().is(':hidden.selected');
			})
			.end();
		if (invalidate)
			thumbnails.children(':visible:first').click();
	});

	$('#thumbnails')
		.children('a.image[imageUrl]')
		.each(function (index) {
			var thumbnail = $(this)
				.click(function (ev) {
					$(this).siblings().removeClass('selected').end().addClass('selected');
					clearViewPort();
					if (ytPlayer != null) {
						$(ytPlayer).remove();
						ytPlayer = null;
					}
					image.draggable('option', 'disabled', true);
					showImage(selectedImage = image);
					ev.stopPropagation();
					ev.preventDefault();
				})[index == selectedIndex ? 'addClass' : 'removeClass']('selected');
			var image = $(new Image());
			image.bind('load',
				function () {
					var originalWidth, originalHeight;
					image.appendTo(dragArea)
						.attr('originalWidth', originalWidth = image.width())
						.attr('originalHeight', originalHeight = image.height())
						.attr('aspect', originalWidth / originalHeight)
						.hide()
						.css('position', 'absolute')
						.draggable({
							disabled: true,
							containment: 'parent',
							start: function (event, ui) { viewPort.addClass('move') },
							stop: function (event, ui) { viewPort.removeClass('move') }
						})
						.click(function (ev) {
							var disabled = image.draggable('option', 'disabled');
							var offset = image.offset();
							image.draggable('option', 'disabled', !disabled);
							showImage(image);
							if (disabled) {
								var aspect_x = 1 - (ev.pageX - offset.left) / image.width();
								var aspect_y = 1 - (ev.pageY - offset.top) / image.height();
								var x = Math.round((dragArea.width() - originalWidth) * aspect_x);
								var y = Math.round((dragArea.height() - originalHeight) * aspect_y);
								image
									.css('left', x + 'px')
									.css('top', y + 'px')
									.width(originalWidth + 'px')
									.height(originalHeight + 'px');
							}
						});
					if (thumbnail.is('.selected')) {
						viewPort.removeClass('loading');
						showImage(selectedImage = image);
					}
				})
				.attr('src', thumbnail.attr('imageUrl'));
		})
		.end()
		.children('a.video[videoId]')
		.each(function () {
			var thumbnail = $(this)
				.click(function (ev) {
					var videoId = $(this).siblings().removeClass('selected').end().addClass('selected').attr('videoId');
					clearViewPort();
					var params = { allowScriptAccess: "always" };
					var attributes = { id: "ytPlayer" };
					var query = { enablejsapi: 1, version: 3, playerapiid: attributes.id };
					swfobject.embedSWF(
						'http://www.youtube.com/v/' + videoId + '?' + jQuery.param(query),
						$('<div id="ytPlayerPlace"/>').appendTo('.viewport').attr('id'),
						"100%", "100%", "8", null, null, params, attributes);
					ev.stopPropagation();
					ev.preventDefault();
				});
			if (thumbnail.is('.selected'))
				thumbnail.click();
		});
};
