// Constants
var addToCartPath = 'addtocart.txt';
var ratingPath = 'rating.txt';

var registrationStartPath = 'registration_start.html';
var registrationForgotPwPath = 'registration_forgotpw.html';
var registrationSignup1Path = 'registration_signup_step1.html';
var registrationSignup2Path = 'registration_signup_step2.html';

//  HSN Visual Effects
var isIE = (navigator.appName == "Microsoft Internet Explorer")?true:false;
var isIE7 = (document.documentElement && typeof document.documentElement.style.maxHeight!="undefined")?true:false;
var isSafari = (document.childNodes)&&(!document.all)&&(!navigator.taintEnabled)&&(!navigator.accentColorName)?true:false;

window.onload = function() {
	if($$('.movieDetails').length > 0) {
		try {
			Event.observe($$('.movieDetails .carouselBody .detailsWrapper a.moreInfoBtn')[0], 'click', function() {		
				carousel(-1, null, $$('.movieDetails .carouselBody')[0], 1);
			});
			Event.observe($$('.movieDetails .carouselBody .moreDetailsWrapper a.goBackBtn')[0], 'click', function() {		
				carousel(1, null, $$('.movieDetails .carouselBody')[0], 1);
			});
		} catch (e) {
			//do nothing...
			//alert("no carouselBody");
		}
	}

	//Add to Cart functions
	new Insertion.After('page', '<div id="addToCartFloaterTo" style="display: none;"><img src="/img/addToCartFloater.gif" /></div>'); 
	var addToCartFloaterTo = $('addToCartFloaterTo');
	var floaterDimensions = addToCartFloaterTo.getDimensions();
	var cartIcon = $('cartBtn');
	var cartIconDimensions = cartIcon.getDimensions();
	var animatingCart = false;
	
//	window.initCartButtons = function() {
//		$$('.addToCartBtn').each(function(btn) {
//			if (!btn.initted) {
//				Event.observe(btn, 'click', function() {
//					showAddToCart(btn.parentNode);
//				});
//				btn.initted = true;
//			}
//		});
	
//		$$('.addToCartBtnOn', '.addToCartOptions').each(function(btn) {
//			if (!btn.initted) {
//				Event.observe(btn, 'mouseover', function() {
//					btn.parentNode.getElementsBySelector('.addToCartBtnOn', '.addToCartOptions').each(function(addToCart) {
//						if(addToCart.parentNode==lastAddToCart)
//							hideAddToCartCancel();
//					});
//				});
//				Event.observe(btn, 'mouseout', function() {
//					hideAddToCartTimout(btn.parentNode);
//				});
//				btn.initted = true;
//			}
//		});
		
//		$$('.addToCartOptions .optionsWrapper .option').each(function(btn) {
//			if (!btn.initted) {
//				Event.observe(btn, 'click', function() {
//					hideAddToCart(lastAddToCart);
//					addToCart(btn.parentNode.parentNode.parentNode.getElementsBySelector('.addToCartBtn')[0]);
//				});
//				btn.initted = true;
//			}
//		});
		
//		$$('.addToCartSingleBtn').each(function(btn) {
//			if (!btn.initted) {
//				Event.observe(btn, 'click', function() {
//					addToCart(btn);
//				});
//				btn.initted = true;
//			}
//		});
//	}
	
//	initCartButtons();
	
	var hideAddToCartTimer = null;
	var lastAddToCart = null;
	
	window.showAddToCart = function(btn) {
		if(lastAddToCart)
			hideAddToCart(lastAddToCart);
		btn.getElementsBySelector('.addToCartBtnOn', '.addToCartOptions').each(function(addToCartBtn) {
			addToCartBtn.show();
		});
		lastAddToCart = btn;
	}
	
	window.hideAddToCartTimout = function(btn) {
		hideAddToCartTimer = setTimeout (function() { hideAddToCart(btn) }, 1000);
	}

	window.hideAddToCart = function(btn) {
		hideAddToCartCancel();
		btn.getElementsBySelector('.addToCartBtnOn', '.addToCartOptions').each(function(addToCartBtn) {
			addToCartBtn.hide();
		});
	}
	
	window.hideAddToCartCancel = function() {
		clearTimeout(hideAddToCartTimer);
	}
	
	window.addToCart = function(btn) {
		incrementCart();
		if(animatingCart)
			return;

		animatingCart = true;
		var cartIconPosition = Position.positionedOffset(cartIcon);
		// Position Floater over add to cart btn
//		Position.clone(btn, addToCartFloaterTo, {
//			offsetLeft: ((btn.getDimensions().width - floaterDimensions.width) / 2) + 55,
//			offsetTop: ((btn.getDimensions().height - floaterDimensions.height) / 2)
//		});
        
        var addToCartIconPosition = Position.cumulativeOffset(btn);
        addToCartFloaterTo.style.left = (addToCartIconPosition[0]+floaterDimensions.width)+"px";
        addToCartFloaterTo.style.top = addToCartIconPosition[1]+"px";
		addToCartFloaterTo.style.position = "absolute";
		addToCartFloaterTo.style.zIndex = 1001;
		// Toggle Vis on
		addToCartFloaterTo.show();
		// Animate Floater to Cart
		new Effect.Move($('addToCartFloaterTo'), {
			x: cartIconPosition[0] + ((cartIconDimensions.width - floaterDimensions.width) / 2) + 25,
			y: cartIconPosition[1] + ((cartIconDimensions.height - floaterDimensions.height) / 2),
			mode: 'absolute',
			duration: 1
		});	
		// Clean up
		setTimeout (function() {
			animatingCart = false;
			addToCartFloaterTo.hide();
		}, 2000);
	}

	window.incrementCart = function() {
	    if(!$('cartTop').visible()) {
			Effect.SlideDown('cartBody', {duration: 0.6});
			$('cartBtn').style.background = "url(/newimg/btnCartOutBg.gif) no-repeat";
			$('cartTop').show();
		}
//		new Ajax.Updater($$('#cartBtn .count')[0], addToCartPath, {
//			method: 'get',
//			evalScripts: false,
//			onComplete: function() {
//			    		if(!$('cartTop').visible()) {
//			Effect.SlideDown('cartBody', {duration: 0.6});
//			$('cartBtn').style.background = "url(/newimg/btnCartOutBg.gif) no-repeat";
//			$('cartTop').show();
//		}
////				openCart();
//			}
//		});
	}
	

	// Cart Flyout	
	Event.observe('cartBtn', 'click', function() {
		// make sure there's no other effects happening on the page
		if (Effect.Queue.effects.length > 0) return;
		
		if (!$('cartBody').visible()) {
			openCart();
		}
		else {
			closeCart();
		}
	});
	
	window.openCart = function() {
		if(!$('cartTop').visible()) {
			Effect.SlideDown('cartBody', {duration: 0.6});
			$('cartBtn').style.background = "url(/newimg/btnCartOutBg.gif) no-repeat";
			$('cartTop').show();
		}
	}
	
	window.closeCart = function() {
		if($('cartTop').visible()) {
			$('cartBtn').style.background = "url(/newimg/btnCartBg.gif) no-repeat";
			Effect.SlideUp('cartBody', {duration: 0.6});
			setTimeout (function() {
				$('cartTop').hide();
			}, 600);
		}
	}

	// Login Flyout
	if($('regOpenBtn')) {
		var registrationFormDownloaded = false;
		Event.observe('regOpenBtn', 'click', function() {
			getRegistration();
		});
		Event.observe('regCloseBtn', 'click', function() {
			toggleReg();
		});
		
		function getRegistration() {
			//if(registrationFormDownloaded) {
			//	toggleReg();
			//} else {
				// notice the use of a proxy to circumvent the Same Origin Policy.
				new Ajax.Updater($$('.myVideoPlayPanelOn')[0], registrationStartPath, {
					method: 'get',
					evalScripts: true,
					onComplete: function() {
						registrationFormDownloaded = true;
						toggleReg();
					}
				});
			//}
		}

		function toggleReg() {
			// make sure there's no other effects happening on the page
			if (Effect.Queue.effects.length > 0) return;
			
			var regBody = $$('.myVideoPlayPanelOn')[0];
			
			if (!regBody.visible()) {
				Effect.SlideDown(regBody, {duration: 1});
				$('regCloseBtn').show();
				$('regOpenBtn').hide();
			}
			else {
				Effect.SlideUp(regBody, {duration: 1});
				setTimeout (function() {
					$('regCloseBtn').hide();
					$('regOpenBtn').show();
					//carousel(-1, null, $$('.myVideoPlayPanelOn .regWrapper .carouselBody')[0], 1, 0);
				}, 1000);
			}
		}
	}
	
	// Star Rating
	$$('.starRating a').each(function(starRating) {
		Event.observe(starRating, 'click', function() {
			var selectedRating = starRating.classNames().toString().substr(6,1);
			new Ajax.Updater($$('.myVideoPlayPanelOn')[0], ratingPath, {
				method: 'get',
				evalScripts: true,
				parameters: { rating: selectedRating },
				onComplete: function(transport) {
					var currentRating = starRating.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName('currentRating')[0];
					currentRating.setStyle({width:(transport.responseText*14)+'px'});
				}
			});
		});
	});
	

	// Carousel Scrolling
	$$('.carouselBody:not(.carouselNhlBody)').each(function(currentCarousel) {
		currentCarousel.getElementsByClassName('slideButtons').each(function(buttons) {
			buttons = buttons.descendants();

			Event.observe(buttons[1], 'click', function() {		
				carousel(-1, buttons, currentCarousel);
			});
			Event.observe(buttons[0], 'click', function() {		
				carousel(1, buttons, currentCarousel);
			});

			carousel(0, buttons, currentCarousel);
		});
	});

	$$('.carouselContainer div)').each(function(carouselItem) {
		Event.observe(carouselItem, 'mouseover', function() {
			if(carouselItem.classNames().toString()!="avators") {
				carouselItem.getElementsBySelector('.thumbnail img').each(function(image) {
					image.setStyle({border:'solid 3px #f90'});
				});
				carouselItem.getElementsBySelector('.itemTitle a', '.userTitle a').each(function(image) {
					image.setStyle({color:'#f90'});
				});
			}
		});
		Event.observe(carouselItem, 'mouseout', function() {
			if(carouselItem.classNames().toString()!="avators") {
				carouselItem.getElementsBySelector('.thumbnail img').each(function(image) {
					image.setStyle({border:'solid 3px #000'});
				});
				carouselItem.getElementsBySelector('.itemTitle a', '.userTitle a').each(function(image) {
					image.setStyle({color:'#fff'});
				});
			}
		});
	});

	$$('.showInfoWrapper').each(function(btn) {
		Event.observe(btn, 'click', function() {
			showInfo(btn);
		});
	});
	$$('.hideInfoWrapper').each(function(btn) {
		Event.observe(btn, 'click', function() {
			hideInfo(btn);
		});
		Event.observe(btn, 'mouseover', function() {
			if(btn==lastInfo)
				hideInfoCancel();
		});
		Event.observe(btn, 'mouseout', function() {
			hideInfoTimout(btn);
		});
		// position the drop elements directly below their controlling buttons
		var showBtnX = Position.positionedOffset(btn.parentNode)[0] - Position.positionedOffset(btn.parentNode.parentNode)[0];
		btn.setStyle({"margin-left":(showBtnX-89)+'px'});
	});

	var hideInfoTimer = null;
	var lastInfo = null;
	function showInfo(btn) {
		if(lastInfo)
			hideInfo(lastInfo);
		btn = btn.parentNode.getElementsByClassName('hideInfoWrapper', 'div')[0];
		lastInfo = btn;
		btn.show();
	}
	
	function hideInfoTimout(btn) {
		hideInfoTimer = setTimeout (function() { hideInfo(btn) }, 500);
	}
	
	function hideInfo(btn) {
		hideInfoCancel();
		btn = btn.parentNode.getElementsByClassName('hideInfoWrapper', 'div')[0]
		btn.hide();
	}
	
	function hideInfoCancel() {
		clearTimeout(hideInfoTimer);
	}

	function carousel(dir, buttons, currentCarousel, divUnits, xMoveBy) {
		var carouselCountainer = currentCarousel.getElementsByClassName('carouselContainer', 'div')[0];
		
		// if there's no stageScroll on the page or
		// there's already an animation in the queue then exit
		if(!carouselCountainer || Effect.Queue.effects.length > 0)
			return;
	
		// setup variables
		var curX = Position.positionedOffset(carouselCountainer)[0];
	
		var xMove = carouselCountainer.parentNode.getWidth();
		var divUnits = typeof(divUnits) == "undefined" ? 5 : divUnits;
		
		//alert(xMove + ":" + divUnits);
		
		//if we're one of the smaller scrolls we need to tweak the xMove a little bit.
		if(xMove == 508)
		{
			xMove += 38;
			divUnits = 3;
		}
		else if(xMove == 700)
		{
			xMove += 28;
			divUnits = 4;
		}

		var numScrolls = Math.ceil(carouselCountainer.immediateDescendants().length / divUnits) - 1;
		var xMoveBy = typeof(xMoveBy) == "undefined" ? (xMove * dir) : xMoveBy;
		var xMoveTo = curX + (xMoveBy);
		var xMax = -Math.abs((numScrolls) * xMove);
		var curScroll = Math.abs(xMoveTo / xMove);
		
		// exit if conditions aren't perfect
		if(!(xMoveTo <= 0 && xMoveTo >= xMax))
			return;
			
		if(buttons)
		{
			// setup left / right buttons
			buttons[0].src = xMoveTo >= 0 ? "/newimg/scrollBackOff.gif" : "/newimg/scrollBackOn.gif";
			buttons[1].src = xMoveTo <= xMax ? "/newimg/scrollForwardOff.gif" : "/newimg/scrollForwardOn.gif";
		}
	
		// do the move
		if(dir != 0)
		//{
		//	if(typeof(finalPos)=="undefined")
				new Effect.MoveBy(carouselCountainer, 0, xMoveBy);
		//	else
		//		new Effect.Move(carouselCountainer, { x: finalPos, mode: 'absolute'});
		//}
		
		// setup status indicators
		var indicatorCount = -1;
		var indicators = currentCarousel.getElementsByClassName('indicatorsWrapper', 'div')[0];
	
		if(indicators)
		{
			// delete the old indicators
			while (indicators.firstChild)
				indicators.removeChild(indicators.firstChild);
		
			// add them back in
			while(indicatorCount++ < numScrolls) {
				indicators.appendChild(Builder.node('div', {className:((indicatorCount == curScroll) ? 'on' : 'off')}));
			}
		}
	}
}
