var xmlDoc;
var xmlData;
var section;

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.4.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.4
 * @date November 17, 2007
 * @category jQuery plugin
 * @copyright (c) 2007 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.lightBox = function(settings) {
		// Settings to configure the jQuery lightBox plugin how you like
		settings = jQuery.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to images
			imageLoading:			'img/b_lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'img/b_lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'img/b_lightbox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'img/b_lightbox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				'img/lightbox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			// Configuration related to keyboard navigation
			keyToClose:				'c',		// (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
			keyToPrev:				'p',		// (string) (p = previous) Letter to show the previous image
			keyToNext:				'n',		// (string) (n = next) Letter to show the next image.
			// Donīt alter these variables in any way
			imageArray:				[],
			activeImage:			0,
			grabItem:				'',
			section:				''
		},settings);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize()
		{
			var thisObjLink = $(this).attr('href');
			if (thisObjLink.indexOf('.jpg') > -1 || thisObjLink.indexOf('.png') > -1 || thisObjLink.indexOf('.gif') > -1)
			{
				_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
				return false; // Avoid the browser following the link
			}			
		}
		/**
		 * Start the jQuery lightBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
			
			
			// Call the function to create the markup structure; style some elements; assign events in some elements.
			_set_interface();
			
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Letīs see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),$(objClicked).next().html()));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),$(jQueryMatchedObj[i]).next().html()));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		
		function _set_interface() {
			// Apply the HTML markup into body tag
			$('body').append('<div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><div id="lightbox-image-details-caption"></div><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');
			
			showOverLay();
			
			// Get page scroll
			var arrPageScroll = ___getPageScroll();
			
			// Calculate top and left offset for the jquery-lightbox div object and show it
			$('#jquery-lightbox').css({
				top:	10,
				left:	arrPageScroll[0]
			}).show();
			// Assigning click events in elements to close overlay
			$('#jquery-overlay,#jquery-lightbox').click(function() {
				_finish();									
			});
			// Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
			$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
				_finish();
				return false;
			});
			// If window was resized, calculate the new overlay dimensions
			$(window).resize(function() {
									  
				showOverLay();
				
				// Get page scroll
				var arrPageScroll = ___getPageScroll();
				// Calculate top and left offset for the jquery-lightbox div object and show it
				$('#jquery-lightbox').css({
					top:	10,
					left:	arrPageScroll[0]
				});
			});
		}
		/**
		 * Prepares image exibition; doing a imageīs preloader to calculate itīs size
		 *
		 */
		function _set_image_to_view() { // show the loading
			// Show the loading
			$('#lightbox-loading').show();
			// Hide some elements
			$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
			
			
			
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
				// Perfomance an effect in the image container resizing it
				_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			}
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		/**
		 * Perfomance an effect in the image container resizing it
		 *
		 * @param integer intImageWidth The imageīs width that will be showed
		 * @param integer intImageHeight The imageīs height that will be showed
		 */
		function _resize_container_image_box(intImageWidth,intImageHeight) {
			// Get current width and height
			var intCurrentWidth = $('#lightbox-container-image-box').width();
			var intCurrentHeight = $('#lightbox-container-image-box').height();
			// Get the width and height of the selected image plus the padding
			var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the imageīs width and the left and right padding value
			var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the imageīs height and the left and right padding value
			// Diferences
			var intDiffW = intCurrentWidth - intWidth;
			var intDiffH = intCurrentHeight - intHeight;
			// Perfomance the effect
			$('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { 
				_show_image(); 
			});
			if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
				if ( $.browser.msie ) {
					___pause(250);
				} else {
					___pause(100);	
				}
			}
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) }); 
			$('#lightbox-container-image-data-box').css({ width: intImageWidth });
		};
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#lightbox-loading').hide();
			$('#lightbox-image').fadeIn(function() {
				
				_show_image_data();
				_set_navigation();
				
				$('#lightbox-image-details-caption select').click(function(){
					return false;
				});
				$('#lightbox-image-details-caption #addToCart a').click(function(){
					updateCart(true, settings.section+'_'+settings.activeImage, $(this).attr('class'));
					alert(xmlData.find('item:eq('+settings.activeImage+') title').text()+' has been added to cart');
					return false;
				});
				
				$('#addToCart select').change(function(){$(this).next().attr('class',$(this).val())});
			});
			_preload_neighbor_images();
		};
		
		function _show_image_data() {
			// Build Caption Content
			$('#lightbox-image-details-caption').html(buildCaption);
			
			$('#lightbox-container-image-data-box').slideDown('fast');
			
			// If we have a image set, display 'Image X of X'
			if ( settings.imageArray.length > 1 ) {
				$('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
			}		
		}
		
		function buildCaption()
		{
			var index = (settings.grabItem != '')?settings.grabItem:settings.activeImage;
			var selImage = xmlData.find('item:eq('+index+')');
			var selOptions = selImage.find('option');
			var nhtml = '';
			if(selImage.attr('buy') == 'yes')
			{
				nhtml += '<div id="addToCart">';
				
				if (selOptions.length > 1)
				{
					nhtml += '<select>';
					selOptions.each(function(i){
						nhtml += '<option value="'+i+'"'+((i==0)?' checked="true"':'')+'>'+$(this).text()+'</option>';
					});
					nhtml += '</select>';
				}
				
				nhtml += '<a href="#" class="0">[Add to cart]</a>';
				nhtml +='</div>';
			}
			nhtml += '<h3>'+selImage.children('title').text()+'</h3>';
			nhtml += selImage.children('content').text();
			nhtml += '<p>'+xmlDoc.find('copyright').text()+'</p>';
			return nhtml;
		}
		/**
		 * Display the button navigations
		 *
		 */
		function _set_navigation() {
			$('#lightbox-nav').show();

			// Instead to define this configuration in CSS file, we define here. And itīs need to IE. Just.
			$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
			
			// Show the prev button, if not the first image in set
			if ( settings.activeImage != 0 ) {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnPrev').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					return false;
				});
			}
			
			// Show the next button, if not the last image in set
			if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
				// Show the images button for Next buttons
				$('#lightbox-nav-btnNext').unbind().hover(function() {
					$(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
				},function() {
					$(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
				}).show().bind('click',function() {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					return false;
				});
			}
			// Enable keyboard navigation
			_enable_keyboard_navigation();
		}
		/**
		 * Enable a support to keyboard navigation
		 *
		 */
		function _enable_keyboard_navigation() {
			$(document).keydown(function(objEvent) {
				_keyboard_action(objEvent);
			});
		}
		/**
		 * Disable the support to keyboard navigation
		 *
		 */
		function _disable_keyboard_navigation() {
			$(document).unbind();
		}
		/**
		 * Perform the keyboard actions
		 *
		 */
		function _keyboard_action(objEvent) {
			// To ie
			if ( objEvent == null ) {
				keycode = event.keyCode;
				escapeKey = 27;
			// To Mozilla
			} else {
				keycode = objEvent.keyCode;
				escapeKey = objEvent.DOM_VK_ESCAPE;
			}
			// Get the key in lower case form
			key = String.fromCharCode(keycode).toLowerCase();
			// Verify the keys to close the ligthBox
			if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
				_finish();
			}
			// Verify the key to show the previous image
			if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
				// If weīre not showing the first image, call the previous
				if ( settings.activeImage != 0 ) {
					settings.activeImage = settings.activeImage - 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
			// Verify the key to show the next image
			if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
				// If weīre not showing the last image, call the next
				if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
					settings.activeImage = settings.activeImage + 1;
					_set_image_to_view();
					_disable_keyboard_navigation();
				}
			}
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		
		/**
		 / THIRD FUNCTION
		 * getPageSize() by quirksmode.com
		 *
		 * @return Array Return an array with page width, height and window width, height
		 */

		/**
		 * Remove jQuery lightBox plugin HTML markup
		 *
		 */
		function _finish() {
			$('#jquery-lightbox').remove();
			$('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').hide(); });
			$('#lightbox-image-details-caption a.buy').unbind('click');
			// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
			$('embed, object, select').css({ 'visibility' : 'visible' });
		}
		
		/**
		 / THIRD FUNCTION
		 * getPageScroll() by quirksmode.com
		 *
		 * @return Array Return an array with x,y page scroll values.
		 */
		function ___getPageScroll() {
			var xScroll, yScroll;
			if (self.pageYOffset) {
				yScroll = self.pageYOffset;
				xScroll = self.pageXOffset;
			} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
				yScroll = document.documentElement.scrollTop;
				xScroll = document.documentElement.scrollLeft;
			} else if (document.body) {// all other Explorers
				yScroll = document.body.scrollTop;
				xScroll = document.body.scrollLeft;	
			}
			arrayPageScroll = new Array(xScroll,yScroll) 
			return arrayPageScroll;
		};
		 /**
		  * Stop the code execution from a escified time in milisecond
		  *
		  */
		 function ___pause(ms) {
			var date = new Date(); 
			curDate = null;
			do { var curDate = new Date(); }
			while ( curDate - date < ms);
		 };
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery);
// Call and execute the function immediately passing the jQuery object
		
$(document).ready(function(){
	section = $('body').attr('id');
	$.ajax({
		type: "GET",
		url: "xml/master.xml",
		dataType: "xml",
		success: function(xml)
		{
			xmlDoc = $(xml);
			
			$('#footer').html($('footer', xmlDoc).text());
			
			$('#menu').html(function(){
				var nhtml = '';
				$('section', xmlDoc).each(function(i){
					var text = $(this).attr('type');
					nhtml += '<li><a href="'+text+'.html"'+(($(this).attr('type') == section)?' class="active"':'')+'>'+text+'</a></li>';
				});
				return nhtml;
			});
			
			$.ajax({
				type: "GET",
				url: "xml/"+section+".xml",
				dataType: "xml",
				success: function(data)
				{
					xmlData = $(data);
					
					$('#gallery-wide').html(function(){
						var nhtml = '';
						nhtml += '<ul>';
						xmlData.find('item').each(function(i){
							var img = $(this).children('gfx');
							
							if (img.attr('link') != '')
							{
								nhtml += '<li '+((img.attr('link').indexOf('.jpg') > -1 || img.attr('link').indexOf('.png') > -1 || img.attr('link').indexOf('.jpg') > -1)?' class="img"':'')+'><a href="'+img.attr('link')+'" target="_blank"><img src="'+img.attr('thumb')+'" alt="'+img.text()+'" /><span>'+img.text()+'</span></a></li>'
							}
							else
							{
								nhtml += '<li><img src="'+img.attr('thumb')+'" alt="'+img.text()+'" /><span>'+img.text()+'</span></li>'
							}
						});
						nhtml += '</ul>'
						return nhtml;
					});
					
					$('#gallery-wide ul li.img a').lightBox({section:section});
					$("#gallery-btn a").css("opacity",0.25).hover(function(){$(this).fadeTo("fast",0.9)},function(){$(this).fadeTo("fast",0.25)});
					galleryStuff();
				}
			});
			
			$('#cart').click(viewCart);
			
			$('#cart_no').html(setCartNo);
		}
	});
});

function setCartNo()
{
	try
	{
		if ($.cookie('cart') != null && $.cookie('cart') != '')
		{
			return $.cookie('cart').split(',').length
		}
		else
		{
			return '0';
		}
	}
	catch(e)
	{
		return '0';
	}
}

function updateCart(add,product,type,no)
{
	var delNo = -1;
	var count = 1;
	var option = (type)?type:0;
	var cart = '';
	
	if ($.cookie('cart') != null)
	{
		cart = $.cookie('cart').split(',');
		
		jQuery.each(cart,function(i,n){
			if (n.indexOf(product+'|'+option) > -1)
			{
				count = (no)?no:parseInt(n.split('-')[1].split('|')[0])+1;
				delNo = i;
			}
		});
		
		if (delNo > -1) cart.delitem(delNo);
	}
	
	if (add) 
	{
		$.cookie('cart',product+'|'+option+'-'+count+((cart !='' && $.cookie('cart') != null)?',':'')+cart, { expires: 5 });
	}
	else
	{
		$.cookie('cart',cart.join(','), { expires: 5 });
	}
	
	$('#cart_no').html(setCartNo);
}

function showOverLay()
{
	$('embed, object, select').css({ 'visibility' : 'hidden' });
	// Get page sizes
	var arrPageSizes = ___getPageSize();
	
	// Style overlay and show it
	$('#jquery-overlay').css({
		backgroundColor:	'#000',
		opacity:			0.8,
		width:				arrPageSizes[0],
		height:				arrPageSizes[1]
	}).fadeIn();
}

function hideCart() {
	$('#view-cart-wrapper').remove();
	$('#jquery-overlay').fadeOut();
	$('embed, object, select').css({ 'visibility' : 'visible' });
}

function viewCart()
{
	showOverLay();	
	$('body').append('<div id="view-cart-wrapper"><div id="view-cart"><div id="view-cart-body">'+buildCart()+'</div><div id="view-cart-close"><a href="#"><img src="img/b_lightbox-btn-close.gif" alt="Close cart" /></a></div></div></div>');
	$('#view-cart-wrapper').fadeIn();
	$('#jquery-overlay').click(hideCart);
	$('#view-cart-close img').click(hideCart);
	
	if ($('form').hasClass('shoppingCart'))
	{
		$('#cartTable td.remove a').click(removeItem);
		$('#cartTable td.quantity input').change(function(){
			var valNo = /^\s*\d+\s*$/;
			var obj = $(this);
			if (obj.val().search(valNo) != -1)
			{
				if (obj.val() == '0') obj.val('1');
				
				var value = obj.attr('class');
				
				updateCart(true,value.split('|')[0],value.split('|')[1],$(this).val());
				
				buildTotal();
			}
			return false;
		});
		$('#shipping-sel').change(buildTotal);
		buildTotal();
		
		$('form.shoppingCart button').click(function(){
			$('form#shoppingCart').submit();
			setTimeout('hideCart()',2000);
		});
	}
}

function removeItem()
{
	var value = $(this).attr('class');
	
	updateCart(false,value.split('|')[0],value.split('|')[1]);
	
	var nCount = setCartNo();
	
	if (nCount == 0) $('#view-cart-body').html('<div style="padding: 5px 0 10px 0">You have no items in your cart.</div>')
	
	$('#cart_no').html(setCartNo);
	$(this).parent().parent().remove();
	buildTotal();
	return false;
}

function buildCart()
{
	var nhtml = '';
	if (setCartNo() != '0')
	{
		var items = $.cookie('cart').split(',');
		nhtml += '<form target="_blank" action="https://www.paypal.com/cgi-bin/webscr" method="post" name="cart" id="shoppingCart" class="shoppingCart"><input type="hidden" name="cmd" value="_cart" /><input type="hidden" name="upload" value="1" /><input type="hidden" name="return" value="http://www.nthread.com/" /><input type="hidden" name="rm" value="1" /><input type="hidden" name="business" value="nanami@nthread.net" /><table id="cartTable" summary="Shopping Cart"><thead>';
		nhtml += '<tr><th /><th scope="col">Price</th><th scope="col">Product</th><th>Quantity</th><th /></tr></thead><tbody>'
		$(items).each(function(i,v){
			var itemSection = v.split('_')[0];
			$.ajax({
				async: false,
				type: "GET",
				url: "xml/"+itemSection+".xml",
				dataType: "xml",
				success: function(xmlProd)
				{
					var values = v.split('_')[1];
					var itemNo = parseInt(values.split('|')[0]);					
					var option = parseInt(values.split('|')[1].split('-')[0]);
					var quantity = parseInt(values.split('-')[1]);
					var product = $(xmlProd).find('item:eq('+itemNo+')');
					nhtml += '<tr class="'+itemSection+'"><td class="thumb"><img src="'+$('option:eq('+(option)+')', product).attr('thumb')+'" alt="" /></td><td class="price">$<span>'+product.attr('price')+'</span> (AUD)</td><td class="product"><input type="hidden" name="item_name_'+(i+1)+'" value="'+product.children('title').text()+' - '+$('option:eq('+(option)+')', product).text()+'" /><input type="hidden" name="amount_'+(i+1)+'" value="'+product.attr('price')+'" /><strong>'+product.children('title').text()+'</strong>  - '+$('option:eq('+(option)+')', product).text()+'</td><td class="quantity"><input type="text" name="quantity_'+(i+1)+'" value="'+quantity+'" class="'+itemSection+'_'+itemNo+'|'+option+'" /></td><td class="remove"><a href="#" class="'+itemSection+'_'+itemNo+'|'+option+'">remove</a><input type="hidden" class="tax" value="10" /></td></tr>';
				}
			});
		});
		nhtml += '</tbody></table>';
		nhtml += '<div class="clearit"><div id="total-price"></div>'+buildShipping()+'<div id="check-out"><button type="submit">[Check Out]</button></div></div></form>';
	}
	else
	{
		nhtml+='<div style="padding: 5px 0 10px 0">You have no items in your cart.</div>';
	}
	return nhtml;
}

function buildShipping()
{
	var nhtml = '';
	nhtml += '<div id="shipping"><label for="shipping-sel">Shipping to: <select id="shipping-sel">';
	$('to',xmlDoc).each(function(){
		var country = $(this).attr('country');
		nhtml += '<option value="'+country+'"'+(($.cookie('shipping') == country)?' selected':'')+'>'+country+'</option>';
	});
	nhtml += '</select></label><div id="shipping-note">'+$('shipping note',xmlDoc).text()+'</div></div>';
	return nhtml;
}

function buildTotal()
{
	if (setCartNo() != '0')
	{
		var quantity = 0, subtotal = 0, shipping = 0, maxItems = 0;
		var selShipping = $('#shipping-sel').val();
		var taxObj = xmlDoc.find('to[country='+selShipping+']');
		
		$('#cartTable tbody tr').each(function(){
			subtotal += parseInt($('td.price span',this).html())*parseInt($('td.quantity input',this).val());
			quantity += parseInt($('td.quantity input',this).val());
			
			jQuery.each($('option[type='+$(this).attr('class')+']',taxObj).text().split(','),function()
			{
				var range = this.split('|')[0].split('-'), start = parseInt(range[0]), end = parseInt(range[1]);
				if (quantity >= start && quantity <= end)
				{
					shipping = parseInt(this.split('|')[1]);
				}
				maxItems = (maxItems < end)?end:maxItems;
			});
		});
		
		if (quantity <= maxItems)
		{
			var items = $.cookie('cart').split(','), noitems = 0, tax = 0, total = 0;
			
			jQuery.each(items,function(i,v){
				noitems += parseInt(v.split('-')[1]);
			});
			
			total = parseInt(subtotal)+parseInt(shipping);
			tax = total/11;
			
			$('#total-price').html(function(){
				var nhtml = '';
				nhtml += '<div id="sub-total" class="clearit"><strong>Subtotal:</strong><span>$'+subtotal.toFixed(2)+'</span></div>';
				nhtml += '<div id="shipping-total" class="clearit"><strong>Postage & Handling:</strong><span>$'+shipping.toFixed(2)+'</span></div>';
				if(selShipping == 'Australia') nhtml += '<div id="tax-total" class="clearit"><strong>'+taxObj.attr('taxType')+':</strong><span>$'+tax.toFixed(2)+'</span></div>';
				nhtml += (selShipping == 'Australia')?'<input type="hidden" value="AU" name="country" />':'<input type="hidden" value="US" name="country" />';
				nhtml += '<div id="grand-total" class="clearit"><strong>Total:</strong><span>$'+total.toFixed(2)+' (AUD)</span></div>';
				nhtml += '<input type="hidden" name="currency_code" value="AUD" /><input type="hidden" name="handling_cart" value="'+shipping+'" />';
				return nhtml;
			});
			
			if(selShipping == 'Australia') 
			{
				$('#shoppingCart').find('input.tax').val('10');
			}
			else
			{
				$('#shoppingCart').find('input.tax').val('0');
			}
			
			$('#shipping').show();
			$('#check-out button').show();
			$('#total-price').css('float','right');
		}
		else
		{
			$('#total-price').html('<div id="maxMet">Sorry! I only allow a maximum of '+maxItems+' items per transaction. For quantities greater than '+maxItems+', please enquiry with me at <a href="mailto:inked@nthread.net">inked@nthread.net</a></div>').css('float','none');
						
			$('#shipping').hide();
			$('#check-out button').hide();
		}
		
		$.cookie('shipping',$('#shipping-sel').val());
	}
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.delitem = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

$.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
