(function($) {
	$(document).ready(function($)
	{
		var cart = $('#minicart').addClass('minicart'), shipstate = $('#shipstate'), promocode = $('#promocode'), cartlink = $('#minicart-anchor');
		var linkstats = $.extend(cartlink.offset(), { width: cartlink.width() }, { height: cartlink.height() });
		var cartstats = { left: linkstats.left - 427, top: linkstats.top + 23, width: cart.width(), height: cart.height() };
		var carthover, over = false, hasfocus = false, lastedit = [null, '', 0], vocitems;

		var closecart = function()
		{	//close cart and cancel timer
			clearTimeout(carthover);

			if (cart.is(':visible'))
			{	//dont blink the shrunken cart
				$('tr.alertrow, tr.warnrow', cart).removeClass('alertrow warnrow');
				cartstats.top = linkstats.top + 23;//restore original position

				//hide contents, animate cart to thingy, then hide
				cart.children().css('visibility', 'hidden');
				cart.animate(linkstats, 'fast', function()
				{
					cart.hide();
				});
			}
		};
		var hovon = function()
		{	//show cart and cancel timer
			var scroll = $(document).scrollTop();
			clearTimeout(carthover);
			over = true;

			if (scroll > cartstats.top)
			{	//move to where you scrolled if its past the top
				cartstats.top = scroll;
			}
			cart.show().animate(cartstats, 'fast', function()
			{
				cart.css('height', 'auto');
				cartstats.height = cart.height();
				cart.children().css('visibility', 'visible');
			});
		};
		var hovoff = function()
		{	//start timer to close cart, if no inputs have focus
			over = false;

			if (!hasfocus)
			{
				carthover = setTimeout(function()
				{
					closecart();
				}, 5000);//close after 5 seconds
			}
		};
		var inpbtn = function()
		{	//show the update button when the quantity inputs are changed
			var self = $(this);

			if (lastedit[1] != self.attr('name'))
			{	//undo previous edit if mind changed
				if (lastedit[0]) lastedit[0].val(lastedit[2]).parent().children('button').hide();
				lastedit = [self, self.attr('name'), self.val()];
			}

			self.parent().children('button').show();
		};
		var hilite = function()
		{	//select the input for easy changing
			hasfocus = true;
			this.select();
		};
		var tryclose = function()
		{	//only fire the close if not actually over
			hasfocus = false;
			if (!over) hovoff();
		};
		var rebuild = function(data)
		{
			vocitems = '';
			var baditems = '';
			$('#minicart-count, #minicart-anchor span').text(data.stats.count);

			if (data.stats.count == '0')
			{
				$('#minicart-full').hide();
				$('#minicart-empty').show();
			}
			else
			{
				$('#minicart-empty').hide();
				$('#minicart-full').show();
				var alltrs = $('#minicart-content tr[class!=heading]');
				var insert = $('#minicart-content tr[class=heading]');
				var copy = $(alltrs[0]).remove().removeClass();
				$('td.icon input', copy).attr('src', OLFS.assets + '/tmpl_images/icons/mini_cart_minus.gif');
				$('ul.minicart-summary li.left p.tiny').hide();
				$('td.qty button', copy).hide();
				alltrs.not(copy).remove();
				var alt = false, temp;

				$.each(data.items, function(prodid, product)
				{
					var newtr = copy.clone().addClass( (alt = !alt) ? 'odd' : 'even' ), flags = '';
					var title = ( product.mfgname ? product.mfgname + ': ' : '' ) + product.name;

					$.each(product.flags, function()
					{
						$('#minicart-note-' + this).show();
						flags += this;
					});
					if (product.badvoc)
					{	//mark the 
						newtr.addClass('warnrow');
						baditems += '<li>' + title + '</li>';
						vocitems += 'cart_pid[' + prodid + ']=0&';
					}

					if (product.changed) newtr.addClass('alertrow');
					$('td.icon input', newtr).attr({ name: 'cart_pid[' + prodid + ']', rel: product.name });
					$('td.qty input', newtr).attr({ name: 'cart_pid[' + prodid + ']', value: product.quantity }).focus(hilite).blur(tryclose); //rebind some events
					$('td.text a', newtr).attr('href', '/store/product/?id=' + prodid).text(title);
					$('td.text p', newtr).text(( flags ? 'Notes: ' + flags + ', ' : '' ) + 'SKU: ' + product.sku);
					$('td.total', newtr).text('$' + product.cleantotal);
					newtr.insertAfter(insert);
					insert = newtr;
				});

				if (data.stats.minship) $('#minicart-note-MS').show();
				$('#minicart-plural').toggle(data.stats.count != '1');
				$('#minicart-shipstate strong').text(data.stats.shipstate);
				$('#minicart-shipstate a').attr('href', '/?pid=10001&mode=changeSS&state=' + data.stats.shipstate);
				$('#minicart-promocode span').html( data.stats.promocode ? '<strong>' + data.stats.promocode + '</strong>' : 'None' );
				if (data.stats.promodesc) $('#minicart-promodesc').text(data.stats.promodesc).show();
				$('#minicart-subtotal strong').text('$' + data.stats.subtotal);
				$('#minicart-weight strong').text(data.stats.weight + ' lb');
				temp = $('#minicart-shipping');

				if (data.stats.shipping)
				{
					$('span', temp).text('$' + data.stats.shiprate);
					$('strong', temp).text('$' + data.stats.shipping);
					temp.show();
				}
				else temp.hide();
				temp = $('#minicart-flamable');

				if (data.stats.flamfee)
				{
					$('span', temp).text('$' + data.stats.flamrate);
					$('strong', temp).text('$' + data.stats.flamfee);
					temp.show();
				}
				else temp.hide();
				temp = $('#minicart-discount');

				if (data.stats.discount)
				{
					$('strong', temp).text('-$' + data.stats.discount);
					temp.show();
				}
				else temp.hide();
				temp = $('#minicart-taxes');

				if (data.stats.tax)
				{
					$('span', temp).text(data.stats.taxrate + '%');
					$('strong', temp).text('$' + data.stats.tax);
					temp.show();
				}
				else temp.hide();
				$('#minicart-total span').text('$' + data.stats.total);
			}

			return baditems;
		};
		var process = function(data, stayopen)
		{
			var baditems = rebuild(data);
			OLFS.addtocart();//next!

			if (data.stats.error)
			{
				switch (data.stats.error)
				{
					case 'shipstate':
						shipstate.dialog('open');
						break;
					case 'vocstate':
						$('span', vocstate).text(OLFS.statepick);
						$('ul.voc-products', vocstate).html(baditems);
						vocstate.dialog('open');
						break;
					case 'vocitem':
						$('span', vocitem).text(OLFS.statepick);
						vocitem.dialog('open');
						break;
				}
			}
			else
			{
				sack.get = {};

				if (!stayopen || stayopen == 'success')
				{	//supposed to always be success..
					hovon();
					hovoff();
				}
			}
		};

		//set up minicart to appear by the cart link when you hover over it
		cart.hide().appendTo('body').css(linkstats).hover(hovon, hovoff);

		cartlink.hover(hovon, hovoff).click(function(e)
		{	//dont allow clicking when empty cart
			if ($('span', cartlink).text() == '0') e.preventDefault();
		});


		$(document).click(function(e)
		{	//close cart when clicking on document
			if (!$(e.target).closest('#minicart, div.ui-dialog, #minicart-anchor').length)
			{	//except in cart or confirmation message
				closecart();
			}
		});
		cart.find("a:contains('continue')").click(function(e)
		{	//X link in the corner closes the cart
			e.preventDefault();
			closecart();
		});

		$('#minicart-shipstate a').click(function(e)
		{	//set up the change link for shipstate
			closecart();
			e.preventDefault();
			shipstate.dialog('open');
		});

		//set up the shipstate dialog
		shipstate.hide().dialog({
			title: 'Please Enter Your Shipping State',
			autoOpen: false,
			modal: true,
			width: 400,

			buttons: {
				Update: function()
				{
					OLFS.statepick = $('option:selected', shipstate).text();
					sack.put(shipstate);
					sack.get.pid = 10001;
					$.getJSON(OLFS.jsonurl + '/?jsonp=?', sack.get, process);
					shipstate.dialog('close');
				}
			}
		});

		var subpro = function()
		{
			sack.get = {};
			sack.put(promocode);
			sack.get.pid = 10001;
			$.getJSON(OLFS.jsonurl + '/?jsonp=?', sack.get, process);
			promocode.dialog('close');
		};

		$('#minicart-promocode a:first').click(function(e)
		{	//set up the change link for promocode
			closecart();
			e.preventDefault();
			promocode.dialog('open');
		});

		$('input', promocode).keyup(function(e)
		{	//enter key to submit the promocode
			if (e.which == 13)
			{
				subpro();
			}
		});

		//set up the promocode dialog
		promocode.hide().dialog({
			autoOpen: false,
			modal: true,
			width: 400,

			buttons: {
				Submit: subpro
			}
		});

		var vocstate = $('#vocstate'), vocitem = $('#vocitem'), dropitem = $('#dropitem');

		vocstate.hide().dialog({
			autoOpen: false,
			modal: true,
			width: 400,

			buttons: {
				'Remove Items': function()
				{
					$.getJSON(OLFS.jsonurl + '/?jsonp=?', vocitems + $.param(sack.get), process);
					vocstate.dialog('close');
				},
				'Change State': function()
				{
					vocstate.dialog('close');
					shipstate.dialog('open');
				}
			},

			open: function()
			{
				vocstate.parent().children('div.ui-dialog-titlebar').addClass('ui-state-error');
			}
		});

		vocitem.hide().dialog({
			autoOpen: false,
			modal: true,
			width: 400,

			buttons: {
				'Never Mind': function()
				{
					vocitem.dialog('close');
				},
				'Change State': function()
				{
					vocitem.dialog('close');
					shipstate.dialog('open');
				}
			},

			open: function()
			{
				vocitem.parent().children('div.ui-dialog-titlebar').addClass('ui-state-error');
			}
		});

		dropitem.hide().dialog({
			autoOpen: false,
			//modal: true,
			width: 400,
			zIndex: 1001,
			position: [cartstats.left + 50, cartstats.top + 50],

			open: function()
			{
				hasfocus = true;
			},

			close: function()
			{
				hasfocus = false;
			}
		});

		var update = function(prodid, quantity, obj)
		{
			obj.attr('src', OLFS.assets + '/tmpl_images/icons/wait.gif');

			$.getJSON(OLFS.jsonurl + '/?jsonp=?', prodid + '=' + quantity + '&pid=10001', function(data)
			{
				process(data, true);
			});
		};

		$('#minicart td.icon input').live('click', function(e)
		{	//set up the cancel icons next to each line item
			e.preventDefault();
			var self = $(this);
			$('span', dropitem).text(self.attr('rel'));

			dropitem.dialog('option', 'buttons', {
				No: function()
				{
					dropitem.dialog('close');
				},
				Yes: function()
				{
					dropitem.dialog('close');
					update(self.attr('name'), 0, self);
				}
			});

			dropitem.dialog('open');
		});

		$('#minicart td.qty input').live('keyup', inpbtn).live('keydown', inpbtn).focus(hilite).blur(tryclose);

		$('#minicart td.qty button').hide().live('click', function(e)
		{	//read and standardize the quantity inputs
			e.preventDefault();
			lastedit = [null, '', 0];
			var self = $(this), parent = self.parent(), inp = parent.children('input');
			var productid = inp.attr('name'), quantity = parseInt(inp.attr('value'), 10);

			if (isNaN(quantity))
			{
				quantity = 0;
			}

			inp.attr('value', quantity);
			update(productid, quantity, $('td.icon input', parent.parent()));
			self.hide();
		});

		OLFS.sendtocart = function(add, qty) { $.getJSON(OLFS.jsonurl + '/?jsonp=?', (sack.get = { pid: 10001, cart_add: add, qty: qty }), process); };

	});


})(jQuery);
