window.mccain = window.mccain || {};
mccain.utils = mccain.utils || {};

(function (_) {
	
	// abort if class(es) are already defined
	if (_.TabMenu) return;
	
	_.usesPie = $('.ie6, .ie7, .ie8').length > 0 ? true : false;
	
	/*******************************************************************************
	Some utility functions that can be used globally.

	*******************************************************************************/
	_.createLargeNutritionTable = function($table, $id) {
		//create a copy of the small table
		var table = $($table).clone();
		//create container for large table
		var container 	= $('<div>').appendTo('body').hide();
		var wrapper		= $('<div>').addClass('lrgNutritionTable')
									.attr('id', $id)
									.appendTo(container);
		
		//insert copy of small table in new wrapper
		table.appendTo(wrapper);
	};
	
	/*******************************************************************************
	TabMenu class
	
	This class represents an instance of the tabbed menu component.
	
	//default usage
	$(document).ready(function() {
		var tabs = new mccain.utils.TabMenu('.tabbed-menu');
		
		//select tab by index
		//This would manually select the first tab
		tabs.selectByIndex(0);
		
		//select tab by id
		//This is assuming there is an <li> element in the tabs <ul> that has an id="mytab"
		//NOTE: you must include the pound symbol(#) for ids and the period(.) for classes
		tabs.selectBySelector('#mytab');
	});

	*******************************************************************************/
	_.TabMenu = function($element) {
		this.init.apply(this, arguments);
	}
	
	$.extend(_.TabMenu.prototype, {
		element: null,
		tabs: null,
		content: null,
		init: function($element) {
			//tab menu wrapper
			this.element = $($element);
			this.tabs    = $('.tabs li', this.element);
			this.content = $('.content-wrapper .content', this.element);
			
			var o = this;
			$('a', this.tabs).each(function($i, $e) {
				$(this).bind('click', {index: $i}, $.proxy(o._onTabClickEvent, o));
				//determine if any of the text is double lined
				var link 		= $(this);
				var lineHeight 	= link.css('line-height').replace('px', '');
				var lines		= Math.round( link.height()/lineHeight );

				//determine whether the link is one or two lines and add proper classname
				if(lines > 1) {
					//if( _.usesPie ) PIE.detach($e);
					link.addClass('double-line');
				}
			});
		},
		/***
		* Public:
		* This can be used to manually select a tab based on index.
		* The $index numbers are zero based so if you want to select the first tab you 
		* would pass in 0 and if you wanted the second tab you would pass in 1 and so on...
		*
		* If a valid tab button is not found nothing will happen.
		**/
		selectByIndex: function($index) {
			var tab = $('.tabs li:eq('+$index+') a', this.element);
			if(tab) tab.trigger('click');
		},
		/***
		* Public:
		* This can be used to manually select a tab based on a unique selector.
		* The $id can be either a HTML class or id attribute, but if it is a class it must be unique.
		* The attribute must be on the <li> element in tabs <ul> in order to be recognized.
		*
		* If a valid cta button is not found nothing will happen.
		**/
		selectBySelector: function($id) {
			var item = $($id + ' a', this.element);
			if(item) item.trigger('click');
		},
		_onTabClickEvent: function($e) {
			$e.preventDefault();
			$($e.currentTarget).blur();
			
			//activate clicked tab
			this.tabs.removeClass('active');
			var tab = $($e.currentTarget).parent('li').addClass("active");
			
			//show corresponding tab content
			var index = $e.data.index;
			this.content.hide();
			var content = $(".content-wrapper .content:eq("+index+")", this.element).show();
			
			//CSS3 Pie fix for any elements that were display none and are having issues rendering
			//just put the css class .pie on the element and this will fix it
			if( _.usesPie ) {
				$('.pie', content).each(function($i, $e) {
					PIE.attach($e);
				})
			}
		}
	});
	
	/*******************************************************************************
	ProductCarousel class
	
	This class represents an instace of a product carousel.
	The carousel is currently set up to wrap when scrolling so that it never ends.
	
	//default usage
	$(document).ready(function() {
		var carousel = new mccain.utils.ProductCarousel('.product-carousel');
		
		//select tab by index
		//This would manually select the first tab
		carousel.selectByIndex(0);
		
		//select tab by id
		//This is assuming there is an <li> element in the products <ul> that has an id="myproduct"
		//NOTE: you must include the pound symbol(#) for ids and the period(.) for classes
		carousel.selectBySelector('#myproduct');
	});

	*******************************************************************************/
	_.ProductCarousel = function($element) {
		$('.product-carousel').css('display', 'block');
		this.init.apply(this, arguments);
	};

	$.extend(_.ProductCarousel.prototype, {
		elements: null,
		totalItems: 0,
		itemWidth: 0,
		totalWidth: 0,
		minItems: 0,
		scrollBy: 1,
		initialX: 0, 
		direction: 0,

		init:function($element) {		
			this.elements		  = {};
			this.elements.wrapper = $($element);
			this.elements.ul	  = $('.products', this.elements.wrapper);
			
			if( this.elements.ul.length == 0 ) return;
			
			this.elements.mask	  = $('.carousel-mask', this.elements.wrapper);
			this.elements.btnNext = $('.btn-right', this.elements.wrapper).bind('click', {}, $.proxy(this._scrollClicked, this));
			this.elements.btnPrev = $('.btn-left', this.elements.wrapper).bind('click', {}, $.proxy(this._scrollClicked, this));

			this.itemWidth 		= $('li:first', this.elements.ul).width();
			this.initialX		=  this.elements.ul.position().left;
						
			this._initValues();
			this._setClickListeners();
			
			
			// adjust for multiple lines

			$('a span', this.elements.ul).each(function($i, $e) {
				//determine if any of the text is double lined
				var link 		= $(this);
				var lineHeight 	= link.css('line-height').replace('px', '');
				var lines		= Math.round( link.height()/lineHeight );

				//console.log(lines);
				
	

				//determine whether the link is one or two lines and add proper classname
				if(lines === 2) {
					link.addClass('two-line');
				}else if(lines === 3) {
					link.addClass('three-line');
				}else if(lines >= 4){
					link.addClass('four-line');
				};
			});
			
			
		},
		/***
		* Public:
		* This can be used to manually select a product based on index.
		* The $index numbers are zero based so if you want to select the first product you 
		* would pass in 0 and if you wanted the second product you would pass in 1 and so on...
		* This will also force the product to be in view in the carousel if it is off screen.
		* If a valid tab button is not found nothing will happen.
		**/
		selectByIndex: function($index) {
			var item = $('li:eq('+$index+') a', this.elements.ul);
			
			if(item) {
				item.trigger('click');
				this._forceScroll($index);
			}
		},
		/***
		* Public:
		* This can be used to manually select a product based on a unique selector.
		* The $id can be either a HTML class or id attribute, but if it is a class it must be unique.
		* The attribute must be on the <li> element in the products <ul> in order to be recognized.
		* This will also force the product to be in view in the carousel if it is off screen.
		* If a valid cta button is not found nothing will happen.
		**/
		selectBySelector: function($id) {
			var item = $($id + ' a', this.elements.ul);
			
			if(item) {
				item.trigger('click');
				var index = item.parent('li').index();
				this._forceScroll(index);
			}
		},
		_forceScroll: function($index) {
			var pos = ($index+1)*this.itemWidth;
			if(pos > this.elements.mask.width()) {
				var remainder = pos - this.elements.mask.width();
				var num = remainder/this.itemWidth;
				
				while(num > 0) {
					this.elements.btnNext.trigger('click', true);
					num--;
				}
			}
		},
		refresh: function() {
			this.elements.ul.css('left', this.initialX + "px");
			this._initValues();
		},
		_setClickListeners: function() {
			$('a', this.elements.ul).bind('click', {}, $.proxy(this._onItemClickEvent, this));
		},
		_onItemClickEvent: function($e) {	
			var item = $($e.currentTarget);

			$('li', this.elements.ul).removeClass('selected');
			
			item.parent('li').addClass('selected');
		},
		_initValues: function() {
			//calculate min items for carousel
			this.minItems = Math.ceil(this.elements.mask.width()/this.itemWidth);
			
			this.totalItems 	= $('li', this.elements.ul).length;
			this.totalWidth 	=  this.itemWidth * this.totalItems;

			this.elements.ul.width(this.totalWidth);

			if (this.totalItems <= this.minItems) {
				this.elements.btnNext.hide();
				this.elements.btnPrev.hide();
				//remove end divider shadow
				$('.left', this.elements.wrapper).hide();
			} else {
				this.elements.btnNext.show();
				this.elements.btnPrev.show();
			}
			//trigger initiated event
			$(this).trigger('carouselInit');
		},
		_scrollClicked: function($event, $noAnimation) {
			$event.preventDefault();
			$event.stopImmediatePropagation();
			$($event.currentTarget).blur();
			
			//don't go any further if we're already animating
			if( this.elements.ul.is(':animated') ) return;
			
			this.direction = $($event.currentTarget).hasClass('btn-right') ? -1 : 1;
			
			//this will ensure that there are items on left side of carousel 
			//on first click of positive scroll
			if(this.direction > 0 && this.elements.ul.position().left == 0) {
				this._onScrollComplete();
			}
			
			var move = this.direction * (this.itemWidth*this.scrollBy);
			//get current position of the ul and minus the initial x position so it's not factored in
			var curPosition = this.elements.ul.position().left - this.initialX;
			//calculated new position of ul
			var newPosition = curPosition + move;
			//calculate the maxScroll for the ul
			var maxScroll = (this.totalWidth - this.elements.mask.width())*scroll;
			
			//make sure we don't scroll too far on either side
			//this logic is for if carousel is not infinite loop
			/*
			if (scroll > 0) {
				if (newPosition > 0) newPosition = 0;
			} else {
				if (newPosition <= maxScroll) newPosition = maxScroll;
			}
			*/
			
			var time = 500;
			if($noAnimation) time = 0;
				
			//console.log(maxScroll + "," + newPosition + "," + curPosition);
			this.elements.ul.animate(
					{ "left": newPosition+"px" }, 
					{
						duration: time,
						easing: 'easeOutQuad',
						complete: $.proxy(this._onScrollComplete, this)
					});
		},
		_onScrollComplete: function($event) {
			//this will wrap the elements around so they infinitely loop
			var offset = (this.totalItems-1)-this.scrollBy;
			var move;
			
			if(this.direction < 0) {
				move = $('li:lt('+ this.scrollBy +')', this.elements.ul);
			} else {
				move = $('li:gt('+ offset +')', this.elements.ul);
			}
			
			var curLeft = this.elements.ul.css("left").replace('px', '');
			var first 	= $('li:first', this.elements.ul);
			var last 	= $('li:last', this.elements.ul);
			
			if(this.direction < 0) {
				//copy first items to back of carousel
				$(last).after(move);
				//indent position comepnsating for moved elements
				var indent = Number(curLeft) + (this.itemWidth*this.scrollBy);
				this.elements.ul.css('left', indent+"px");
			} else {
				//copy first items to back of carousel
				$(first).before(move);
				//indent position comepnsating for moved elements
				var indent = Number(curLeft) - (this.itemWidth*this.scrollBy);
				this.elements.ul.css('left', indent+"px");
			}
		}
	});
	//Carousel end
	
	/*******************************************************************************
	ToolTip class
	
	When this class is initiated it acts as a manger for all the tooltips present on
	the page. It's in charge of hiding and showing the tooltip for the corresponding link.
	
	For each link on the page with the ".tip" class there has to be a corresponding ".tooltip"
	in the "#tooltips" container on the page.
	
	The link that has the tip class must have an id attribute. The tooltip that corresponds to that
	link needs to have a class that has the same name as the id used on the link.
	
	Example:
	
	<a href="#" id="myTip" class="tip">Tooltip link</a>
	
	<div class="tooltip myTip">
		<img class="arrow" src="/img/img-tooltip-arrow.png" width="15" height="20" alt="" />
		<h1 class="heading">Tooltip Heading</h1>
		<div class="tip-content">
			<div class="p">Lorem ipsum</div>
			<img class="img-tool" src="/img/product-page/tooltip-potatoes.png" width="100" height="100" alt="" />
		</div>
	</div>
		
	</div>
	
	*******************************************************************************/
	_.ToolTip = new function() {

		return {
			initialized: false,	
			links: null,
			tips: null,
			init: function() {
				if(this.initialized) return;
				this.initialized = true;
				this.links 	= $('.tip').bind('mouseover mouseout click', {}, $.proxy(this._onLinkMouseEvent, this));
				this.tips	= $('#tooltips');
				
				//IE7 z-index fix for tooltip
				// if( $('.ie7').length > 0 ) {
				//  	var zIndexNumber = 1000;
				//                  	
				//  	this.links.mouseover(function () {
				//  	    zIndexNumber += 10;
				// 			   	 	    $(this).css('zIndex', zIndexNumber);
				// 			 	 	});
				// }

			},
			_showToolTip: function($link) {
				var tooltip = $('.tooltip', $link);
				//check to see if tooltip has already been inserted in link
				
				if( tooltip.length <= 0 ) {
					var id = $link.attr('id');
					var xPos = $link.width() + 15 + "px"; //15 accounts for width of arrow
					//add tooltip to link
					var tip = $('.'+id, this.tips).remove();
					//position x position of tooltip
					
					tip.css("left", xPos);
					tip.appendTo($link);
				}
				//show tooltip
				tooltip.show();

			},
			_onLinkMouseEvent: function($e) {
				var link = $($e.currentTarget);
				$e.preventDefault();
				// $e.stopImmediatePropagation();
				switch($e.type) {
					case "click":
						$e.preventDefault();
						this._showToolTip( link );
						$('.tip').css('z-index','5');
						link.css('z-index','1000');
					break;
					
					case "mouseover":
						this._showToolTip( link );
						$('.tip').css('z-index','5');
						link.css('z-index','1000');
					break;
					
					case "mouseout":
						this._hideToolTip( link );
						$('.tip').css('z-index','5');
					break;
				}
			},
			_hideToolTip: function($link) {
				$('.tooltip', $link).hide();
			}
		}
	}();
	
})(mccain.utils)


					


