var previous_state = 'click';
var loading_image = 'ajax-loader.gif';
var getpriceDataSrc = 'ajax/get_price.php';
var zoomDataSrc = 'ajax/zoom.php';
var priceObject = new Object();

var path_to_icons = 'skins/subscription/images/';

var loadingImage = new Image();

var share_links = {
	toggle: function()
	{
		$('.social-networks')
		.slideToggle('slow');
	}
}

var action = {
		init:		function(obj)
		{
					// Must unbind click events to ensure that 
					// each element will only ever have a
					// click event once at any given time
					var parentObj = this;
					$(obj)
					.unbind('click')
					.bind('click', function(event)
					{	
						var rel = $(obj).attr('rel');
						
						if( rel == 'labels' )
							swap_image(this, event);
						
						switch( rel)
						{
							case 'labels'	:
								return true;
								if( $(obj).hasClass('clicked'))
								{
									//alert('Has clicked');
									
									$(this)
									.find('span:last')
									.html('Hide labels');
									
									$(obj).removeClass('clicked'); window.location.hash = 'labels=on';
									swap_item(obj, 'on');
								}
								else 
								{
									$(this)
									.find('span:last')
									.html('Show labels');
									
									$(obj).addClass('clicked');	 window.location.hash = 'labels=off';
									swap_item(obj, 'off');
									
									
								}
								parentObj.disable($(this));
												break;	
							case 'magnify'	:	
								if( $(this).find('span:last').html() == 'Stop Magnifying' )
								{
									removeInlineZoom(this);
									parentObj.enable($(this));
								}
								else
								{
									inlineZoom();
									parentObj.temp_disable();
									//popWin('zoom');
								}
												break;	
							case 'price'	:
								showDialog('Get Price', '');
								parentObj.disable($(this));
												break;
												
							/*
							case 'cart'		:	
								if( !$(obj).hasClass('remove') )
									$(obj).addClass('add');
								cart(obj);
								parentObj.disable($(this));
												break;	
												
							case 'lightbox'	:	
								if( !$(obj).hasClass('remove') )
									$(obj).addClass('add');
								collection(obj);
								parentObj.disable($(this));
								
								//showDialog('Add to Lightbox', '<p>Add this item to your lightbox?</p>');
												break;	
							*/
							case 'cart'	:
												break;
							case 'lightbox'	:
												break;
							
							case 'share'	:	
								share_links.toggle();
												break;	
							case 'facebook'	:	
								fbs_click();
												break;
							case 'bebo'	:	
								bebo_click();
												break;
							case 'print'	:	
								printThis($('.item'));
												break;	
							case 'download'	:
								return true;
												break;
							case 'cite'	:	
							return true;
												break;
						}
						
						if( rel == 'linkedin' 
							|| rel == 'digg' 
							|| rel == 'email' 
							|| rel == 'stumbleupon' 
							|| rel == 'events' 
							|| rel == 'lightbox' 
							|| rel == 'cart'){
							return true;
						}
						return false;
					});
		},
		enable:	function(obj)
		{
					var parentObj = this;
				
					$('.item-actions,.module_itemsubactions')
					.find('a')
						.each(function()
						{
							if( obj != null )
							{
								if( $(this).attr('rel') != obj.attr('rel') )
									parentObj.init(this);
							}
							else
								parentObj.init(this);
						});
		},
		disable:	function(obj)
		{			
					if( $(obj).length )
						$(obj).unbind('click');
					else
					{
						$('.item-actions,.module_itemsubactions')
						.find('a')
						.each(function()
						{
							$(this).unbind('click');
						});
					}
		},
		temp_disable: function()
		{
					$('.item-actions,.module_itemsubactions')
					.find('a')
					.each(function()
					{
						if( $(this).attr('rel') != 'magnify' && $(this).attr('rel') != 'stop' && ( $(this).attr('href').indexOf('void') > -1 ||  $(this).attr('href').indexOf('javascript') > -1) )
						{	
							$(this)
							.unbind('click')
							.bind('click', function()
							{
								showDialog('Feature Temporarily Disabled', '<p style="font-weight: bold; text-align: center;">This feature is disabled while magnifying.<br><span style="font-weight: normal;">Please click "<i>Stop Magnifying</i>" to re-enable.</span></p>');
								//alert('This feature is disabled while magnifying.\nPlease click "Stop Magnifying" to enable');
								
								$('#dialog').dialog('option', 'buttons', 
								{
									'OK' : 
									function()
									{
										$('.ui-dialog').remove();
									}, 
									"Stop Magnifying" : 
									function()
									{
										removeInlineZoom('a[rel=magnify]');
										action.enable($('a[rel=magnify]'));
										$('.ui-dialog').remove();
									}
								});
							});
						}
					});
		},
		over:		function(obj)
		{
					$(obj)
					.bind('mouseover', function(event)
					{
						switch( $(this).attr('rel') )
						{
							case 'magnify'	:	break;	
							case 'cart'		:	break;	
							case 'cite'		:	break;	
							case 'lightbox'	:	break;	
							case 'share'	:	break;	
							case 'print'	:	break;	
							case 'download'	:	break;
							case 'facebook'	:	break;
							case 'twitter'	:	break;
						}
						swap_image(this, event);
					});
		},
		out:		function(obj, event)
		{
					$(obj)
					.bind('mouseout', function(event)
					{
						switch( $(this).attr('rel') )
						{
							case 'magnify'	:	break;	
							case 'cite'		:	break;	
							case 'cart'		:	break;	
							case 'lightbox'	:	break;	
							case 'share'	:	break;	
							case 'print'	:	break;	
							case 'download'	:	break;
							case 'facebook'	:	break;
							case 'twitter'	:	break;
						}
						swap_image(this, event);
					});
		}
	}
	
function printThis(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 += '<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();
}

$(function()
{
	$(loadingImage)
		.attr('src', path_to_icons + loading_image)
		.attr('id', 'loading-image');
	
});
	
function cart(obj)
{
	handleCart(obj);
}

function collection(obj)
{
	handleCollection(obj);
}
	
	
//	Check if the a link has been clicked
function isClicked()
{
	if( previous_state == 'click' )
	{
		return true;
	}
	return false;
}

function swap_image(obj, event)
{	
	switch(event.type)
	{
		case 'mouseover'	:	var state = 'over';		break;
		case 'mouseout'		:	var state = 'over';		break;
		case 'click'		:	var state = 'clicked';	break;
	}
	var img = $(obj).find('img');
	var src = img.attr('src');
	var src_array = src.split(".");		
	var index = src_array[0].indexOf('_' + state);

	if( index == -1 )
	{
		var a = src_array[0].split('_');
		if( a[2] == null )
			a[2] = '';
		else
			a[2] = '_' + a[2];
			
		if(state == 'over' && !isClicked())
			var nsrc = a[0] + '_' + a[1]+ a[2] + '_' + state + '.' + src_array[1];
		else
			var nsrc = a[0] + '_' + a[1] + '_' + state + a[2] + '.' + src_array[1];

		$(img).attr('src', nsrc);
	}
	else
	{
		if( isClicked() && state != 'clicked' )
			var osrc = src_array[0].replace(/_over/, '') + "." + src_array[1];
		else
			var osrc = src_array[0].replace('_' + state, '') + "." + src_array[1];
			
		$(img).attr('src', osrc);
	}

	previous_state = event.type;		
}

function removeInlineZoom(obj)
{
	$('#zoomContainer')
	.fadeOut('slow', function()
	{
		$(this).remove();
	});
	
	$(obj)
	.find('span:last')
	.html('Magnify');
	
	$('#instruct')
	.fadeOut('slow', function()
	{
		$(this).remove();
		action.enable($(obj));
	});
}

function inlineZoom()
{
	$(loadingImage)
		.attr('src', path_to_icons + loading_image)
		.attr('id', 'loading-image');
		
	$('.module_itemsubactions')
		.prepend('<div id="instruct"></div>');
		
	$("#instruct")
	.bind("ajaxSend", function(){
		$(this)
		.hide()
		.css({
			padding: '3px',
			border: '1px solid #214b01',
			background: '#e0fccc',
			fontSize: '1.1em',
			float: 'left',
			width: '494px',
			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>');				
				
				$('.item-actions')
				.find('a[rel=magnify]')
				.find('span:last')
				.html('Stop Magnifying');
				
				$('a[rel=stop]')
				.bind('click', function()
				{
					removeInlineZoom('a[rel=magnify]');
				});
		}
	})
	.fadeOut(4000);		
		
	// generate the zoom image
	$('.item').find('img[rel=display]').css({position: 'relative'});
	var item_title = $('.item-title').find('span:first').html();
	var item_id = $('.item').find('img[rel=display]').attr('id');
	var item_type = $('#get-price').html();
	var q = 'title=' + item_title + '&id=' + item_id + '&snt=true';
	var h = parseInt($('.item').find('img[rel=display]').attr('height'));
	var w = parseInt($('.item').find('img[rel=display]').attr('width'));
	var left = parseInt($('.item').find('img[rel=display]').position().left);
	
	var itemContainerWidth =  parseInt($('.item').width());
	var itemWidth = parseInt($('.item').find('img[rel=display]').attr('width'));
	var left = (itemContainerWidth - itemWidth - 2)/2;
	
	if( /MSIE (6\.\d+);/.test(navigator.userAgent) )
	{
		var top = parseInt($('.item').find('img[rel=display]').position().top) - 6;
	}
	else if( /MSIE (7\.\d+);/.test(navigator.userAgent) )
	{
		var top = parseInt($('.item').find('img[rel=display]').position().top) - 0;
	}
	else if( /MSIE (8\.\d+);/.test(navigator.userAgent) )
	{
		var top = parseInt($('.item').find('img[rel=display]').position().top);
	}
	else
	{
		var top = parseInt($('.item').find('img[rel=display]').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: 51000,
					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>');				
				
				$('.item-actions')
				.find('a[rel=magnify]')
				.find('span:last')
				.html('Stop Magnifying');
				
				$('a[rel=stop]')
				.bind('click', function()
				{
					removeInlineZoom('a[rel=magnify]');
				});
				
				//action.enable();
			})
			.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
		});
	}
}

function swap_item(obj, stat)
{	
	var displayedItemUrl = $('.item').find('img[rel=display]').attr('src');
	var displayedItemID = $('.item').find('img[rel=display]').attr('id');
	var hiddenItemUrl = $('#alt-image').attr('title');
	var hiddenItemID = $(obj).attr('id');
	
	//alert(displayedItemID);
	
	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)
				.append(' loading please wait...')
				.fadeIn('fast');
			
			var img = new Image();
			$(img)
				.load(function()
				{
					$('#loading-image')
						.fadeOut(1000, function()
						{
							$('.item').find('img[rel=display]')
								.attr('src', hiddenItemUrl)
								.attr('id',hiddenItemID)							
								.fadeIn(1500, function()
								{
									action.enable();
									// redundency to ensure that the loading icon
									// goes away if the item image loads before it does.
									$('#loading-image').fadeOut(1000);
								});
						});
						
					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')
						.fadeOut('slow', function()
						{
							$(this).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');	 			
					}
						
					$('.add-to-cart')
					.find('a[rel=cart]')
					.attr('title', hiddenItemID);
				})
				.attr('src', hiddenItemUrl);
		}
	}
	else
	{
		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);
	}
}

//facebook
function fbs_click(){
	u = location.href;
	t = document.title;
	window.open( 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t),  'sharer', 'toolbar=0,status=0,width=626,height=436');
	
	return false;
}

//bebo
function bebo_click() {
	u = location.href;
	t = document.title;
	window.open('http://www.bebo.com/c/share?Url=' + encodeURIComponent(u) + '&Title=' + encodeURIComponent(t) + '&MID=8974376238&TUUID=fc7850b8-964c-47bd-8a91-db1d2a5cad3c','sharer','toolbar=0,status=0,width=626,height=436');
	
	return false;
}