(function() {
	/* 
	 * SKY CAROUNSEL CLASS
	 * Functionality gets automatically attached to a div of class sky-carousel-v2
	 *
	 *
	 *
	 ********************************************************************************************************/
	var SkyHomePageCarousel = function(data) {
		var self = this;
		self.domRoot = data.domRoot;
		self.domItems = $(self.domRoot).find(".sky-carousel-item").get();
		self.items = new Array();
		self.numItems = self.domItems.length; 
		self.dimensions = {
			width: $(self.domRoot).width(),
			height: $(self.domRoot).height() 
		}
		self.jumpToAlignment = $(self.domRoot).find(".sky-carousel-jump-to-alignment").text();
		self.jumpToHorizontalAlignment = $(self.domRoot).find(".sky-carousel-jump-to-vertical-alignment").text();
		self.jumpToHorizontalAlignment = (self.jumpToHorizontalAlignment) ? self.jumpToHorizontalAlignment : "bottom";
		self.jumpToHoverGraphic = $(self.domRoot).find(".sky-carousel-jump-to-hover-graphic").text();
		self.jumpToGraphic = $(self.domRoot).find(".sky-carousel-jump-to-graphic").text();
		self.transitionStyle = $(self.domRoot).find(".sky-carousel-transition-style").text(); 
		self.doAnim = "";
		self.autoplay = $(self.domRoot).find(".sky-carousel-autoplay").text();
		self.autoplay = (self.autoplay == "true" && self.numItems > 1) ? true : false;
		self.autoplayDelay = parseInt(parseFloat($(self.domRoot).find(".sky-carousel-autoplay-delay-seconds").text()) * 1000);
		self.transitionTime = parseInt(parseFloat($(self.domRoot).find(".sky-carousel-transition-time-seconds").text()) * 1000);
		self.initialViewItemIndex = 0;
		self.selectedItemByIndex = 0;
		self.currentlyAnimating = false;
		self.autoplayTimer = "";
		self.cancelTransition = false;
		self.termsAndConditionsExist = false;
		self.domTandCBlock = "";
		self.domTandCContent = "";
	}
	
	SkyHomePageCarousel.prototype = {
		init: function() {
			var self = this;
			$(self.domRoot).find("script").remove();
			
			switch (self.transitionStyle) {
				case "slide":
					self.doAnim = self.doAnimSlide;
					$(self.domRoot).addClass("sky-carousel-transition-style-slide");
				break;
				case "fadeInOut":
					self.doAnim = self.doAnimFadeInOut;
					$(self.domRoot).addClass("sky-carousel-transition-style-fadeInOut");
				break;
				default:
					self.doAnim = self.doAnimFadeBetween;
					$(self.domRoot).addClass("sky-carousel-transition-style-fadeBetween");
				break;	
			}
			
			$.each( self.domItems, function() {
				var termsAndConditions = $(this).find(".sky-carousel-terms-and-conditions-text").html();
				if (termsAndConditions) {
					self.termsAndConditionsExist = true;	
				}
				self.items.push( {
					domItem: this,
					termsAndConditions: termsAndConditions 
				});
				
			});
			
			self.findInitialPanelSetting();
			self.generateHTML();
			self.displayTermsAndConditionsForItem({itemIndex: self.initialViewItemIndex });
			self.initiateJumpTos();
			self.selectJumpToWithIndex({ jIndex: self.initialViewItemIndex });
			if (self.autoplay) {
				setTimeout( function() {
					self.startAutoPlayTimer();
				},2000); // Short delay before auto play starts to allow page to laod
			}
			
			// Prevent transitions when mouse is over the carousel
			$(self.domRoot).hover( function() {
				self.cancelTransition = true;	
			}, function() {
				self.cancelTransition = false;	
			});
			
			return self;
		},
		findInitialPanelSetting: function() {
			var self = this;
			var pageUrl = window.location.toString();
			if (pageUrl.indexOf("?panel=") != -1) {
				var panelNum = parseInt(pageUrl.split("?panel=")[1])-1; 
				self.initialViewItemIndex = (panelNum && panelNum > 0 && panelNum < self.numItems) ? panelNum : 0;
				self.selectedItemByIndex = self.initialViewItemIndex;
			}
			
				
		},
		startAutoPlayTimer: function() {
			var self = this;
			self.autoplayTimer = setTimeout( function() {
				if (self.cancelTransition) {
					if (self.autoplay) {
						self.startAutoPlayTimer();
					}
				}
				else {
					var newItemIndex = ((self.selectedItemByIndex + 1) >= self.numItems) ? 0 : self.selectedItemByIndex + 1;
					self.displayItem({ itemIndex: newItemIndex });
				}
			},self.autoplayDelay);
		},
		killAutoPlayTimer: function() {
			var self = this;
			if (self.autoplayTimer) { 
				clearTimeout(self.autoplayTimer);
				self.autoplayTimer = "";	
			}
		},
		generateHTML: function() {
			var self = this;
			var insertHTML = '<div class="shpc-stage-holder">';
			insertHTML += '<div class="shpc-stage">';
			insertHTML += '</div>';
			insertHTML += '</div>';
			
			self.domStageHolder = $(insertHTML).get()[0];
			self.domStage = $(self.domStageHolder).find(".shpc-stage").get()[0];
			$(self.domItems).detach();
			$(self.domStage).append(self.domItems[self.initialViewItemIndex]);
	
			if (self.domItems.length > 1) {
				var insertHTML = '<ul class="shpc-jumptos shpc-jumptos-aligned-'+self.jumpToAlignment+' shpc-jumptos-aligned-'+self.jumpToHorizontalAlignment+'">';
				$(self.domItems).each( function() {
					var selectedGraphicStyle = ' style="background: url('+self.jumpToHoverGraphic+') left top no-repeat"';
					var unselectedGraphicStyle = ' style="background: url('+self.jumpToGraphic+') left top no-repeat"';
					insertHTML += '<li>';
					insertHTML += '<a href="#"><span class="shpc-jt-default" '+unselectedGraphicStyle+'></span><span class="shpc-jt-selected" '+selectedGraphicStyle+'></span></a>';
					insertHTML += '</li>';
					
					$(this).css({ width: self.dimensions.width, height: self.dimensions.height, float: "left" });
				});
				insertHTML += '</ul>';
				self.domJumpToList = $(insertHTML).get()[0];
				self.domJumpTos = $(self.domJumpToList).find("li").get();
			}
			
			$(self.domStageHolder).css({ width: self.dimensions.width, height: self.dimensions.height });
			$(self.domStage).css({ width: self.dimensions.width * 3, height: self.dimensions.height });
			
			$(self.domItems).css({ width: self.dimensions.width, height: self.dimensions.height });
			$(self.domStageHolder).append(self.domJumpToList);
			$(self.domRoot).append(self.domStageHolder);
			if (self.jumpToAlignment == "centre") {
				self.centreJumpToList();
			}
			// Need to generate the terms and conditions block beneath the carousel
			if (self.termsAndConditionsExist) {
				insertHTML = '<div class="sky-carousel-v2-terms-and-conditions">';
				insertHTML += '<div class="scv2-tandc-inner">';
				insertHTML += '</div>';
				insertHTML += '</div>';
				self.domTandCBlock = $(insertHTML).get()[0];
				self.domTandCContent = $(self.domTandCBlock).find(".scv2-tandc-inner").get()[0];
				$(self.domTandCBlock).css({ width: self.dimensions.width });
				$(self.domRoot).after(self.domTandCBlock);
				self.calculateHeightOfTandCs();
			}
		},
		calculateHeightOfTandCs: function() {
			var self = this;
			// We need the height of the terms and conditions to be set to the height of the tallest content
			var testTermsAndConditions = $(self.domTandCBlock).clone().get()[0];
			var testTermsAndConditionsContent = $(testTermsAndConditions).find(".scv2-tandc-inner").get()[0];
			$(testTermsAndConditions).css({ position: "absolute", left: -999999, top: -999999 });
			$("body").append(testTermsAndConditions);
			var tAndCHeight = 0;
			$.each(self.items, function() {
				$(testTermsAndConditionsContent).html(this.termsAndConditions);
				var thisHeight = $(testTermsAndConditions).height();
				tAndCHeight = (thisHeight > tAndCHeight) ? thisHeight : tAndCHeight;
			});
			$(testTermsAndConditions).remove();
			$(self.domTandCBlock).css({ height: tAndCHeight });
			
		},
		centreJumpToList: function() {
			var self = this;
			var jumpToListWidth = $(self.domJumpToList).width();
			$(self.domJumpToList).css({ left: parseInt(self.dimensions.width/2 - jumpToListWidth/2)});
		},
		initiateJumpTos: function() {
			var self = this;	
			var jumpToIndex = 0;
			$(self.domJumpTos).each( function() {
				var thisIndex = jumpToIndex; 
				$(this).find("a").click( function() {
					// Autoplay should be killed when user interacts with controls
					self.killAutoPlayTimer();
					self.autoplay = false;
					
					self.displayItem({ itemIndex: thisIndex });
					return false;
				}).hover( function() {
					$(this).addClass("shpc-hover");
				}, function() {
					$(this).removeClass("shpc-hover");
				});
				jumpToIndex++;
			});
	
			// For ie, use the png hack to display pngs
			if ($.browser.msie && $.browser.version < 9) {
				if (self.jumpToHoverGraphic.indexOf(".png") != -1) {
					$(self.domJumpToList).find(".shpc-jt-selected").css({
						backgroundImage: "none",
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+self.jumpToHoverGraphic+'", sizingMethod="crop")'
					});	
				}
				if (self.jumpToGraphic.indexOf(".png") != -1) {
					$(self.domJumpToList).find(".shpc-jt-default").css({
						backgroundImage: "none",
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+self.jumpToGraphic+'", sizingMethod="crop")'
					});
				}
			}
	
		},
		displayTermsAndConditionsForItem: function(data) {
			var self = this;
			var itemIndex = data.itemIndex;	
			$(self.domTandCContent).html(self.items[itemIndex].termsAndConditions);
		},
		displayItem: function(data) {
			var self = this;
			var newItemIndex = data.itemIndex;

			// We only want autoplay to iterate through the options once
			// So when we show the first item again, we kill autoplay
			if (newItemIndex == 0) {
				self.killAutoPlayTimer();
				self.autoplay = false;
			}

			if (self.currentlyAnimating || newItemIndex == self.selectedItemByIndex) {
				return;	
			}
			var oldItemIndex = self.selectedItemByIndex;
			
			self.selectJumpToWithIndex({ jIndex: newItemIndex });
			self.deselectJumpToWithIndex({ jIndex: oldItemIndex });

			self.currentlyAnimating = true;

			if (self.termsAndConditionsExist) {
				self.displayTermsAndConditionsForItem({ itemIndex: newItemIndex });
			}
			self.doAnim({ 
				newItemIndex: newItemIndex, 
				oldItemIndex: oldItemIndex,
				callback: function() {
					self.selectedItemByIndex = newItemIndex;
					self.currentlyAnimating = false;
					if (self.autoplay) {
						self.killAutoPlayTimer();
						self.startAutoPlayTimer();
					}
				}
			})
		},
		doAnimSlide: function(data) {
			var self = this;
			var newItemIndex = data.newItemIndex;
			var oldItemIndex = data.oldItemIndex;
			var callback = data.callback;
			// If the index is greater than currently visible item, then we append the new item
			// animate, to reveal it. remove the existing item, and reset the left pos of stage to 0
			// If the index is lower, then we prepend the new item, shift the stage to ensure the existing
			// item is visible, then animate to reveal the new item. And then remove the existing item
			if (newItemIndex > oldItemIndex) {
				$(self.domStage).append(self.domItems[newItemIndex]);
				$(self.domStage).animate({ left: -self.dimensions.width }, self.transitionTime, function() {
					$(self.domItems[oldItemIndex]).detach();
					$(self.domStage).css({ left: 0 });
					callback();
				});
			}
			else {
				$(self.domStage).prepend(self.domItems[newItemIndex]).css({left: -self.dimensions.width });
				$(self.domStage).animate({ left: 0 }, self.transitionTime, function() {
					$(self.domItems[oldItemIndex]).detach();
					callback();
				});
			}
		},
		doAnimFadeBetween: function(data) {
			var self = this;
			var newItemIndex = data.newItemIndex;
			var oldItemIndex = data.oldItemIndex;
			var callback = data.callback;
			$(self.domStage).prepend(self.domItems[newItemIndex]);
			$(self.domItems[oldItemIndex]).animate({opacity: 0 }, self.transitionTime, function() {
				$(self.domItems[oldItemIndex]).detach();
				$(self.domItems[oldItemIndex]).css({ opacity: 1 });
				callback();
			});
		},
		doAnimFadeInOut: function(data) {
			var self = this;
			var newItemIndex = data.newItemIndex;
			var oldItemIndex = data.oldItemIndex;
			var callback = data.callback;
			var sectionTransitionTime = parseInt(self.transitionTime/2);
			
			$(self.domItems[oldItemIndex]).animate({opacity: 0 }, sectionTransitionTime, function() {
				$(self.domItems[oldItemIndex]).detach();
				$(self.domItems[oldItemIndex]).css({ opacity: 1 });
				$(self.domItems[newItemIndex]).css({ opacity: 0 });
				$(self.domStage).append(self.domItems[newItemIndex]);
				$(self.domItems[newItemIndex]).animate({opacity: 1}, sectionTransitionTime, function() {
					callback();
				});
			});
		},
		selectJumpToWithIndex: function(data) {
			var self = this;
			if (self.numItems <=1) {
				return;	
			}
			var jIndex = data.jIndex;
			$(self.domJumpTos[jIndex]).addClass("shpc-jumptos-selected");
		},
		deselectJumpToWithIndex: function(data) {
			var self = this;
			if (self.numItems <=1) {
				return;	
			}
			var jIndex = data.jIndex;
			$(self.domJumpTos[jIndex]).removeClass("shpc-jumptos-selected");
		}
	}
	
	$(document).ready( function() {
		$("body").addClass("jsEnabled"); // Remove this on live
		$(".sky-carousel-v2").each( function() {
			new SkyHomePageCarousel({
				domRoot: this
			}).init();
		});
	});

})();
