$(document).ready(function(){
	addToCart.configure()
})
var addToCart = {
	configure: function () {
		$('.add_to_cart_button').click( function ( e ) {
			e.preventDefault()
			addToCart.addToCart( this.id )
		})
		$('.reprint_button').click( function ( e ) {
			e.preventDefault()
			addToCart.requestReprint( this.id )
		})
	},
	addToCart: function ( id ) {
		idParts = id.split('_')
		//if ( console ) console.log( '/cart/add_to_cart/product:' + idParts[1] + '/size:' + idParts[2] )
		$.getJSON( '/cart/add_to_cart/product:' + idParts[1] + '/size:' + idParts[2], function ( json ) {
			var flashHeader = addToCart.findSwf('flashHeader')
			if ( flashHeader ) {
				flashHeader.SetVariable( 'cartItems', json.totalQuantity + ( json.totalQuantity > 1 ? ' items' : ' item' ) )
				flashHeader.SetVariable( 'cartValue', '@ R' + json.totalValue )
			}
			addToCart.displayMessage( json.quantityAdded == 1 
														? 'Your Tshirt has been added to your shopping cart.<br/>'
														  + 'You have 60 minutes to pay for this Tshirt or it will be removed from your cart.<br/>'
														  + 'To see your purchases or check out at any time, simply click the shopping cart at the top right of the screen.'
														: 'We\'re sorry, we\'ve just sold out of that item! If you like, you can request a reprint below.' )
			if ( json.stockDepleted ) {
				var sizeID = id.split('_')[2]
				$('#' + id).replaceWith( "<a href='#' class='reprint_button' id='reprint_" + id + "'><img src='/img/icons/reprint_size_" + sizeID
																 + ".png' width='70' height='56' alt='Request Reprint' title='Request Reprint' /></a>" )
			}
		})
	},
	requestReprint: function ( id ) {
		idParts = id.split('_')
		$.getJSON( '/cart/request_reprint/product:' + idParts[1] + '/size:' + idParts[2], function ( json ) {
			addToCart.displayMessage( 'We\'ve taken note of your request. We\'ll let you know when it\'s available!' )
		})
	},
	displayMessage: function ( message ) {
		scroll(0,0)
		if ( $('#message').length > 0 ) {
			$('#message').slideUp('fast', function () {
				$('#message').html( message + "<br/><div>(click to hide)</div>" )
				$('#message').slideDown('fast')
			})
		} else {
			$('#content').prepend("<div id='message'>" + message + "<br/><div>(click to hide)</div></div>")
			$('#message').hide()
			$('#message').click( function () { 
				$(this).slideUp('fast')
			})
			$('#message').slideDown('fast')
		}
	},
	findSwf: function( id ){
		if ( window.document[id] ) return window.document[id]
		if ( !$.browser.msi ) {
			if ( document.embeds && document.embeds[id] ) return document.embeds[id]
		} else {
			return $('#'+id)[0]
		}
	}
}