$emailEntered = false;
var TheAffair = function()
{
	function externalLinks()
	{
		if (!document.getElementsByTagName) 
		{
			return;
		}
		var anchors = document.getElementsByTagName("a");
		for (var i=0; i<anchors.length; i++) 
		{
			var anchor = anchors[i];
			if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			{
				anchor.target = "_blank";
			}
		}
	}
	
	function attachPopups()
	{
		$("a[rel~='popup']").click(function(e) {
			e.preventDefault();
			window.open(
				$(this).attr('href'),
				'affairpop',
				'location=1,status=0,scrollbars=1,width=550,height=400'
			); 
		});
	}
	
	function attachNewsletterSignup()
	{
		$("#emailSignup #emailAddress").click(clearEmailSignup);
	}
	
	function attachTracking() {
	    $('.track').click(function() {
		track('page', {
		    'url': $(this).attr('href')
		});
	    });

	    $('.track-event').click(function() {
		var endPos = $(this).attr('rel').length;
		if ($(this).attr('rel').indexOf(' ') > 0) {
		    endPos = $(this).attr('rel').indexOf(' ');
		}
		var action = $(this).attr('rel').substring(0, endPos);

		track('event', {
		   'action': action,
		   'url': $(this).attr('href')
		});
	    });
	}

	function track(type, trackingData) {
	    if (typeof(pageTracker) == 'undefined' ||
		typeof(pageTracker._trackPageview) == 'undefined' ||
		typeof(pageTracker._trackEvent) == 'undefined') {
		    return false;
	    }

	    switch(type) {
		case 'page':
		    if (typeof(trackingData.url) != 'undefined') {
			 pageTracker._trackPageview(trackingData.url);
		    }
		    break;
		case 'event':
		    if (typeof(trackingData.url) != 'undefined' &&
			typeof(trackingData.action) != 'undefined') {
			    pageTracker._trackEvent(
				    trackingData.action,
				    trackingData.url
			    );
		    }
		    break;
	    }
	}	
	function clearEmailSignup() 
	{
		if (!$emailEntered)
		{
			$(this).get(0).value = "";
			$emailEntered = true;
		}
	}
	
	function shirtAddInit()
	{
		$('#sizes a.stockButton').click(addToCart);
		$('#cartShirts a.remove').click(removeFromCart);
		$('#notYetButton').click(showSizes);
	}
	
	function addToCart()
	{
		try
		{
			button = this;
			if ($(this).parent().find(".numRemaining").text() > 0)
			{
				$.post(this.href, function(){animateProductToCart(button);});
			}
			else
			{
				changeButtonToInactive(button);
			}
		}
		catch(err)
		{
			alert(err);
		}
		finally
		{
			return false;
		}
	}
	
	function animateProductToCart(button)
	{
		buttonParent = $(button).parent();
		numRemaining = $(buttonParent).find(".numRemaining").text();
		$(buttonParent).find(".numRemaining").text(numRemaining - 1);
		widthAll = $(buttonParent).width();
		widthSold = $(buttonParent).find(".stockSold").width()
		widthRemaining = widthAll - widthSold;
		numSold = (numRemaining * widthSold) / widthRemaining;
		numAll = (numSold * 1) + (numRemaining * 1);
		widthShirt = widthAll / numAll;
		$(buttonParent).find(".stockSold").animate({'width': widthSold + widthShirt}, 200); 
		$("#shirtHero").prepend('<div id="shirtCartAnim"></div>');
		$("#shirtCartAnim").prepend($("#shirtStatic").clone().css({'display': 'block', 'z-index': 1000}).animate({height: '0', width: '0', top: '120px', left: '-30px'}, 1000));
		
		if (numRemaining == 1)
		{
			changeButtonToInactive(button);
		}
		
		showLargeButtons();
	}
	
	function animateCart()
	{
		$('#shirtCartAnim').remove();
		if ($("#cartFull").css("display") == 'block')
		{
			$("#cartFull").fadeOut(50, function(){$("#cartFull").fadeIn(100);});
		}
		else
		{
			$("#cartFull").fadeIn('slow');
		}
	}

	function changeButtonToInactive(button)
	{
		$(button).parent().addClass("stockButtonDisabled");
		$(button).parent().parent().children(".stockStatus").children("span").text("Sold Out");
		buttonId = $(button).attr("id");
		buttonStockName = $(button).children(".stockName");		
		inactiveStockButton = '<div class="stockButton" id="' + buttonId + '"><span class="stockName">' + $(buttonStockName).html()  + '</span></div>';
		$(button).replaceWith(inactiveStockButton);
	}

	function showLargeButtons()
	{
		$('#sizes').hide();
		$('#largeButtons').show();
	}
	
	function showSizes()
	{
		$('#largeButtons').hide();
		$('#sizes').show();
		return false;
	}
	
	function removeFromCart()
	{	
		try
		{
			button = this;
			$.get(this.href + "&js=true", function(data){animateRemoveProductFromCart(button, data);}, "json");
		}
		catch(err)
		{
			alert(err);
		}
		finally
		{
			return false;
		}		
	}
	
	function animateRemoveProductFromCart(button, data)
	{
		buttonParent = $(button).parent();
		$(buttonParent).hide(600);
		
		$('#cartDiscount .price').html("-" + parseFloat(data.promotion.discount_amount).toFixed(2));
		if (data.total_quantity == 1)
		{
			$('#teeWord').html("tee");
		}
		else
		{
			$('#teeWord').html("tees");
		}
		$('#totalQuantity').html(data.total_quantity);
		$('#cartShipping .price').html(parseFloat(data.shipping_price_gbp).toFixed(2));
		$('#cartPrice .price').html(parseFloat(data.total_price_gbp).toFixed(2));
		if (data.shirt_price_gbp <= 0)
		{
			$('#checkout').hide(600);
		}
	}
	
	
	var galleryShowing;
	
	function shirtGalleryInit()
	{
		$('#shirtGalleryThumbs li a').hover(shirtGalleryHover, shirtGalleryHoverOut);
		$('#shirtGalleryThumbs li a').click(shirtGalleryShow);
		$('#shirtGallery .galleryClose').click(shirtGalleryHide);
		$('#shirtGalleryControls #galleryPrev').click(shirtGalleryPrev);
		$('#shirtGalleryControls #galleryNext').click(shirtGalleryNext);
	}
	
	function shirtGalleryHover()
	{
		$(this).children(".over").fadeTo(0, 0.5);
	}
	
	function shirtGalleryHoverOut()
	{
		$(this).children(".over").hide();
	}
	
	function shirtGalleryShow()
	{
		$(this).parent().parent().find(".black").hide();
		$(this).children(".black").fadeTo(0, 0.5);
		$("#shirtGalleryThumbs").css('border-top-color','transparent');
		$("#shirtGalleryControls").hide();
		
		$("#shirtGalleryImages li").css('top','747px');
		galleryShowing = $("#" + this.rel);
		closeSiblings = galleryShowing.parent().children().children(".galleryClose");
		closeSiblings.hide();
		closeButton = galleryShowing.children(".galleryClose");
		closeButton.hide();
		galleryShowing.animate({top: '412px'}, 500, 'swing', function(){
			$("#shirtGalleryControls").fadeIn('slow');
			closeButton.fadeIn('slow');
			$("#shirtGalleryThumbs").css({'border-top-color':'#333','margin-top':'10px'});
		});
		return false;
	}
	
	function shirtGalleryHide()
	{
		closeDiv = this;

		if ($("#shirtGalleryControls").length) {
			$(this).fadeOut('fast');
			$("#shirtGalleryControls").fadeOut('fast', function(){
				shirtGalleryPicsHide(closeDiv);
			});
		}
		else {
			shirtGalleryPicsHide(closeDiv);
		}
		return false;
	}
	
	function shirtGalleryPicsHide(closeDiv)
	{
		$("#shirtGalleryThumbs").css('border-top-color','transparent');
		$(closeDiv).parent().animate({top: '747px'}, 500, 'swing', function(){
			$("#shirtGalleryThumbs").css('border-top-color','#333');
			$("#shirtGalleryThumbs").find(".black").hide();
		});
	}

	function shirtGalleryNext()
	{
		oldCloseButton = galleryShowing.children('.galleryClose');
		oldCloseButton.hide();
		if (galleryShowing.get(0) != galleryShowing.parent().children().last().get(0))
		{
			galleryNext = galleryShowing.next();
		}
		else
		{
			galleryNext = galleryShowing.parent().children().first();
		}
		closeButton = galleryNext.children('.galleryClose');
		closeButton.hide();
		galleryNext.css({'top':'412px', 'left':'471px', 'z-index':'6'});
		galleryNext.animate({'left': '0'}, 500, 'swing', function(){
			galleryShowing.css({'top':'747px'});
			galleryShowing = galleryNext;
			galleryShowing.css({'z-index':'5'});
			closeButton.fadeIn('slow');
		});
		return false;
	}
	
	function shirtGalleryPrev()
	{
		oldCloseButton = galleryShowing.children('.galleryClose');
		oldCloseButton.hide();
		if (galleryShowing.get(0) != galleryShowing.parent().children().first().get(0))
		{
			galleryPrev = galleryShowing.prev();
		}
		else
		{
			galleryPrev = galleryShowing.parent().children().last();
		}
		closeButton = galleryPrev.children('.galleryClose');
		closeButton.hide();
		galleryPrev.css({'top':'412px', 'left':'-466px', 'z-index':'6'});
		galleryPrev.animate({'left': '0'}, 500, 'swing', function(){
			galleryShowing.css({'top':'747px'});
			galleryShowing = galleryPrev;
			galleryShowing.css({'z-index':'5'});
			closeButton.fadeIn('slow');
		});
		return false;
	}	

	return{externalLinks: externalLinks, attachPopups: attachPopups, attachNewsletterSignup: attachNewsletterSignup, attachTracking: attachTracking, shirtGalleryInit: shirtGalleryInit, shirtAddInit: shirtAddInit};
}();

$(document).ready(
	function()
	{
		TheAffair.externalLinks();
		TheAffair.attachPopups();
		TheAffair.attachNewsletterSignup();
		TheAffair.attachTracking();
		TheAffair.shirtGalleryInit();
		TheAffair.shirtAddInit();
	}
);


function embedShirtSwf(tshirtID)
{			
	var ver = "0.1";
	var flash_version = '10.0.0';
	
	var flashvars = {
		version: 			ver,
		tshirtID:			tshirtID,
		spinPath:			'/uploads/shirt/'
	};
	
	var params = {
		bgcolor: 			'#000000',
		allowfullscreen: 	'true',
		allowscriptaccess: 	'always',
		menu: 				'false',
		wmode:				'transparent'
	};
	
	var attributes = {
	};
	
	swfobject.embedSWF(
		'/_swf/spin-shell.swf',
		'shirtSpin',
		'466',
		'725',
		flash_version,
		'/_swf/flash-install.swf',
		flashvars,
		params,
		attributes,
		hideStaticHero
	);
}
		
function hideStaticHero(e)
{
	$('#shirtStatic').animate({'z-index':'1'}, 200);
}

function showSpinPrompt(e)
{
	$('#spinPrompt').fadeIn(2000, hideSpinPrompt);
}

function hideSpinPrompt(e)
{
	$('#spinPrompt').fadeOut(2000);
}

function submitCart(cartGuid)
{
	$.post('/cart/submit.php', {cart_guid: cartGuid} );
}
	

