(function($) {
	if(!window['console']) {
		window['console'] = {
			log: function() {
				// var messages = arguments;
				// for(var i = 0; i < messages.length; i++) {
				// 	$('body').append('<p>' + messages[i] + '</p>');
				// }
			}
		};
	}

	$.fn.center = function(params) {
		var options = {
			vertical: true,
			horizontal: true
		},
			// op = Object.extend(options, params || {});
			op = {};

		for(var i in params) {
			op[i] = params[i];
		}

		this.each(function() {
			var element = $(this);

			var width = element.width(),
				height = element.height(),
				paddingTop = parseInt(element.css('padding-top') || 0, 10),
				paddingBottom = parseInt(element.css('padding-bottom') || 0, 10),
				borderTop = parseInt(element.css('border-top') || 0, 10),
				borderBottom = parseInt(element.css('border-bottom') || 0, 10),
				mediaPadding = (paddingTop + paddingBottom) / 2,
				mediaBorder = (borderTop + borderBottom) / 2,
				positionType = element.parent().css('position'),
				halfWidth = (width / 2) * (-1),
				halfHeight = ((height / 2) * (-1)) - mediaPadding - mediaBorder,
				cssProp = { position: 'absolute' };

			if(op.vertical) {
				cssProp.top = '50%';
				cssProp.marginTop = halfHeight + 'px';
			}
			if(op.horizontal) {
				cssProp.left = '50%';
				cssProp.marginLeft = halfWidth + 'px';
			}
			if(positionType == 'static') {
				element.parent().css('position', 'relative');
			}
			element.css(cssProp);
		});

		return this;
	};

	var currentThumb = $('#sidebar_column li.current a'),
		currentId = currentThumb.attr('href').replace(/^.*[\#\?]id=/, ''),
		currentItem = $('#portfolio_content .current_item').attr('id').replace(/^image_/, ''),
		thumbsSelector = '#sidebar_column li a',
		leftArrow = $('#portfolio_left a'),
		rightArrow = $('#portfolio_right a'),
		arrowSelector = '#portfolio_view a',
		thumbs = $(thumbsSelector),
		caches = {},
		previousThumb, previousItem, nextThumb, nextItem;

	caches[currentId] = {
		content: $('#portfolio_content ul').html(),
		description: $('#portfolio_description').html()
	};

	$(arrowSelector + ', ' + thumbsSelector).each(function(i, link) {
		link = $(link);
		link.attr('href', link.attr('href').replace('?', '#'));
	});

	var setArrows = function() {
		currentThumb = $('#sidebar_column li.current a');

		var currentThumbIndex = thumbs.index(currentThumb);

		currentId = currentThumb.attr('href').replace(/^.*[\#\?]id=/, '');
		currentItem = $('#portfolio_content .current_item').length > 0 ?
			$('#portfolio_content .current_item').attr('id').replace(/^image_/, '') : null;

		if(currentItem == null || currentItem >= parseInt(currentThumb.parents('li:first').attr('-data-image-length'), 10)) {
			nextThumb = $(thumbs[(currentThumbIndex == thumbs.length - 1 ? 0 : (currentThumbIndex + 1))]);
			nextItem = nextThumb.parents('li:first').attr('-data-image-length') > 0 ? 1 : null;
		} else {
			nextThumb = currentThumb;
			nextItem = parseInt(currentItem, 10) + 1;
		}
		if(currentItem == null || currentItem <= 1) {
			previousThumb = $(thumbs[((currentThumbIndex == 0 ? thumbs.length : currentThumbIndex) - 1)]);
			previousItem = previousThumb.parents('li:first').attr('-data-image-length') > 0 ?
				previousThumb.parents('li:first').attr('-data-image-length') : null;
		} else {
			previousThumb = currentThumb;
			previousItem = currentItem - 1;
		}

		leftArrow.attr('href', '#id=' + previousThumb.attr('href').replace(/.*id=/, '') +
			(previousItem == null ? '' : '&item=' + previousItem));
		rightArrow.attr('href', '#id=' + nextThumb.attr('href').replace(/.*id=/, '') +
			(nextItem == null ? '' : '&item=' + nextItem));
	};
	setArrows();

	var loading = false,
		selectItemCached = function(item) {
			var sameItem = false;
			$('#portfolio_content .current_item').each(function(i, currentItem) {
				if(currentItem == $('#image_' + item)[0]) {
					sameItem = true;
				}
			});
			if(sameItem) {
				// console.log('here be dragons');
				setTimeout(setArrows, 10);
				return;
			}
			$('#portfolio_content .current_item').removeClass('current_item').fadeOut(500);
			var alt = $('#image_' + item).addClass('current_item').fadeIn(500).find('img, object').attr('alt');
			$('#portfolio_piece_nav li.selected').removeClass('selected');
			if($('#portfolio_piece_nav .portfolio_item_' + item)) {
				$('#portfolio_piece_nav .portfolio_item_' + item).parents('li:first').addClass('selected');
			}
			$('#portfolio_item_description').html($.trim(alt) != '' ? (' | ' + alt) : '');
			setTimeout(setArrows, 10);
		},
		selectItem = function(thumb, item) {
			if(thumb.length > 0 && currentThumb.length > 0 && thumb[0] != currentThumb[0]) {
				currentThumb.parents('li:first').removeClass('current');
				thumb.parents('li:first').addClass('current');
				$('#portfolio_content ul').html('');
				$('#portfolio_description').html('<p>Hang Tight...</p>');
				loading = true;

				var id = thumb.attr('href').match(/id=(\d+)/)[1],
					href = '/?p=' + id,
					nav = '';

				for(var i = 1; i < parseInt(thumb.parents('li:first').attr('-data-image-length'), 10) + 1; i++) {
					nav += '<li' + (i == item ? ' class="selected"' : '') + '>' +
						'<a href="#id=' + href.replace(/^\/\?p=/, '') + '&amp;item=' + i + '" ' +
						'class="portfolio_item_' + i + '">' + i + '</a></li>';
				}
				$('#portfolio_piece_nav ul').html(nav);

				if(caches[id] !== undefined) {
					$('#portfolio_content ul').html(caches[id].content);
					$('#portfolio_content image').css({
						verticalAlign: 'middle'
					});
					$('#portfolio_description').html(caches[id].description);
					$('#portfolio_piece_nav ul .selected a').click();
					selectItemCached(item);
					loading = false;
					return;
				}

				$.get(href, function(data) {
					data = $(data);
					var images = $($.grep(data.find('*'), function(el) {
							el = $(el);
							return el.is('img') || el.is('a');
						})),
						header = data.find('h1'),
						content = '',
						description = null,
						image;

					for(var i = 1; i < images.length; i++) {
						image = $(images[i]);
						var imageWidth = image.attr('width') == 0 ?
							image[0].outerHTML.match(/width=(['"]?)(\d+)\1/)[2].toString() :
							image.attr('width');
						var imageHeight = image.attr('height') == 0 ?
							image[0].outerHTML.match(/height=(['"]?)(\d+)\1/)[2].toString() :
							image.attr('height');

						if(image.is('a')) {
							var matches = image.attr('href').match(/^https?\:\/\/(?:www\.)?vimeo.com\/(\d+)/);
							image.attr('alt', image.text());
						}

						content += '<li id="image_' + i + '"' +
							(i == item ? ' class="current_item"' : ' style="display: none"') +
							'>' +
							(image.is('img') ?
								'<img src="' + image.attr('src') + '" alt="' +
									image.attr('alt') + '" width="' + imageWidth +
									'" height="' + imageHeight + '" ' +
										(
											$('#ltIE8').length > 0 ?
												'style="margin-top: ' + (221 - Math.floor(imageHeight / 2)) + 'px;"' :
												''
										) +
									' />'
								: image.is('a') && matches ?
									'<object width="480" height="380" alt="' + image.text() + '">\
										<param name="wmode" value="transparent" />\
										<param name="bgcolor" value="transparent" />\
										<param name="allowfullscreen" value="true" />\
										<param name="allowscriptaccess" value="always" />\
										<param name="movie" \
											value="http://vimeo.com/moogaloop.swf?clip_id=' +
												matches[1] +
											'&amp;server=vimeo.com&amp;show_title=1&amp;' +
												// WRAP :P
											'show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" />\
										<embed type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always"\
											width="480" height="380" wmode="transparent" bgcolor="transparent"\
											src="http://vimeo.com/moogaloop.swf?clip_id=' + matches[1] +
												'&amp;server=vimeo.com&amp;show_title=1&amp;' +
												// WRAP :P
												'show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1"></embed>\
									</object>'
									: ''
							) +
							'</li>';
						if(i == item) {
							description = image.attr('alt');
						}
					}

					var description = (header.length > 0 ? ('<h1>' + header.html() + '</h1>') : '') +
						(description != null ?
							('<p id="portfolio_item_description">' +
								(header.length > 0 ? '&nbsp;| ' : '') +
								description + '</p>') :
							'');
					$('#portfolio_content ul').html(content);
					$('#portfolio_content image').css({
						verticalAlign: 'middle'
					});
					$('#portfolio_description').html(description);

					caches[id] = {
						content: content,
						description: description
					};

					setTimeout(setArrows, 10);
					loading = false;
				});
			} else if(item != null) {
				selectItemCached(item);
			}
		};

	leftArrow.click(function(e) {
		if(loading) {
			return false;
		}
		setTimeout(function() {
			selectItem(previousThumb, previousItem);
		}, 10);
	});

	rightArrow.click(function(e) {
		if(loading) {
			return false;
		}
		setTimeout(function() {
			selectItem(nextThumb, nextItem);
		}, 10);
	});

	thumbs.click(function(e) {
		var thumb = $(this);
		selectItem(thumb, 1);
	});

	var hashMatch = /^\#?id=(\d+)(?:&(?:amp;)?item=(\d+))?$/;

	$(document).click(function(e) {
		var target = $(e.target);
		if(target.is('a') && target.parents('#portfolio_piece_nav').length > 0) {
			var hash = target.attr('href').match(hashMatch);
			if(hash) {
				selectItem($('#sidebar_column li a[href="#id=' + hash[1] + '"]'), hash[2] || 1);
			}
		}
	});

	var hash = location.hash.match(hashMatch)
	if(hash) {
		selectItem($('#sidebar_column li a[href="#id=' + hash[1] + '"]'), hash[2] || 1);
	}

})(jQuery);