/**
 * Resizes floated image containers to the size of the image
 */
$.fn.imageWidth = function(threshold) {
	/**
	 * Function takes a jquery object and a css property (called dimension) and determines how many pixels the item is
	 * @param {jQuery Object} $item The jQuery object we're looking at
	 * @param {String} dimension The CSS property name to look for
	 * @returns The width or height of the CSS property with 'px' removed
	 * @type Number
	 */
	var	determineDimension = function($item, dimension) {
		$item = $($item);
		if ($item.css(dimension)) {
			return parseInt($item.css(dimension).replace('px', ''), 10);
		} else {
			return 0;
		};
		return false;
	};
	
	var	resizeImage = function($image, $parent, $container) {
		// Determine the width of the image along with borders and padding
		var imageWidth = $image.width();
		var paddingLeft = determineDimension($image, 'padding-left');
		var paddingRight = determineDimension($image, 'padding-right');
		var borderLeft = determineDimension($image, 'border-left-width');
		var borderRight = determineDimension($image, 'border-right-width');

		// Calculate total edge (padding and border) width and the total width (edge and image)
		var edgeWidth = paddingLeft + paddingRight + borderLeft + borderRight;
		var totalWidth = imageWidth + edgeWidth;

		// Determine parent width
		var parentWidth = $parent.width();

		// If the image is greater then the threshold times the parent width resize the image and the container width
		// Otherwise set the image left's div to the size of the image plus the edge
		if ((threshold * parentWidth) <= totalWidth) {
			var revisedWidth = parentWidth * threshold;
			var revisedImageWidth = revisedWidth - edgeWidth;

			$image.width(revisedImageWidth);
			$container.width(parseInt(revisedWidth, 10));
		} else {
			$container.width(totalWidth);
		};
	};

	return this.each(function() {
		// Threshold is the maximum width an image plus its border and padding can be 
		// in relation to its parent container
		var threshold = (threshold) ? threshold : 2/3;

		// Find image within div
		var $image = $('img', $(this));
		var $parent = $(this).parent();
		var $container = $(this);

		$image.each(function(index) {
			resizeImage($image, $parent, $container);
			$(this).load(function() {			
				resizeImage($image, $parent, $container);
			});
		});
	});		
};


/**
 * Builds pull quote divs assuming you've wrappted your content with a span with the class: pullquote-left or pullquote-right
 */
$.fn.pullQuote = function() {
	return this.each(function() {
		var contents = $.trim($(this).html());
		var firstCharacterCode = contents.charCodeAt(0);
		if (firstCharacterCode < 65 || firstCharacterCode > 96) {
			contents = '&hellip; ' + contents;
		};
		
		var lastCharacter = contents.charAt(contents.length - 1);
		if ("?!.".search(lastCharacter) < 0) {
			contents = contents + ' &hellip;';
		};
		var $parent = $(this).parent();
		var $pullquote = $('<div>').attr('class', $(this).attr('class')).html(contents);
		$parent.before($pullquote);
	});		
};

/**
 * Clears a text form element when it has the style 'clear-default'
 */
$.fn.clickClear = function() {
	return this.each(function() {
		this.defaultValue = $(this).val();
		$(this).click(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).focus(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val(this.defaultValue);
			};
		});
		
		$('form').submit(function(event) {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		});
	});	
};

var markupPrep = function() {
	var listPrep = function() {
		$('> li:last', 'ul, ol').addClass('last');
	};
	
	var	tablePrep = function() {
		$('table tbody tr:odd').addClass('alt');
		$('table tr').each(function(index) {
			$('*:last', $(this)).addClass('last');
		});
	};
	
	listPrep();
	tablePrep();
};

/**
 * Sets up the Accordion on the Home Page
 */
var featureAccordion = function() {
	var SPEED = 500;
		
	if ($('body.front').size() > 0) {
		// Set opacity to get IE6 to work
		$('#content-feautre dl dd.image').css('opacity', '0');
		$('#content-feature dl.active dd.image').css('opacity', '1.0');
		
		// Set a click event to only the inactive dt
		$('#content-feature dl:not(.active) dt').live('click', function(event) {
			event.preventDefault();
			
			// Define the items
			var $toShow = $(this).parent();
			var $toHide = $('#content-feature dl.active');
			
			// Find height instead of assuming the height if something changes
			var currentHeight = $toHide.find('dd.bottom').height();
			
			// Setup the animations (these can be chained, but it would be slower)
			$toShow.find('div.notch').animate({left: 0}, SPEED);
			$toShow.find('dd.bottom').animate({height: currentHeight}, SPEED);
			$toShow.find('dd.image').animate({opacity: 1.0}, SPEED);
			$toShow.find('dt').animate({backgroundPosition: '(0 -49px)'}, SPEED);
			
			$toHide.find('div.notch').animate({left: -13}, SPEED);
			$toHide.find('dd.bottom').animate({height: 0}, SPEED);
			$toHide.find('dd.image').animate({opacity: 0}, SPEED);
			$toHide.find('dt').animate({backgroundPosition: '(0 0px)'}, SPEED);
			
			// Swap the classes
			$toShow.addClass('active');
			$toHide.removeClass('active');
		});
	};
};

/**
 * Controls image swapping when front page accordion is changed.
 */
var frontFeatureImage = function() {
	$('div#accordion .ui-accordion-header').click(function(event) {
		
		$('div.notch').fadeOut();
		
		if ($('div#accordion #feature-rotary').hasClass('ui-state-active')) {
			$('div#feature-images div#feature-linear-image').fadeOut();
			$('div.notch').animate({
			    top: '10',
			  }, 50, function() {
			    $('div.notch').fadeIn();
			  });
		}
		if ($('div#accordion #feature-linear').hasClass('ui-state-active')) {
			$('div#feature-images div#feature-linear-image').fadeIn();
			$('div.notch').animate({
			    top: '60',
			  }, 50, function() {
			    $('div.notch').fadeIn();
			  });
		}
	});
};

var faqDisplay = function() {
	var slideSpeed = 'normal';
	
	if ($('dl.faqs dt a').size() > 0) {
		$('dl.faqs dt a').each(function(index) {
			var $associatedDD = $(this).parent().next();
			$associatedDD.hide();
			
			$(this).click(function(event) {
				event.preventDefault();
				$associatedDD.slideToggle(slideSpeed);
				pageTracker._trackPageview('/FAQ/Q'+$(this).attr('number'))
				
			});
		});
		
		$('ul.faq-controls li.expand').click(function(event) {
			event.preventDefault();
			$('dl.faqs dd:hidden').slideDown(slideSpeed);
		});
		
		$('ul.faq-controls li.collapse').click(function(event) {
			event.preventDefault();
			$('dl.faqs dd:visible').slideUp(slideSpeed);
		});
	};
};

var videoLoader = function() {
	if ($('.video:visible').size() > 0) {
		// $('#player').flowplayer();
		flowplayer("player", "/js/flowplayer.commercial-3.1.5.swf", {
			key: '#@c1b908743277c75aa37',
			plugins: {
				controls: {
					url: '/js/flowplayer.controls-3.1.5.swf',
					playlist: false,
					time: false,
					
					progressColor: '#9A9995',
					bufferColor: '#E5E4E3',
					
					buttonColor: '#9A9995',
					buttonOverColor: '#B3B2AF',
					
					backgroundColor: '#1a252f',
					backgroundGradient: 'none'
				}
			}
		});
	};
};

$(document).ready(function() {
	$('input.clear-default').clickClear();
	$('div.image-left, div.image-right').imageWidth();
	$('span.pullquote-left, span.pullquote-right').pullQuote();
	
	markupPrep();
	
	// featureAccordion(); let's try UI Accordion instead...
	$('div#content-feature div#accordion').accordion({
		icons: {
			'header':'ui-icon-triangle-1-e',
			'headerSelected':'ui-icon-triangle-1-s'
		}
	});
	
	frontFeatureImage();
	faqDisplay();
	
	// Tabs for the product views
	var $tabs = $(".product-browse .tabs, .catalog .tabs" ).tabs({ selected: 0 });

	$('a.jump-to-tab').click(function(e) { // bind click event to link
		e.preventDefault();
		
		target = $(this).attr('rel');
	    $tabs.tabs('select', target);
	});
	
	videoLoader();
});
