/**
 * @author justin
 */
$(document).ready(function() {
	
	/**
	 * navigation setup closure 
	 * @link {http://www.sohtanaka.com/web-design/mega-drop-downs-w-css-jquery/}
	 */
	(function() {

		//Set custom configurations
		var config = {
				sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
				interval: 100, // number = milliseconds for onMouseOver polling interval
				over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
				timeout: 500, // number = milliseconds delay before onMouseOut
				out: megaHoverOut // function = onMouseOut callback (REQUIRED)
		};
		
		$("#navigation li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
		$("#navigation > ul > li").hoverIntent(config); //Trigger Hover intent with custom configurations
		
		$("#navigation li .sub").each(function(){
			$(this).parent().find('> a').wrapInner('<span />').append('<span class="menu-hint-icon arrow-icon arrow-icon-s" />');
//			$(this).parent().find('a').replaceWith(content);
//			$('<span class="menu-hint-icon arrow-icon-s"></span>').appendTo($(this).parent().find('a'));
		});
		
		//On Hover Over
		function megaHoverOver(){
			
			if ($(this).find(".sub").length > 0) {
				$(this).toggleClass('parent-state-over');
			}
			
			$(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
			
			(function($) {
				//Function to calculate total width of all ul's
				jQuery.fn.calcSubWidth = function() {
					rowWidth = 0;
					//Calculate row
					$(this).find("ul").each(function() { //for each ul...
						rowWidth += $(this).width() + parseInt($(this).css('padding-right')); //Add each ul's width together plus padding
					});
				};
			})(jQuery); 
			
			if ( $(this).find(".row").length > 0 ) { //If row exists...
				
				var biggestRow = 0;	
				
				$(this).find(".row").each(function() {	//for each row...
					$(this).calcSubWidth(); //Call function to calculate width of all ul's
					//Find biggest row
					if(rowWidth > biggestRow) {
						biggestRow = rowWidth;
					}
				});
				
				$(this).find(".sub").css({'width' :biggestRow}); //Set width
				$(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin
				
			} else { //If row does not exist...
				
				$(this).calcSubWidth();  //Call function to calculate width of all ul's
				$(this).find(".sub").css({'width' : rowWidth}); //Set Width
				
			}
		};
		
		//On Hover Out
		function megaHoverOut(){
			if ($(this).find(".sub").length > 0) {
				$(this).toggleClass('parent-state-over');
			}
			$(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opacity
				$(this).hide();  //after fading, hide it
			});
		};
		
	})();

	if ($("#main > .carousel").length > 0) {
		$.getJSON("/carousel/home", function(data){
			$.each(data, function(key, val){
				var img = new Image();
				img.src = val;
				var element = $("<img>").attr("src", val);
				$("#main > .carousel").append(element);
			});
			$("#main > .carousel").carousel({autoScroll: true, timeout: 5000, duration: 3200, interval: 9000})
				.prepend('<div class="viewport-frame">') // inject a frame for the gradient
				.find('.viewport-frame')
				.css({
					zIndex: 2,
					position: 'absolute',
					width: 980,
					height: 354,
					background: 'url(/images/ui/home_carousel_viewport_frame.png)'
				});
		});
	}
	
	if ($("#content_carousel > .carousel").length > 0) {
		$.getJSON("/carousel/content", function(data){
			$.each(data, function(key, val){
				var img = new Image();
				img.src = val;
				var element = $("<img>").attr("src", val);
				$("#content_carousel > .carousel").append(element);
			});
			$("#content_carousel > .carousel").carousel({duration: 1600, interval: 9000, autoScroll: true})
				.prepend('<div class="viewport-frame">') // inject a frame for the gradient
				.find(".viewport-frame")
				.css({
					zIndex: 2,
					position: 'absolute',
					width: 480,
					height: 354,
					background: 'url(/images/ui/content_carousel_viewport_frame.png)'
				});
		});
	}
	
	$("#promo_panel").load("/promo_panel", function(data){
		$("#promo_panel").carousel({duration: 1000, autoScroll: true, timeout: 0, arrows: true});
	});
	
	$(".scrollable").scrollbar({containerHeight: 354, arrows: false}); // initialise scrollbars
	$(".scrollable").find(".scrollbar-pane").wrap('<div class="scrollbar-pane-container"/>').end()
		.find('.scrollbar-pane-container').css({position: 'absolute', width: 480, height: 354, overflow: 'hidden'}); // wrap new container round pan to fix input focus bug
	
});

/**
 * Custom jQuery carousel plugin
 */
(function ($){
	
	$.fn.carousel = function(options) {
		
		if ($(this).children().length <= 1) {
			return $(this);
		}
		
		var interval;
		var timeout;
		
		var defaults = {
			css: {
				controllers: {
					position: 'absolute',
					zIndex: 2,
					height: 16,
					width: 16,
					top: ($(this).height() - 16) / 2,
					textAlign: 'center'
				},
				viewport: {
					height: $(this).height(),
					width: $(this).width(),
					zIndex: 1
				}
			},
			duration: 2000,
			interval: 4000,
			timeout: 10000,
			easing: 'easeInOutSine',
			autoScroll: false,
			arrows: true
				
		};
		
		var settings = $.extend(true, defaults, options);
		
		$(this).css({
			position: 'relative',
			overflow: 'hidden',
			width: settings.css.viewport.width,
			height: settings.css.viewport.height
		});
		
		var viewport = $("<div>")
			.css($.extend({position: 'absolute', overflow: 'hidden'}, settings.css.viewport))
			.addClass('carousel-viewport');
		
		var prevController = $("<div><</div>")
			.addClass('carousel-controller-prev ui-icon ui-icon-triangle-1-w')
			.css(settings.css.controllers)
			.css('left', 0)
			.click(function(){
				scrollPrev();
				initAutoScroll();
				return false;
			})
			.hover(
				function(){
					$(this).css("cursor", "pointer");
				}
			);
		
		var nextController = $("<div>></div>")
			.addClass('carousel-controller-next ui-icon ui-icon-triangle-1-e')
			.css(settings.css.controllers)
			.css('right', 0)
			.click(function(){
				scrollNext();
				initAutoScroll();
				return false;
			})
			.hover(
				function(){
					$(this).css("cursor", "pointer");
				}
			);
		
		function initAutoScroll() {
			if (settings.autoScroll) {
				window.clearTimeout(timeout);
				window.clearInterval(interval);
				timeout = window.setTimeout(function(){
					interval = window.setInterval(scrollNext, settings.interval + settings.duration); 
				}, settings.timeout);
			}
		}
		
		function scrollNext() {
			if (viewport.children().queue().length == 0) {
				viewport.children().each(function() {
					$(this).animate(
						{left: '-=' + viewport.width()}, 
						settings.duration,
						settings.easing,
						function () {
							if (parseInt($(this).css('left')) < 0) {
								$(this).remove().css('left', viewport.children().length * viewport.width());
								$(this).appendTo(viewport);
							}
						}
					);
				});
			}
		}
		
		function scrollPrev() {
			if (viewport.children().queue().length == 0) {
				viewport.children().last().remove().css({left: 0 - viewport.width()}).prependTo(viewport);
				viewport.children().each(function() {
						$(this).animate(
							{left: '+=' + viewport.width()}, 
							settings.duration,
							settings.easing,
							function(){}
						);
				});
			}
		}
		
		initAutoScroll();
		
		var slides = new Array();

		$(this).children().each(function(){
			slides.push($(this));
			$(this).remove();
		});
		
		$(this).append(viewport);
		
		if (settings.arrows) {
			$(this).append(prevController).append(nextController);
		}
		
		for (i = 0; i < slides.length; i++) {
			slides[i].css({position: 'absolute', left: i * viewport.width()});
			viewport.append(slides[i]);
		}

		return $(this);
		
	};
	
})(jQuery);

