/*
	Origional Code this was based off of:
	jQuery Coda-Slider v2.0 - http://www.ndoherty.biz/coda-slider
	Copyright (c) 2009 Niall Doherty
	This plugin available for use in all personal or commercial projects under both MIT and GPL licenses.
	
	However...
	This has been modified alot... so i wouldnt bet on it working the way you want it to
	- Jeremy
*/

// Preloader stuff for this shit
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)



$(function(){
	// Remove the coda-slider-no-js class from the body
	$("body").removeClass("abb_p-slider-no-js");
	// Preloader
	$(".abb_p-slider").children('.panel').hide().end().prepend('<p class="loading"><img src="/img/base_img/loader-black-bg.gif" alt="loading..."/></p>');
	
	//using the preloader
	jQuery.preLoadImages("/img/base_img/loader-black-bg.gif", "/img/base_img/loader-yellow-bg.gif", "/img/base_img/abb-facts-logo.gif", "/img/base_img/close-button.gif");
	
	if($("#pin_nutrition_facts").length > 0) {
		var image_to_load_up = $("#nutrition_facts_src").attr('rel');
		//alert(image_to_load_up);
		jQuery.preLoadImages(image_to_load_up);
	}
	
});

var sliderCount = 1;

$.fn.abb_pSlider = function(settings) {

	settings = $.extend({
		autoHeight: true,
		autoHeightEaseDuration: 200,
		autoHeightEaseFunction: "easeInOutQuad",
		autoSlide: false,
		autoSlideInterval: 7000,
		autoSlideStopWhenClicked: true,
		crossLinking: true,
		dynamicTabs: false,
		dynamicTabsAlign: "center",
		dynamicTabsPosition: "top",
		externalTriggerSelector: "a.xtrig",
		firstPanelToLoad: 1,
		panelTitleSelector: "h2.title",
		slideEaseDuration: 450,
		slideEaseFunction: "easeInOutExpo"
	}, settings);
	
	return this.each(function(){
		
		// Uncomment the line below to test your preloader
		 //alert("Testing preloader");
		
		var slider = $(this);
		
		
		
		
		// A function for the lightbox shit
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#loading').show();
				
			$('#yellow_box').prepend('<div id="lightbox-image-container"><h3 id="facts_title_box">'+ $('#product_info h2').text() + '</h3><img id="lightbox-image" title="Click to Close"/></div>');
			
			$('#lightbox-image,#lightbox-image-container').hide();
			
			var image_to_load_up = $("#nutrition_facts_src").attr('rel');
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				
				$('#loading').fadeOut(100);
				var image_to_load_up = $("#nutrition_facts_src").attr('rel');
				$('#lightbox-image').attr('src',image_to_load_up);
				$('#lightbox-image').attr('alt',$('#product_info h2').text());
				
				_show_image();
				// Perfomance an effect in the image container resizing it
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = image_to_load_up;
		};
		
		// A function for the lightbox shit
		function _show_image() {
			
			$('#lightbox-image').show();
			$('#facts_title_box').show();
			$('#lightbox-image-container').show();
			
			var top_height_one = $(window).height() / 2;
			var top_height_two = $("#lightbox-image").height() / 2;
			var new_top_height = top_height_one - top_height_two - 95;
			
			if(new_top_height < 35) {
				new_top_height = 35 + "px";	
			} else {
				new_top_height = Math.round(new_top_height) + "px";
			}
			
			$('#lightbox-image-container').animate({"top" : new_top_height}, 400, "easeOutBack", function(){
						
						if($("#lightbox-image-container p").length == 0) {
						$("#lightbox-image-container").append("<p>( CLICK TO CLOSE )</p>");
						$("#lightbox-image-container p").delay(500).slideDown(600);
																			
						}
			});
			
		};
		
		// A function for the lightbox shit
		function _hide_image() {
			//$('#facts_title_box').empty().remove();
			$('#lightbox-image').fadeOut(5, function() {										 
				$('#lightbox-image-container').hide();	
				$('#lightbox-image-container').css({"top": "-650px"});
			});
			$('#lightbox-image-container p').empty().remove();
		}
		
		
		
		
		// ADDED TO USE FOR A LIGHTBOX FOR NUTRITION INFORMATION
		function launch_factsbox() {
			//$('body').css({"overflow" : "hidden"});
			$('body').append('<div id="yellow_box"><img id="close_button" src="/img/base_img/close-button.gif" style="float:right; margin:10px; background-color:#000; width:26px; height:26px; overflow:hidden; color:#ffc425;" alt="close" title="Click to close" /><div id="loading"><img src="/img/base_img/loader-yellow-bg.gif" alt="loading..."/></div></div>');
			$("#product_info").fadeOut(200);
			//$('#yellow_box').css({"width": "100%", "height":document.height, "background-color": "#ffc425", "position" : "absolute", "z-index" : "999999", "top" : "0px", "left" : "0px", "display" : "none"});
			  if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 7) {
				  
			  } else {
				  $('#yellow_box').css({"height" : $(document).height() });
			  }
			
			$('select, embed, object').hide();
			//$('#yellow_box').animate({"width" : "100%"}, 200, function () {
			$('#yellow_box').slideDown(250,  function(){
			// Insert all the good stuff to run the lightbox there
					_set_image_to_view();				  
			});
			
			// Ammend this to include other objects to close the lightbox
			$("#yellow_box").click(
				function() {
					//$(this).removeAttr("href");
					$("#yellow_box").fadeOut(150, function() { 
														   
						$("#product_info").fadeIn(200); $('select, embed, object').show();
						$("#yellow_box").unbind('click');
						$("#close_button").hide();
						$("#yellow_box").empty().remove();
						_hide_image();
						});
					
			});	
		}
		
	
		
		var panelWidth = slider.find(".panel").width();
		var panelCount = slider.find(".panel").size();
		var panelContainerWidth = panelWidth*panelCount;
		var navClicks = 0; // Used if autoSlideStopWhenClicked = true
		
		// Surround the collection of panel divs with a container div (wide enough for all panels to be lined up end-to-end)
		$('.panel', slider).wrapAll('<div class="panel-container"></div>');
		// Specify the width of the container div (wide enough for all panels to be lined up end-to-end)
		$(".panel-container", slider).css({ width: panelContainerWidth });
		
		// Specify the current panel.
		// If the loaded URL has a hash (cross-linking), we're going to use that hash to give the slider a specific starting position...
		if (settings.crossLinking && location.hash && location.hash == "#info"){
			var currentPanel = 1;
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
		} else if (settings.crossLinking && location.hash && location.hash == "#facts"){
			launch_factsbox();
			var currentPanel = 1;
			var offset = 0;
			$('.panel-container').css({ marginLeft: offset });
		} else if (settings.crossLinking && location.hash && location.hash == "#moreinfo"){
			var currentPanel = 2;
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
		} else if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
			var currentPanel = parseInt(location.hash.slice(1));
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
		// If that's not the case, check to see if we're supposed to load a panel other than Panel 1 initially...
		} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) { 
			var currentPanel = settings.firstPanelToLoad;
			var offset = - (panelWidth*(currentPanel - 1));
			$('.panel-container', slider).css({ marginLeft: offset });
		// Otherwise, we'll just set the current panel to 1...
		} else { 
			var currentPanel = 1;
		};
			
		
		
		
			
		// If we need a tabbed nav
		$('#abb_p-nav-' + sliderCount + ' a').each(function(z) {
			// What happens when a nav link is clicked
			if ($(this).attr("href") == "#facts") {
							$(this).bind("click", function() {
							launch_factsbox();
							//slider.siblings('.abb_p-nav').find('a').removeClass('current').parents('ul').find('li:eq(0) a').addClass('current');
							});
			} else {
			
				$(this).bind("click", function() {
					navClicks++;
					$(this).addClass('current').parents('ul').find('a').not($(this)).removeClass('current');
					offset = - (panelWidth*z);
					alterPanelHeight(z);
					currentPanel = z + 1;
					$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
				});
			}
			if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
		});
		
		
		// External triggers (anywhere on the page)
		$(settings.externalTriggerSelector).each(function() {
			// Make sure this only affects the targeted slider
			if (sliderCount == parseInt($(this).attr("rel").slice(12))) {
				$(this).bind("click", function() {
					navClicks++;
			
						if ($(this).attr("href").slice(1) == "facts") {
							
							launch_factsbox();
							targetPanel = 1;
							offset = 0;
							alterPanelHeight(targetPanel - 1);
							currentPanel = targetPanel;
							// Switch the current tab:
							slider.siblings('.abb_p-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') a').addClass('current');
	
							// Slide
							$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
							
						} else {
							targetPanel = parseInt($(this).attr("href").slice(1));
							offset = - (panelWidth*(targetPanel - 1));
							alterPanelHeight(targetPanel - 1);
							currentPanel = targetPanel;
							// Switch the current tab:
							slider.siblings('.abb_p-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (targetPanel - 1) + ') a').addClass('current');
	
							// Slide
							$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
						}
						
					if (!settings.crossLinking) { return false }; // Don't change the URL hash unless cross-linking is specified
				});
			};
		});
		
		
		
		
		// Specify which tab is initially set to "current". Depends on if the loaded URL had a hash or not (cross-linking).
		if (settings.crossLinking && location.hash && location.hash == "#info"){
			$("#abb_p-nav-" + sliderCount + " a:eq(0)").addClass("current");
		} else if (settings.crossLinking && location.hash && location.hash == "#facts"){
			launch_factsbox();
			$("#abb_p-nav-" + sliderCount + " a:eq(0)").addClass("current");	
		} else if (settings.crossLinking && location.hash && location.hash == "#moreinfo"){
			$("#abb_p-nav-" + sliderCount + " a:eq(1)").addClass("current");
		} else if (settings.crossLinking && location.hash && parseInt(location.hash.slice(1)) <= panelCount) {
			$("#abb_p-nav-" + sliderCount + " a:eq(" + (location.hash.slice(1) - 1) + ")").addClass("current");
		// If there's no cross-linking, check to see if we're supposed to load a panel other than Panel 1 initially...
		} else if (settings.firstPanelToLoad != 1 && settings.firstPanelToLoad <= panelCount) {
			$("#abb_p-nav-" + sliderCount + " a:eq(" + (settings.firstPanelToLoad - 1) + ")").addClass("current");
		// Otherwise we must be loading Panel 1, so make the first tab the current one.
		} else {
			$("#abb_p-nav-" + sliderCount + " a:eq(0)").addClass("current");
		};
		
		// Set the height of the first panel
		if (settings.autoHeight) {
			panelHeight = $('.panel:eq(' + (currentPanel - 1) + ')', slider).height();
			slider.css({ height: panelHeight });
		};
		
		// Trigger autoSlide
		if (settings.autoSlide) {
			slider.ready(function() {
				setTimeout(autoSlide,settings.autoSlideInterval);
			});
		};
		
		function alterPanelHeight(x) {
			if (settings.autoHeight) {
				panelHeight = $('.panel:eq(' + x + ')', slider).height()
				slider.animate({ height: panelHeight }, settings.autoHeightEaseDuration, settings.autoHeightEaseFunction);
			};
		};
		
		function autoSlide() {
			if (navClicks == 0 || !settings.autoSlideStopWhenClicked) {
				if (currentPanel == panelCount) {
					var offset = 0;
					currentPanel = 1;
				} else {
					var offset = - (panelWidth*currentPanel);
					currentPanel += 1;
				};
				alterPanelHeight(currentPanel - 1);
				// Switch the current tab:
				slider.siblings('.abb_p-nav').find('a').removeClass('current').parents('ul').find('li:eq(' + (currentPanel - 1) + ') a').addClass('current');
				// Slide:
				$('.panel-container', slider).animate({ marginLeft: offset }, settings.slideEaseDuration, settings.slideEaseFunction);
				setTimeout(autoSlide,settings.autoSlideInterval);
			};
		};
		
		// Kill the preloader
		$('.panel', slider).show().end().find("p.loading").remove();
		slider.removeClass("preload");
		
		sliderCount++;
		
	});
};
