(function($, window, undefined) {
	if(!$('#portfolio').length) {
		return;
	}
	var pg, item, hash, cache = {}, firstImage, tempFragment, i, children, nav,
		contentSections, contentSection,
		navItems = $('#portfolio-navigation li'),
		setHash = function(pgHash, itemHash) {
			pg = pgHash.replace(/^page=(page=)+/, 'page=');
			item = itemHash !== undefined ? itemHash.replace(/^item=(item=)+/, 'item=') : itemHash;
			hash = '#' + pg;
			if(item !== undefined) {
				hash += '&' + item;
			}
			window.location.hash = hash;
		},
		loading = function(stop) {
			if(stop === undefined) {
				$('#portfolio-loading').fadeIn(500);
			} else if(stop === false) {
				$('#portfolio-loading').fadeOut(250);
			}
		},
		populateContent = function(children, items) {
			children.filter('ul:last').hide();
			tempFragment = document.createDocumentFragment();
			nav = '';
			for(i = 0; i < children.length; i++) {
				tempFragment.appendChild(children[i]);
			}
			for(i = 0; i < items.length; i++) {
				nav += '<li' + (i == 0 ? ' class="active"' : '') + '>' +
					'<a href="?' + pg + '&amp;item=' + i + '">' + (i + 1) + '</a></li>';
			}

			$('#portfolio-content').append(tempFragment);
			contentSections = $('#portfolio-content ul');
			for(var i = 0; i < contentSections.length; i++) {
				contentSection = $(contentSections[i]);
				if(i < contentSections.length - 1) {
					contentSection.animate({ opacity: 0 }, 500, function() {
						$(this).remove();
					});
				} else {
					contentSection.fadeIn(500);
				}
			}
			$('#portfolio-navigation ul').html(nav);
			navItems = $('#portfolio-navigation li');
		},
		showItem = function(index, firstLoad) {
			index = Math.max(index, 0);

			if((item == 'item=' + index || (index == 0 && item == undefined)) && firstLoad === undefined) {
				return;
			}

			navItems.removeClass('active');
			$(navItems[index]).addClass('active');

			item = 'item=' + index;
			setHash(pg, item);

			var lastList = $('#portfolio-content ul:last');
			lastList.find('li.active').css({
				display: 'block',
				opacity: 1
			}).animate({ opacity: 0 }, 500, function() {
				$(this).css({
					display: 'none',
					opacity: ''
				}).removeClass('active');
			});
			lastList.find('li:eq(' + index + ')').css({
				opacity: 0,
				display: 'block'
			}).animate({ opacity: 1 }, 500, function() {
				$(this).css({
					opacity: ''
				}).addClass('active');
			});
		},
		onLoadAction,
		fragment = document.createDocumentFragment(),
		div = document.createElement('div'),
		tempLoader = $(div);

	fragment.appendChild(div);

	$('#portfolio-sidebar a').click(function(e) {
		e.preventDefault();
		var link = $(this),
			listItem = link.closest('li'),
			realHref = link.attr('href'),
			href = realHref.replace(/.*\?/, '');

		realHref += (/\?/.test(realHref) ? '&' : '?') + 'ajaxRequest=true';

		listItem.addClass('active').siblings('li.active').removeClass('active');

		if(pg == href && onLoadAction === undefined) {
			showItem(0);
			return;
		}

		pg = href;
		setHash(pg);
		loading();
		$.get(realHref, function(data) {
			tempLoader.html(data);
			firstImage = tempLoader.find('img:eq(0)');
			children = tempLoader.children();
			if(firstImage.length) {
				firstImage.load(function() {
					populateContent(children, tempLoader.find('li'));
				});
			} else {
				populateContent(children, tempLoader.find('li'));
			}
			if(onLoadAction !== undefined) {
				onLoadAction();
				onLoadAction = undefined;
			}
			loading(false);
		});
	});

	$('#portfolio-navigation a').live('click', function(e) {
		e.preventDefault();

		var clicked = $(this),
			index = navItems.index(clicked.closest('li')[0]);

		showItem(index);
	});

	var hashSources = [window.location.hash, window.location.search], hashSource, spl, j,
		hashObj = {}, currentHash;
	for(var x = 0; x < hashSources.length; x++) {
		hashSource = hashSources[x];

		currentHash = hashSource.replace(/^(#|\?)/, '').split('&');
		for(i = 0; i < currentHash.length; i++) {
			if(!currentHash[i].length) {
				continue;
			}
			spl = currentHash[i].split('=');
			if(spl.length > 2) {
				for(j = 2; j < spl.length; j++) {
					spl[1] += '=' + spl[j];
				}
			}

			hashObj[spl[0]] = spl[1];
		}
		if('page' in hashObj) {
			break;
		}
	}

	if(!('page' in hashObj) || !('item' in hashObj)) {
		var firstItem = $('#portfolio-sidebar a:first'),
			firstHref = firstItem.attr('href').replace(/^.*\?/, '');
		if(!('page' in hashObj)) {
			hashObj.page = firstHref.match(/(^|&)page=(.*?)(&|$)/)[2];
			pg = 'page=' + hashObj.page;
		}
		if(!('item' in hashObj)) {
			hashObj.item = 0;
		}
	}	
	pg = 'page=' + hashObj.page;
	item = 'item=' + hashObj.item;

	var currentPage = $('#portfolio-page_' + hashObj.page);
	if(!currentPage.hasClass('active')) {
		onLoadAction = function() {
			showItem(hashObj.item);
		};
		currentPage.find('a').click();
	} else if(!$(navItems[hashObj.item]).hasClass('active')) {
		showItem(hashObj.item, true);
	}
})(jQuery, this);
