/**
 * @module action
 */

/**
 * TODO: Add description
 * @namespace Moen.action
 * @class Product
 * @static
 */
Moen.action.Product = function () {
	var Product = Moen.action.AbstractAction('products', 'product');

	Product.initialize = function () {
		// Setup Bazaarvoice Integration
		if ($('#BVFrame').length > 0) {
			this.setupBazaarvoice();
		}

		// Setup Omniture tagging for "Where to Buy" link
		this.setupInteractionTracking();

		// Create the modal window used to display the alternate images
		this.setupModalWindow();

		// Handle Valve Changes
		if ($('#valves').length) {
			this.setupValveInteractions();
		}

		(function () {
			var openedSpotResistFinish = false;

			$('.finish, .mirrorscapes_finish').each(function (index, item) {
				var $this = $(this),
					tooltip,
					$tooltipUI = $('.tooltip-ui', $this);

				tooltip = new Moen.ui.Tooltip($this, $tooltipUI.html(), {
					position: 'bottom'
				});

				function showTooltip () {
					openedSpotResistFinish = true;

					tooltip.show();

					var hideTimeout = window.setTimeout(function () {
						tooltip.hide();
					}, 3000);

					function cancelHide () {
						window.clearTimeout(hideTimeout);
					}

					$this.one('mouseenter', function () { cancelHide(); });
					$('#tip-wrapper').live('mouseover', function () { cancelHide(); });
				}

				if (!openedSpotResistFinish && $tooltipUI.hasClass('spot_resist')) {
					var baseSku = $('#product_details').attr('data-baseSku'),
						spotResistViewedSkus = Moen.util.Cookie.get('spotResistViewedSkus');

					if (!spotResistViewedSkus) {
						Moen.util.Cookie.set('spotResistViewedSkus', baseSku, {
							path: '/'
						});
						showTooltip();
					} else {
						var viewed = false;

						spotResistViewedSkus = spotResistViewedSkus.split('%7C');
						for (var i = 0; i < spotResistViewedSkus.length; i++) {
							if (spotResistViewedSkus[i] === baseSku) {
								viewed = true;
							}
						}

						if (!viewed) {
							spotResistViewedSkus.push(baseSku);
							Moen.util.Cookie.set('spotResistViewedSkus', spotResistViewedSkus.join('|'), {
								path: '/'
							});
							showTooltip();
						}
					}
				}
			});
		})();

		$('#print_this_page').click(function (event) {
			event.preventDefault();
			window.print();
		});

		(function () {
			var $alternateViews = $('#media-alternate_views'),
				$list = $alternateViews.find('ul'),
				$items = $list.find('li').not('.enlarge'),
				numberOfViews = $items.length;

			if (numberOfViews > 4) {
				var $left = $('#media-alternate_views-left'),
					$right = $('#media-alternate_views-right'),
					position = 0,
					step = 51;

				$alternateViews.addClass('assembled');
				$list.width(step * $items.length);

				var leftover = $list.width() - $alternateViews.width();

				$left.click(function () {
					if (position > 0) {
						move(-1);
					}
				});

				$right.click(function () {
					if (position < numberOfViews - 4) {
						move(1);
					}
				});
				
				function move (newPosition) {
					position = position + newPosition;
					$list.animate({
						left: -position * step
					}, 250);
				}
			}
		})();

                // START of carousel
                	// Setup the carousels
		$('.suggestionsScroller').each(function() {
			var id = $(this).attr('id').split('-')[1];
			$(this).jCarouselLite({
		        btnNext: '#nextS' + id,
	            btnPrev: '#prevS' + id,
	            visible: 6,
				speed: 1250,
				circular: false,
				scroll: 6
		    });
		});

		// Get the position of the first and last card that are visible. In IE, the first and last card are not able to go above the prev/next arrows, we need to shift the enlarged card position on the first and last cards.
		var firstVisibleItemPos = $('.suggestionsScroller li:first').offset().left;
                var lastVisibileItemPos = 0;
		if($('.suggestionsScroller li').length > 6) {
			lastVisibleItemPos = $('.suggestionsScroller li:eq(4)').offset().left;
		}

                // END of carousel

	};

	Product.setupBazaarvoice = function () {
		document.domain = 'moen.ca';

		var productSku = $('#BVFrame').attr('data-sku');
		var bvEnvironmentUri = $('#BVFrame').attr('data-bv-environment-uri');

		window['BVisLoaded'] = false;
		function BVcheckLoadState() {
			if(!BVisLoaded) {
				var page = document.getElementById('BVFrame').src;
				document.getElementById('BVFrame').src='http://reviews.moen.com/' + bvEnvironmentUri + 'logging?page=' + escape(page);
				document.getElementById('BVReviewsContainer').innerHTML = '<!-- Review retrieval timed out -->';
			}
		}

		(function () {

			var bvPage = 'http://reviews.moen.com/' + bvEnvironmentUri + '0544/' + productSku + '/reviews.htm?format=embedded';
			var bvReviewIDName = 'featurereview';

			var bvReviewIDRegex = new RegExp('[?&]' + bvReviewIDName + '=([^&#]+)');
			var bvReviewIDMatch = bvReviewIDRegex.exec(window.location.search);
			var bvReviewID = bvReviewIDMatch ? decodeURIComponent(bvReviewIDMatch[1]) : null;

			document.getElementById('BVFrame').src = /^[0-9]+$/.test(bvReviewID) ? bvPage + '&reviewid=' + bvReviewID : bvPage;

			//Timeout for review load.  Consider reviews unavailable if not loaded within 15 seconds
			window.setTimeout(BVcheckLoadState, 15000);

		}());

		window['ratingsDisplayed'] = handleRatingsLoad;
		function handleRatingsLoad (totalReviewsCount, avgRating, ratingsOnlyReviewCount, recommendPercentage, productID) {
			$('#rating').show();
			$('#rating-overall').html(avgRating + ' Out of 5');
			$('#rating-write_review').attr('href', $('#BVRRDisplayContentLinkWriteID').find('a[name="BV_TrackingTag_Review_Display_WriteReview"]').attr('href'));
			$('.BVRRHistogram').addClass('shadowed');
			$('.BVRRRatingsHistogramButtonImage').attr('src', '/assets/moencom/images/catalog/product-details/reviews/expand.png');
		}
	};

	Product.setupInteractionTracking = function () {
		// Setup product page interaction tracking
		$('#knockout a, #media-alternate_views a, #finishes a, #actions a').click(function (e) {
			Moen.util.Omniture.trackData({
				name: 'Product Page Interactions',
				type: 'o',
				data: {
					events: 'event16',
					products: s.products
				}
			});
		});

		// Setup W2B link tracking
		$('#where_to_buy').click(function (e) {
			Moen.util.Omniture.trackData({
				name: 'Where to Buy',
				type: 'o',
				data: {
					events: 'event1,event16',
					eVar32: 'Where to Buy',
					products: s.products
				}
			});
		});

		// Setup Cross Sell tracking
		$('#coordinating_items a').click(function (e) {
			Moen.util.Omniture.trackData({
				name: 'Cross Sell',
				type: 'o',
				data: {
					events: 'event22',
					eVar11: 'Cross Sell: ' + $(this).attr('data-sku'),
					products: s.products
				}
			});
		});

		// Setup Up Sell tracking
		$('#suggestions a').click(function (e) {
			Moen.util.Omniture.trackData({
				name: 'Up Sell',
				type: 'o',
				data: {
					eVar11: 'Up Sell: ' + $(this).attr('data-sku'),
					events: 'event11',
					products: s.products
				}
			});
		});

		// Setup Guide link tracking
		$('#download_guides a').click(function (e) {
			var url = Moen.util.String.explodeURL(e.currentTarget.href),
				filename = url.path.replace(/(.*)\//, '') + '.' + url.extension;

			Moen.util.Omniture.trackData({
				name: 'Guide Downloads',
				type: 'o',
				data: {
					events: 'event29',
					eVar17: filename,
					products: s.products
				}
			});
		});

		// Setup Print link tracking
		$('#print_this_page').click(function () {
			Moen.util.Omniture.trackData({
				name: 'Print',
				type: 'o',
				data: {
					eVar32: 'Print',
					products: s.products
				}
			});
		});

		// Setup Save to My Project link tracking
		$('#my_project_link').click(function () {
			Moen.util.Omniture.trackData({
				name: 'Save to My Project',
				type: 'o',
				data: {
					eVar32: 'Save to My Project',
					products: s.products
				}
			});
		});

		// Setup Swatch/Finish link tracking
		$('#finishes a').click(function () {
			Moen.util.Omniture.trackData({
				name: 'Swatch',
				type: 'o',
				data: {
					eVar32: 'Swatch',
					products: s.products
				}
			});
		});

		// Setup Enlarge link tracking
		$('#knockout .enlarge').click(function () {
			Moen.util.Omniture.trackData({
				name: 'Enlarge',
				type: 'o',
				data: {
					eVar32: 'Enlarge',
					products: s.products
				}
			});
		});

		// Setup Alternate Views link tracking
		$('#media-alternate_views a').click(function () {
			Moen.util.Omniture.trackData({
				name: 'Alternate Views',
				type: 'o',
				data: {
					eVar32: 'Alternate Views',
					products: s.products
				}
			});
		});


		// Setup Channel Intelligence link tracking
		/*$('#channel_intelligence').parent().click(function () {
			Moen.util.Omniture.trackData({
				name: 'Channel Intelligence',
				type: 'o',
				data: {
					eVar32: 'Get Prices and Buy button',
					events: 'event16,event44'
				}
			});
		});*/
	};

	Product.setupModalWindow = function () {

		var modalWindow = null;

		$('#knockout .knockout img').click(function () {
			$('#media-alternate_views a').eq(0).click();
		});

		$('#knockout a, #media-alternate_views ul a').live('click', function (event) {
			var url = Moen.util.String.explodeURL(this.href);
			url.extension = (modalWindow) ? 'ajax' : 'modal';
			url.query.title = true;
			url = Moen.util.String.implodeURL(url);

			modalWindow = new Moen.ui.Overlay({
				destroyOnHide: true,
				overlayClass: 'drawer ui-overlay'
			});

			$.get(url, function (html) {
				modalWindow.contentBox = $(html).appendTo('body').get(0);

				$('a.close', modalWindow.contentBox).click(function (event) {
					modalWindow.hide();
					event.preventDefault();
				});

				modalWindow.show();
				centerModalContent();
			}, 'html');

			$(modalWindow).bind(Moen.ui.Overlay.events.SHOW, function () {
				overlay = $(modalWindow.contentBox);

				var $alternateViews = $('<div class="alt_list"/>').append($('#media-alternate_views ul').clone().attr('class', 'gridded')),
					$list = $alternateViews.find('ul'),
					$items = $list.find('li').not('.enlarge');

				overlay.append($alternateViews);

				if ($items.length > 7) {
					$alternateViews.addClass('assembled');
					$list.width(67 * $items.length);

					var leftover = $list.width() - $alternateViews.width();

					var $slider = $('<div/>').slider({
						orientation: 'horizontal',
						slide: function (event, state) {
							$list.css('left', -(state.value / 100) * leftover);
						}
					}).appendTo(overlay);
				} else {
					$list.css('width', 'auto');
					$list.css({
						marginLeft: -$list.width() / 2,
						paddingLeft: '50%'
					});
				}

				$('#modal-window .alt_list a').click(Moen.util.Event.dummyEventHandler).mousedown(function (event) {
					event.preventDefault();

					var url = Moen.util.String.explodeURL(this.href);
					url.extension = 'ajax';
					url = Moen.util.String.implodeURL(url);

					$('#modal-content').load(url, function () {
						centerModalContent();
					});
				});
			});

			$(modalWindow).bind(Moen.ui.Overlay.events.HIDE, function() {
				modalWindow = null;
			});

			event.preventDefault();
		});

		function centerModalContent () {
			var viewport = $('#modal-window-content').get(0),
				content = $('#modal-content :first-child').get(0);

			if (content.nodeName.toString().toUpperCase() === 'IMG') {
				$(content).hide();
				$(content).bind('load', function (event) {
					center();
				});
			} else if ($(content).hasClass('flv_video')) {
				$(content).css({
					top: '50%',
					left: '50%',
					margin: '-180px -320px',
					position: 'absolute'
				}).show();
			} else {
				center();
			}

			function center () {
				$(content).css({
					top: '50%',
					left: '50%',
					margin: -($(content).height() / 2) + 'px ' + -($(content).width() / 2) + 'px',
					position: 'absolute'
				}).show();
			}
		}

	};

	Product.setupValveInteractions = function () {
		var basePrice = Number($.trim($('#base_price').text()).substr(1)),
			baseSku = $.trim($('#base_sku').text()),
			components = $.map($('#selections .component'), componentMapper),
			valves = $.map($('#selections .valve'), componentMapper),
			$model = $('#model'),
			$total = $('#total_price');

		function componentMapper (el) {
			return {
				sku: $(el).data('sku'),
				price: Number($(el).data('price'))
			};
		}

		$('#valves .valve').each(function () {
			var valve = this;

			$(valve).find('input:radio').bind($.browser.msie ? 'click' : 'change', function () {
				var thisSku = $(valve).data('sku'),
					skus = [baseSku],
					totalPrice = basePrice;

				var i,j;

				// Find valve and add it's price
				for (i = 0, j = valves.length; i < j; i++) {
					if (thisSku === valves[i].sku) {
						skus.push(valves[i].sku);
						totalPrice += valves[i].price;
						break;
					}
				}

				// Add up the price of all other components
				for (i = 0, j = components.length; i < j; i++) {
					skus.push(components[i].sku);
					totalPrice += components[i].price;
				}

				$model.text(skus.join(' + '));
				$total.text('$ ' + Moen.lang.round(totalPrice, 2));
			});
		});
	};

	return Product;

}();


