/**
 * 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);
	});		
};

/**
 * Makes the placeholder attribute on input items useful by emulating the behavior
 */ 
$.fn.placeholder = function() {
	if ((this[0] && 'placeholder' in document.createElement('input')) || this.size() == 0) return this;
	
	return this
		.val($(this).attr('placeholder')).addClass('placeholder')
		.focus(function() {
			if ($(this).val() === $(this).attr('placeholder')) {
		        $(this).val('').removeClass('placeholder');
			}
		})
		.blur(function() {
			if ($(this).val() === ''){
				$(this).val($(this).attr('placeholder')).addClass('placeholder');
			}
		});
};

var markupPrep = {
	
	init: function(){
		this.listPrep();
		this.tablePrep();
	},
	
	/**
	 * Adds the class 'last' to the last list items, and the last table item in a row. 
	 */
	listPrep: function() {
		$('> li:last', 'ul, ol').addClass('last');
	},
	
	/**
	 * Adds alt class to odd table rows.
	 */
	tablePrep: function() {
		$('table tr:odd').addClass('alt');
		$('table td:last, table th:last').addClass('last');
	}

};

var content = {
	
	init: function(){
		this.homePhotoGallery();
		this.mainPhotoGallery();
		
		if ( $('body.home').length ) // twitter feed is only on homepage
			this.twitterFeed();
	},
	
	twitterFeed: function(){
		var $profile_image = $('#whats-new div.twitter img.image-left'),
			$feed_list = $('#whats-new ul.twitter-feed'),
			url = "http://twitter.com/status/user_timeline/Smoky_Mountain.json?count=4&callback=?",
			html_result = '',
			img_url = '';
		
		$.getJSON(url, function(data){
		
			var date, gmtHours, now;

			$.each(data, function(i, item) {

				date = Date.parse(item.created_at);			
				gmtHours = -date.getTimezoneOffset() / 60;
				date = date.add(gmtHours).hours();
				now = new Date();

				// get the profile image
				if ( img_url == '' )
					img_url = item.user.profile_image_url;
				
				item.text = linkify(item.text);
				
				html_result += '<li>' + item.text + ' <span>' + date.toString('h:mm tt MMM d') + '</span></li>';
		   
		    }); //each
		    
		    $feed_list.html(html_result);
		    $profile_image.attr('src', img_url);
		    
		});
	},
	
	//this should probably be redone with JSON sometime
	homePhotoGallery: function(){
		var $thumbnail_wrap = $('body.home ul.poloroids');

		$thumbnail_wrap.load('/includes/home-facebook-albums', function(){
			$thumbnail_wrap.prev('p').remove();
			$thumbnail_wrap.find('li:last').addClass('last');
		});
		
	},
	
	//this should probably be redone with JSON sometime
	mainPhotoGallery: function(){
		var $thumbnail_wrap = $('#gallery-thumbs');

		$thumbnail_wrap.load('/includes/main-facebook-albums', function(){
			$thumbnail_wrap.find('p').remove();
			$thumbnail_wrap.find('li:last').addClass('last');
		});
		
	},
	
}

$(document).ready(function() {
	$('input[placeholder]').placeholder();
	$('div.image-left, div.image-right').imageWidth();
	$('span.pullquote-left, span.pullquote-right').pullQuote();
	
	$('.innerfade').innerFade({
		animationType: 'fade',
		speed: 'slow',
		timeout: '10000',
		prevLink: '.button-previous',
	    nextLink: '.button-next',
		indexContainer: '.innerfade-control ul',
		containerHeight: '200px'
	});
	           
	markupPrep.init();
	content.init();
});
