$(function()
{
	$.fn.itemActionFunctions = $.fn.itemActions;

	// Printing
	$.fn.itemActionFunctions.printThis = function(obj)
	{
		var print_item = obj.clone();
		var title = $('.item-title').clone();

		title
		.removeClass('item-title')
		.addClass('monograph-title');

		print_item
		.prepend(title);

		var s = '<html><head>';
		s += '<title>' + $(title).find('span:first').html() + '</title>';
		s += '<style type="text/css">';
		s += 'body{font-family: Verdana, Arial, sans-serif;}';
		s += '.monograph-title{font-weight: bold; font-size: 16px;}';
		s += '.monograph-text{font-size: 11px;}';
		s += '.article-figure-right{float: right; margin-left: 10px;}';
		s += '.article-figure-left{float: left; margin-right: 10px;}';
		s += '</style>';
		s += '<base href="'+ baseUri +'" />';
		s += '</head><body>';
		var e = '</body></html>';

		win = window.open();
		self.focus();
		win.document.open();
		win.document.write(s + print_item.html() + e);
		win.document.close();
		win.print();
		win.close();
		this.focus();
	}

	$.fn.itemActionFunctions.priceRange = function()
	{
		var itemtype = $('#get-price').html();
		var itemtype2 = $('#get-price2').html();
		var itemtitle = $('.item-title').find('span:first').html();

		if( $('.item').find('img[id!=loading-image]').length )
			var itemid = $('.item').find('img[id!=loading-image]').attr('id');
		else
			var itemid = parseInt($('#animation-id').html());

		var preprice = 'true';

		function handleData(data, status)
		{
			$('.price-range')
			.html(data);
		}

		function handleError(XHR, error, except)
		{
			if( error == 'timeout' )
			{
				alert('Oops, there was an error while\nrequesting the item\'s price range.\nPlease reload this page to try again.');
			}
			else
			{
				alert(error + ' : ' + except);
			}
		}

		function handleComplete(XHR, status)
		{
			//alert('Completed: ' + status);
		}

		function handleFilter(data, type)
		{
			return data;
		}

		if( itemtype != '' && itemtype != '2' && itemtype2 != '' && itemtype2 != '2' )
		{
			$.ajax(
			{
				type		:	'GET',
				url			:	$.fn.itemActionFunctions.defaults.getpriceDataSrc,
				dataType	: 	'html',
				data		:	({item_id: itemid, item_type: itemtype, item_title: itemtitle, pre_price: preprice}),
				success		:	handleData,
				cache		:	true,
				async		:	true,
				error		:	handleError,
				complete	:	handleComplete,
				dataFilter	:	handleFilter,
				timeout		:	60000
			});
		}
		else
		{
			$('.price-range')
			.remove();
		}
	}
	//priceRange();

	$.fn.itemActionFunctions.cart = function(obj)
	{
		handleCart(obj);
	}

	$.fn.itemActionFunctions.collection = function(obj)
	{
		handleCollection(obj);
	}

	$.fn.itemActionFunctions.removeInlineZoom = function()
	{
		$('#zoomContainer')
		.fadeOut('slow', function()
		{
			$(this).remove();
		});

		$('#instruct')
		.fadeOut('fast', function()
		{
			$(this).remove();
			$.fn.itemActionFunctions.action.enable();
		});
	}

	$.fn.itemActionFunctions.inlineZoom = function()
	{
		$($.fn.itemActionFunctions.defaults.loadingImage)
			.attr('src', $.fn.itemActionFunctions.options.path_to_icons + $.fn.itemActionFunctions.defaults.loading_image)
			.attr('id', 'loading-image');

		$('.padder').append('<div id="instruct"></div>').append('<div class="clearer"></div>');

		$("#instruct")
		.bind("ajaxSend", function(){
			$(this)
			.hide()
			.css({
				padding: '1%',
				border: '0.1em solid #214b01',
				background: '#e0fccc',
				fontSize: '11px',
				width: '97.8%',
				textAlign: 'center',
				marginBottom: '5px',
				color: '#214b01',
				fontWeight: 'bold',
				display: 'none',
				float: 'left'
			})
			.html('<br>Please wait while the image is generated. This may take up to 1 minute.')
			.fadeIn('slow');
		})
		.bind("ajaxComplete", function(){
			$(this)
			.html('<div class="loading-complete">Image Generated!</div>...Initializing Magnifier. Please wait!');

			$('.loading-complete')
				.css({
				fontSize: '1.8em',
				color: 'red'
			});
			if( $('#zoomContainer').length )
			{
				$('#instruct')
				.html('Move your mouse over the image to see a magnified section!<br><a href="javascript: void(0);" rel="stop">click here to stop magnifying this image</a>');

				$('a[rel=stop]')
				.bind('click', function()
				{
					$('a[rel=magnify]')
					.trigger('click');
				});
			}
		})
		.fadeOut(4000);

		// generate the zoom image
		var this_item_img = $('.item').find('img[rel=display]');
		this_item_img.css({position: 'relative'});
		var item_title = $('#item-title').html();
		var item_id = this_item_img.attr('id');
		var item_type = $('#get-price').html();
		var q = 'title=' + item_title + '&id=' + item_id + '&snt=true';
		var h = parseInt(this_item_img.attr('height'));
		var w = parseInt(this_item_img.attr('width'));
		var left = parseInt(this_item_img.position().left);

		var itemContainerWidth =  parseInt($('.item').width());
		var itemWidth = parseInt(this_item_img.attr('width'));
		var left = (itemContainerWidth - itemWidth - 2)/2;

		if( /MSIE (6\.\d+);/.test(navigator.userAgent) )
		{
			var top = parseInt(this_item_img.position().top) - 6;
		}
		else if( /MSIE (7\.\d+);/.test(navigator.userAgent) )
		{
			var top = parseInt(this_item_img.position().top) - 0;
		}
		else if( /MSIE (8\.\d+);/.test(navigator.userAgent) )
		{
			var top = parseInt(this_item_img.position().top);
		}
		else
		{
			var top = parseInt(this_item_img.position().top);
		}

		var inlineZoomDataSrc = 'ajax/inline_zoom.php';

		function handleData(data, status)
		{
			if( !$('#zoomContainer').length )
			{
				var wp = $('#zoomContainer').parent().width();
				var wz = $('#zoomContainer').width();
				var zoomImage = new Image();

				$(zoomImage)
				.css({display: 'none'})
				.load(function()
				{
					$('.item')
					.append('<div id="zoomContainer"></div>');

					$('#zoomContainer')
					.css({
						position: 'absolute',
						zIndex: 1500,
						width: w + 'px',
						height: h  + 'px',
						left: left  + 'px',
						top: top  + 'px'
					}).
					append(this);

					$(this)
					.css({
						display: 'block',
						position: 'absolute',
						left: (wp-wz) + 'px',
						top: top  + 'px'
					})
					.magnify();

					$('#instruct')
					.html('Move your mouse over the image to see a magnified section!<br><a href="javascript: void(0);" rel="stop">click here to stop magnifying this image</a>');

					$('a[rel=stop]')
					.bind('click', function()
					{
						$('a[rel=magnify]')
						.trigger('click');
					});
				})
				.attr('src', data)
				.fadeIn('slow');
			}
		}

		function handleError(XHR, error, except)
		{
			if( error == 'timeout' )
			{
				alert('Oops, there was an error while\nrequesting the magnifier.\nPlease reload this page to try again.');
			}
			else
			{
				alert(error + ' : ' + except);
			}
		}

		function handleComplete(XHR, status)
		{
			//alert('Completed: ' + status);
		}

		function handleFilter(data, type)
		{
			return data;
		}

		if( !$('#zoomContainer').length )
		{
			$.ajax(
			{
				type		:	'GET',
				url			:	inlineZoomDataSrc,
				dataType	: 	'html',
				data		:	({title: item_title, id: item_id, itemtype: item_type, snt: 'true'}),
				success		:	handleData,
				cache		:	true,
				async		:	true,
				error		:	handleError,
				complete	:	handleComplete,
				dataFilter	:	handleFilter,
				timeout		:	60000
			});
		}
	}

	$.fn.itemActionFunctions.swap_item = function(obj, stat)
	{
		function getImage()
		{
			//alert(stat);
			var displayedItemUrl = $('.item').find('img:last').attr('src');
			var displayedItemID = $('.item').find('img:last').attr('id');
			var hiddenItemUrl = $('#alt-image').attr('title');
			var hiddenItemID = $(obj).attr('id');

			if( displayedItemID > 0 && hiddenItemID > 0 )
			{
				// Fix a bug: stops image from changing when switching from
				// javascript disabled to javascript enabled and labels = off
				// from pure php script
				var manual = queryString('manual');
				if( manual != '1' )
				{
					// Preload the new Image
					// Show the loading image
					$('#labels-loading')
						.html(loadingImage.loadingImage)
						.append(' loading please wait...');

					var img = new Image();
					$(img)
						.load(function()
						{
							$('.item')
							.find('img')
								.fadeOut(1000, function()
								{
									$('.item').find('img')
										.attr('src', hiddenItemUrl)
										.attr('id',hiddenItemID)
										.fadeIn(1500, function()
										{
											$.fn.itemActionFunctions.action.enable();
										});
								});

							var vendorNumber = $('#info-image-id').html();

							if( vendorNumber.indexOf('-nl') == -1 && stat == 'off')
							{
								$('#info-image-id')
								.html(vendorNumber + '-nl');
							}
							else if( vendorNumber.indexOf('-nl') > -1 && stat == 'off')
							{
								$('#info-image-id')
									.html(vendorNumber);
							}
							else if( vendorNumber.indexOf('-nl') > -1 && stat == 'on')
							{
								$('#info-image-id')
									.html(vendorNumber.substring(0, vendorNumber.indexOf('-nl')));
							}
							else if( vendorNumber.indexOf('-nl') == -1 && stat == 'on')
							{
								$('#info-image-id')
									.html(vendorNumber);
							}

							/*$('#info-source-id')
								.html(hiddenItemID);
							*/
							$('#labels-loading')
								.html('');

							$('#alt-image')
								.attr('title', displayedItemUrl);
							$(obj)
							.attr('id', displayedItemID);

							if( stat == 'on' )
							{
								$(obj)
								.find('span:last')
								.html('Hide labels');

								$(obj).removeClass('clicked');
							}
							else
							{
								$(obj)
								.find('span:last')
								.html('Show labels');

								$(obj).addClass('clicked');
							}

							// Change the cart link as well
							var href = $('a[rel=cart]').attr('href');
							var act = queryFromString('action', href);
							str = act.split('-');
							str.pop();
							var new_act = str.join('-') +'-'+ hiddenItemID;
							var old_act = act;
							str = href.replace(old_act, new_act);

							$('a[rel=cart]')
							.attr({
								title: hiddenItemID,
								href: str
							});

						})
						.attr('src', hiddenItemUrl);
				}
			}
			else
			{
				$.fn.itemActionFunctions.action.enable();
				$('#item-loading')
					.html("The non-labeled version of this item in not available! " +  displayedItemID + ' ' + hiddenItemID);

				var position = $('#item-loading').position();
				$(window).scrollTop(position.top);
			}
		}

		// Add a delay to allow for the vars to be set
		// before any other script is executed here.
		$(obj).oneTime(250, 'delay', function()
		{
			getImage();
		});
	}

	$.fn.itemActionFunctions.getPrice = function()
	{
		var error = new Array();

		$('.get-price-section')
		.each(function()
		{
			var radio = $(this)
			.find('input:checked');

			var which = radio
				.parent()
				.parent()
				.find('label:first')
				.find('span:first')
				.html();

			if( radio.val() != null && radio.val() != '' )
			{
				$('.get-price-section-list')
				.find('select option:selected')
					.each(function()
					{
						var opt = parseInt($(this).val());

						if( opt != null && opt != 'none' && !isNaN(opt) )
						{
							error.push('false');

							var typeid = $.fn.itemActionFunctions.options.priceObject[parseInt(radio.attr('rel'))][opt].typeid;

							//alert(typeid);
							var formatid = $.fn.itemActionFunctions.options.priceObject[parseInt(radio.attr('rel'))][opt].id;

							var name = $.fn.itemActionFunctions.options.priceObject[parseInt(radio.attr('rel'))][opt].name;

							var price = $.fn.itemActionFunctions.options.priceObject[parseInt(radio.attr('rel'))][opt].price;

							var ship = $.fn.itemActionFunctions.options.priceObject[parseInt(radio.attr('rel'))][opt].ship;

							var str = '<span class="plus-one bold">' + price + '</span>';

							if( /\*\*/.test(ship) )
								str += ' <span class="minus-one"> - Shipping and handling extra. Prices subject to change without notice.</span>';

							str += '<br><span class="minus-one">call (800) 338-5954 or (770) 805-0460 or </span><span class="minus-one underline"><a href="pricing">click for more information</a></span>';

							if( $('.get-price-price').length )
								{
									$('.get-price-price').remove();
								}
							$('#dialog')
							.append('<div class="get-price-price"><p><span class="bold">Estimated Price for ' + which + ' ' + name + ':</span> <span class="italic">' + str + '</span></p></div>');
						}
						else
						{
							error.push('true');
						}
					});

				error.join('');
				//if( error.indexOf('false') == -1 )
					//alert("Please select a format for " + which);

				error.push('false');
			}
			else
			{
				error.push('true');
			}
		});
		error.join('');
		//if( error.indexOf('false') == -1 )
			//alert('Please select the type of project you wish to price');
	}

	$.fn.itemActionFunctions.handleArticleImage = function()
	{
		$('.article-image')
		.bind('click', function(e)
		{
			e.preventDefault();
			var item_id = parseInt($(this).attr('id').split('-').pop());
			var item_url = $(this).attr('href');
			$.fn.itemActions.dialog.show('View Article Image', [item_id, item_url]);
		});
	}
});
