var showingScrollbars = false;
var switching = false;
var loadedAbout = false;
$(function() {
	startWorking();
	setupSlider();
	$('div.imgBox img, #info').hide();
	$('#subNav div.subLinks').each(function() {
		if (! $(this).hasClass('selected')) {
			$(this).hide();
		}
	});

	setupImages($('div.portfolioGroup:first'));
	$.preloadCssImages();
	$(window).resize(function() {
		$('#portfolio').animate({'left': 0}, 500);
		$('#scrollHandle').css('left', 0);
		setupSlider();
	});

	if ($('#container').hasClass('home')) {
		setTimeout(function() {
			$('#nav').animate({'left': 27},1000);
		}, 4000);
	}
	$('#portfolio').mousewheel(function(evt, delta) {
		if (switching) return false;
		delta = delta * 10;
		var list = $(this);
		var left = parseInt(list.css('left'));
		var width = $('#container').width() - list.width();
		if (delta < 0) {
			if (width < left) {
				if (delta + left < width) delta = width - left;
				list.css('left', left + delta);
			}
		} else {
			if (0 > left) {
				if (delta + left > 0) delta = -left;
				list.css('left', left + delta);
			}
		}
		// readjust scroll handle
		var pct = left / width;
		if (pct > 1) {
			pct = 1;
		}
		$('#scrollHandle').css('left', (($('#scrollbar').width() - 10) * pct));
		return false;
	});

	$('#creativeDir, #stylist').mouseover(showSubNav);

	setupEmail();

	$('#subNav div.subLinks a').click(function() {
		// don't want it to try and add another portfolio while scrolling in a new one
		if (switching) return false;
		var $this = $(this);
		if ( ! $this.hasClass('selected')) {
			switching = true;
			startWorking();
			hideAbout();
			$('#subNav div.subLinks a').removeClass('selected');
			$this.addClass('selected');
			var url = $this.attr('href') + '?js=true';
			var prevPortfolio = $('#portfolio div.portfolioGroup');
			var prevId = '#' + prevPortfolio.attr('id');
			var prevWidth = prevPortfolio.width();
			var prevOffset = prevPortfolio.parent().position()['left'];
			$.get(url, function(data) {
				var html = $(data);
				$('#portfolio').append(html);
				setupPortfolioWidth();
				setupImages(html);
				hideInfo();
				var newLeft = -prevWidth;
				var animTime = prevWidth + prevOffset;
				$('#portfolio').animate({'left': newLeft}, animTime, function() {
					swapInfo(html.attr('_title'), html.children('div.comments').html());
					$(prevId).remove();
					$('#portfolio').css('left', 0);
					setupPortfolioWidth();
					resetScroll();
					switching = false;
				});
				showHeaderFooter();
			});
			var ga = _gat._getTracker('UA-18083126-2');
			ga._trackPageview($this.attr('href'));
		}
		return false;
	});
	$('#returnScroll').click(function() {
		if ( ! switching) {
			var portfolio = $('#portfolio');
			var animTime = -portfolio.position()['left'];
			portfolio.animate({'left': 0}, animTime);
			resetScroll();
		}
		return false;
	});
	$('#infoDetails').hide();
	$('#infoExpander').click(function() {
		if ($(this).hasClass('show')) {
			hideInfo();
		} else {
			$(this).addClass('show');
			$('#infoDetails').slideDown(500);
		}
		return false;
	});
	$('#infoTitle').click(function() {
		$('#infoExpander').trigger('click');
	});

	$('#about').click(function() {
		if ($('#aboutContainer').hasClass('showing')) {
			hideAbout();
			return false;
		}
		if (!loadedAbout) {
			$.get($(this).attr('href') + '?js=true', function(data) {
				var html = $(data);
				$('#aboutText').html(html.html());
				showAbout();
			});
			loadedAbout = true;
		} else {
			showAbout();
		}
		return false;
	});
	$('#aboutContainer').click(hideAbout);
	var musique = $('#musiqueInfo');
	musique.attr({'_showing': 'false', '_height': musique.height()});
	$('#musicPlayer').mouseover(function() {
		var $this = $('#musiqueInfo');
		clearTimeout($this.attr('_timer'));
		if ($this.attr('_showing') == 'false') {
			$this.stop().animate({'opacity': 1, 'height': $this.attr('_height')}, 500).attr('_showing', 'true');
		}
	}).mouseout(function() {
		var $this = $('#musiqueInfo');
		if ($this.attr('_showing') == 'true') {
			$this.stop().animate({'opacity': 0, 'height': 0}, 500).attr('_showing', 'false');
		}
	});
	musique.height(0).css('opacity', 0);
});

function showSubNav() {
	var navItem = this;
	$('#creativeDir, #stylist, #about').each(function() {
		if (this.id == navItem.id && ! $(this).hasClass('selected')) {
			// need to show the navigation
			$(this).addClass('selected');
			var length = parseInt($('#' + this.id + 'Line').attr('_length'));
			var height = parseInt($('#' + this.id + 'Line').attr('_height'));
			$('#' + this.id + 'Line').css('display', 'block').animate({'width': length}, (length / 3) * 10,
				function() {
					$(this).animate({'height': height}, (height / 2) * 10, function() {
						$('#' + navItem.id + 'Sub').slideDown(300);
					});
				}
			);

		} else if (this.id != navItem.id && $(this).hasClass('selected')) {
			// need to hide the navigation
			$(this).removeClass('selected');
			var length = parseInt($('#' + this.id + 'Line').attr('_length'));
			var height = parseInt($('#' + this.id + 'Line').attr('_height'));
			$('#' + this.id + 'Sub').fadeOut(300);
			$('#' + this.id + 'Line').animate({'height': 0}, (height / 2) * 10, function() {
				$(this).animate({'width': 0}, (length / 3) * 10, function() {
					$(this).css('display', 'none');
				});
			});
		}
	});
}

function setupEmail() {
	// Email obfuscator script 2.1 by Tim Williams, University of Arizona
	// Random encryption key feature by Andrew Moulden, Site Engineering Ltd
	// This code is freeware provided these four comment lines remain intact
	// A wizard to generate this code is at http://www.jottings.com/obfuscator/
	coded = "ZU0Ngxamxa0xh9@SKUgO.mxK"
	key = "PCR5ibdtuO8kvrXVWmfUojF2ABwLgqp9En4Qsh3IeKZMxG7lTJy1S6zcDaHY0N"
	shift=coded.length
	link=""
	for (i=0; i<coded.length; i++) {
		if (key.indexOf(coded.charAt(i))==-1) {
			ltr = coded.charAt(i)
			link += (ltr)
		} else {
			ltr = (key.indexOf(coded.charAt(i))-shift+key.length) % key.length
			link += (key.charAt(ltr))
		}
	}
	$('#email').attr('href', 'mailto:' + link);
}

function setupSlider() {
	// make sure if the functionality exists currently it is removed first
	$('#scrollHandle').draggable('destroy');

	$('#scrollHandle').draggable({axis: 'x', containment: '#scrollbar', drag: function(event, ui) {
		var containerWidth = $('#container').width();
		var scrollWidth = $('#scrollbar').width() - 10;
		var pWidth = $('#portfolio div.portfolioGroup').width();
		var pct = ($(this).position()['left'] - 25) / scrollWidth;
		$('#portfolio').css('left', -((pWidth - containerWidth) * pct));
	}});
}

function setupPortfolioWidth() {
	var portfolioWidth = 0;
	$('#portfolio div.imgBox').each(function() {
		portfolioWidth += $(this).width();
	});
	$('#portfolio').width(portfolioWidth);

}

function setupImages($group, callback) {
	var loadCount = 0;
	var id = '#' + $group.attr('id');
	$(id + ' div.imgBox').each(function() {
		if ( ! $(this).hasClass('leadBox')) {
			loadCount++;
			var wrapper = $(this);

			var imgName = baseUrl + 'images/portfolios/' + wrapper.attr('_img');
			var img = new Image();
			$(img).load(function() {
				if (id == '#homePortfolio') {
					if (this.width > 491) {
						// need to stretch out the container of the image first
						wrapper.animate({'width': this.width}, 300, function() {
							wrapper.children('img').hide().attr('src', $(img).attr('src')).fadeIn(300);
							setupPortfolioWidth();
						});
					} else {
						wrapper.children('img').hide().attr('src', $(this).attr('src')).fadeIn(300);
						setupPortfolioWidth();
					}
				} else {
					var newWidth = parseInt(img.width * 0.8688);
					wrapper.animate({'width': newWidth}, 300, function() {
						wrapper.children('img').hide().attr({
							'width': newWidth,
							'height': 543,
							'src': $(img).attr('src')
						}).fadeIn(300);
						setupPortfolioWidth();
					});
				}
				loadCount--;
				if (loadCount <= 0) {
					finishedWorking();
					if (callback != undefined) {
						callback();
					}
				}
			}).attr('src', imgName);
		}
	});
	$(id + ' img').bind('contextmenu', function(e){
		alert('All images are copyrighted.  Duplication is prohibited.');
		return false;
	});
}

function startWorking() {
	$('#loader').css('display', 'block');
}
function finishedWorking() {
	$('#loader').css('display', 'none');
}

function showHeaderFooter() {
	if (! showingScrollbars) {
		showingScrollbars = true;
		$('#header, #footer').css('left', $('#container').width() + 491)
			.animate({'left': 0}, $('#container').width() + 491);
		$('#headerLeadin, #footerLeadin').css('left', $('#container').width())
			.animate({'left': -491}, $('#container').width() + 491);
	}
}
function resetScroll() {
	$('#scrollHandle').css('left', 0);
}
function hideInfo(newText) {
	if ($('#infoExpander').hasClass('show')) {
		$('#infoExpander').removeClass('show');
		$('#infoDetails').slideUp(500);
	} else if (newText != undefined) {
		$('#infoDetails').html(newText);
	}
}
function showAbout() {
	var width = $('#container').width();
	$('#info').slideUp(500);
	$('#aboutContainer').css('left', width).animate({'left': 0}, $('#container').width()).addClass('showing');
}
function hideAbout() {
	if ($('#aboutContainer').hasClass('showing')) {
		var width = $('#container').width();
		$('#aboutContainer').animate({'left': width}, width, function() {
			$(this).css('left', '100%');
		}).removeClass('showing');
		if ($('#info').hasClass('showing')) {
			$('#info').slideDown(500);
		}
	}
}
function swapInfo(title, text) {
	document.title = title + ' - Fashion Consort';
	$('#info').slideUp(500, function() {
		$('#infoTitle').html(title);
		$('#infoDetails').html(text);
		$('#info').slideDown(500);
	}).addClass('showing');
}

function refreshImageList() {
	var imageList = [];
	$('#portfolio div.portfolioGroup:first div.imgBox').each(function() {
		if (! $(this).hasClass('leadBox')) {
			imageList.push(baseUrl + 'images/portfolios/' + $(this).attr('_img'));
		}
	});
	return imageList;
}