////////////////////////////////////////////////////////////////
// Item Functionality
////////////////////////////////////////////////////////////////

scSite.item = {};

// Holds Image Information
scSite.item.GalImage = function(src, thumb, alt)
{
	this.src = src;
	this.thumb = thumb;
	this.alt = alt;
}


//
// Floating item list (with popup thumbnails)
////////////////////////////////

scSite.floatingItemList = scSite.addComponent('floatingItemList', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			// Loop through each
			$('.sc-floating-item-list').each(function()
			{
				$('li', this).each(function()
				{
					var item = $(this);

					item.qtip(
					{
						content:
						{
							text: function()
							{
								return '<strong>'+ $('a', item).html() +'</strong><br />' +
									'<div style="text-align: center"><img alt="" src="'+ $('img', item).attr('src') +'" /></div>'
							}
						},

						position:
						{
							my: 'left top',
							at: 'right center',
							adjust:
							{
								x: -15,
								y: 0
							}
						},

						style:
						{
							classes: 'ui-tooltip-tipped'
						}
					});

				});
			});
		}
	});
});




//
// Item Thumb (Image) Gallery
////////////////////////////////

scSite.itemThumbGallery = scSite.addComponent('itemThumbGallery', function(comp)
{

	$.extend(comp,
	{
		videoPlaceHolder: '/images/icons/control-play-blue.png', 
		
		// The function called when clicking the "View Larger Image" link on an item page.
		// Even if there are multiple image galleries, largerLinkFunc can only apply to one.
		largerLinkFunc: $.noop,
		
		galAd: null,
		
		imageList: new Array(),
		
		selectFirstImage: function()
		{
			$('#productImageMain').find('.ad-thumb0').trigger('click');
		},
		
		init: function()
		{
			$('.see_larger_image_link,.productimagetext').live('click', function(ev)
			{
				if( typeof comp.largerLinkFunc == 'function' )
				{
					ev.preventDefault();
					comp.largerLinkFunc();
				}
			});
			
			// Overlays may not work as expected if there is more than one item-thumb-gallery
			$('.sc-item-thumb-gallery').each(function()
			{
				// thumbGallery
				var tGal = $(this);
				var tGalAd;
				
				var popupGallery;
				
				var hoverImg = 0;
				var imgIndex;
				var forceImgIndex = false;
				
				var imgList = [];
				
				// foreach thumbnail link, go through and add the image to the popup gallery list - DGP
				tGal.find('.ad-thumb-list a')
					.each(function()
					{
						var self = $(this);
						var sImg = self.find('img');
						
						self.data('sc-gallery-index', imgList.length);
						
						imgList.push(
							new scSite.item.GalImage(
								self.attr('href'),
								sImg.attr('src'),
								sImg.attr('alt')
							)
						);
						
						comp.imageList.push(
							new scSite.item.GalImage(
								self.attr('href'),
								sImg.attr('src'),
								sImg.attr('alt')
							)
						);
						
						// Loop through and change it so that only the thumbs get shown since the images aren't enlarged at this point.
						self.attr('href', sImg.attr('title','').attr('alt','').attr('src'));
						
						/*self.click(function(){
							setTimeout( showPopupGallery, 500 );
						});*/
					})
				;
				
				tGal.addClass('ad-gallery')
					.delegate('.ad-image img', 'click', showPopupGallery)
				;
				
				comp.largerLinkFunc = showPopupGallery;
				
				function showPopupGallery(ev)
				{
					imgIndex = forceImgIndex == false ? tGalAd.current_index : forceImgIndex;
					if( isNaN(imgIndex) )
					{
						imgIndex = 1;
					}
					if ( !scSite.browser.isIE7orLess() )
					{
						forceImgIndex = false;
					} else {
						forceImgIndex = true;
					}

					if( ! popupGallery )
					{
						popupGallery = scSite.popupImageGallery.newImageGallery(imgList, imgIndex);
					}
					
					
					if ( !scSite.browser.isIE7orLess() )
					{
						popupGallery.open(imgIndex);
					} else {
						popupGallery.open(0);
					}
					
					// if we've got six or less thumbs, hide the scroller arrows on the sides of the thumb gallery
					if( $('.sc-item-image-gallery .ad-thumb-list li').length <= 6 )
					{
						$('.sc-item-image-gallery .ad-forward').hide();
						$('.sc-item-image-gallery .ad-back').hide();
					}
					
					// if we've got only one image, hide the left & right arrows on main image
					if( $('.sc-item-image-gallery .ad-thumb-list li').length <= 1 )
					{
						$('.sc-item-image-gallery .ad-next, .sc-item-image-gallery .ad-prev').css('display','none');
					}
				}
				
				var tGalFirstImgShown = false;
				var tGalInited = false;
				
				if ( !scSite.browser.isIE7orLess() )
				{
					//alert('whfasfdaadfsdfasddfast??');
					comp.galAd = tGalAd = tGal.adGallery(
					{
						thumb_opacity: 1,
						description_wrapper: false,
						slideshow: { enable: false },
						scale_up: true,
						callbacks:
						{
							init: function()
							{
								$(window).load(function(){
									$.timeoutRepeat(function()
									{
										if( tGalFirstImgShown )
										{
											tGalInited = true;
											scSite.itemVideo.playVideo();
											return true;
										}
										return false;
									}, 100, 10);
								});
							},

							beforeImageVisible: function()
							{
								scSite.itemOptions.imageOverlays.hideOverlays(true);
								scSite.personalization.hideCoverText(true);

								if( tGalInited )
								{
									scSite.itemVideo.stopVideo();
								}
							},

							afterImageVisible: function()
							{
								if( this.current_index == 0 )
								{
									scSite.itemOptions.imageOverlays.hideOverlays(false);
									scSite.personalization.hideCoverText(false);
								}
								if ( tGalFirstImgShown == true )
								{
									// show the popup gallery after they click on a thumbnail
									//showPopupGallery();
								}
								tGalFirstImgShown = true;
								
							}
						}
					})[0];
					
					// if we've got six or less thumbs, hide the scroller arrows on the sides of the thumb gallery
					if( $('.ad-thumb-list li').length <= 6 )
					{
						$('.ad-nav').css('margin-left','0px');
						$('.ad-thumbs').css('width','230px');
						$('.ad-forward').hide();
						$('.ad-back').hide();
					}
					
					// if we've got only one image, hide the left & right arrows on main image
					if( $('.ad-thumb-list li').length <= 1 )
					{
						$('.ad-next, .ad-prev').css('display','none');
					}
					
				
				} else {
					//old IE setup
					//alert('what??');
					forceImgIndex = true;
					$('.ad-thumb-list').css('width','250px');
					//alert('boogity');
					$('.ad-thumbs').css('overflow','none');
					$('.ad-nav').css('width','250px');
					$('.ad-nav').css('margin-left','0px');
					
					// show the popup gallery after they click on a thumbnail
					$('.ad-thumb-list a').click(function(ev){
						ev.preventDefault();
						showPopupGallery(ev);
					});
					
					//scSite.itemOptions.enableOptionsDropdowns();
					
					// if we've got only one image, hide the left & right arrows on main image
					if( $('.ad-thumb-list li').length <= 1 )
					{
						$('.ad-next, .ad-prev').css('display','none');
					}
				}
			});
		}
		
	});
});


scSite.genericThumbGallery = scSite.addComponent('genericThumbGallery', function(comp)
{
	$.extend(comp,
	{
		videoPlaceHolder: '/images/icons/control-play-blue.png', 
		
		// The function called when clicking the "View Larger Image" link on an item page.
		// Even if there are multiple image galleries, largerLinkFunc can only apply to one.
		largerLinkFunc: $.noop,
		
		galAd: null,
		
		selectFirstImage: function()
		{
			$('.sc-thumb-gallery').find('.ad-thumb0').trigger('click');
		},
		
		init: function()
		{
			$('.see_larger_image_link,.productimagetext').live('click', function(ev)
			{
				if( typeof comp.largerLinkFunc == 'function' )
				{
					ev.preventDefault();
					comp.largerLinkFunc();
				}
			});
			
			// Overlays may not work as expected if there is more than one item-thumb-gallery
			$('.sc-generic-thumb-gallery').each(function()
			{
				// thumbGallery
				var tGal = $(this);
				var tGalAd;
				
				var popupGallery;
				
				var hoverImg = 0;
				var imgIndex;
				var forceImgIndex = false;
				
				var imgList = [];
				
				// foreach thumbnail link, go through and add the image to the popup gallery list - DGP
				tGal.find('.ad-thumb-list a')
					.each(function()
					{
						var self = $(this);
						var sImg = self.find('img');
						
						self.data('sc-gallery-index', imgList.length);
						
						imgList.push(
							new scSite.item.GalImage(
								self.attr('href'),
								sImg.attr('src'),
								sImg.attr('alt')
							)
						);
						
						// Loop through and change it so that only the thumbs get shown since the images aren't enlarged at this point.
						self.attr('href', sImg.attr('title','').attr('alt','').attr('src'));
						
						self.click(function(ev){
							ev.preventDefault();
							setTimeout( showPopupGallery, 500 );
						});
					})
				;
				
				function showPopupGallery(ev)
				{
					imgIndex = forceImgIndex == false ? tGalAd.current_index : forceImgIndex;
					if( isNaN(imgIndex) )
					{
						imgIndex = 1;
					}
					if ( !scSite.browser.isIE7orLess() )
					{
						forceImgIndex = false;
					} else {
						forceImgIndex = true;
					}

					if( ! popupGallery )
					{
						popupGallery = scSite.popupImageGallery.newImageGallery(imgList, imgIndex);
					}
					
					
					if ( !scSite.browser.isIE7orLess() )
					{
						popupGallery.open(imgIndex);
					} else {
						popupGallery.open(0);
					}
					
					// if we've got six or less thumbs, hide the scroller arrows on the sides of the thumb gallery
					if( $('.sc-item-image-gallery .ad-thumb-list li').length <= 6 )
					{
						$('.sc-item-image-gallery .ad-forward').hide();
						$('.sc-item-image-gallery .ad-back').hide();
					}
				}
				
				tGal.addClass('ad-gallery')
					.delegate('.ad-image img', 'click', showPopupGallery)
				;
				
				comp.largerLinkFunc = showPopupGallery;
				

				var tGalFirstImgShown = false;
				var tGalInited = false;
				
				if ( !scSite.browser.isIE7orLess() )
				{
					//alert('whfasfdaadfsdfasddfast??');
					comp.galAd = tGalAd = tGal.adGallery(
					{
						thumb_opacity: 1,
						description_wrapper: false,
						slideshow: { enable: false },
						scale_up: true,
						callbacks:
						{
							init: function()
							{
								$(window).load(function(){
									$.timeoutRepeat(function()
									{
										if( tGalFirstImgShown )
										{
											tGalInited = true;
											scSite.itemVideo.playVideo();
											return true;
										}
										return false;
									}, 100, 10);
								});
							},

							beforeImageVisible: function()
							{
								scSite.itemOptions.imageOverlays.hideOverlays(true);
								scSite.personalization.hideCoverText(true);

								if( tGalInited )
								{
									scSite.itemVideo.stopVideo();
								}
							},

							afterImageVisible: function()
							{
								if( this.current_index == 0 )
								{
									scSite.itemOptions.imageOverlays.hideOverlays(false);
									scSite.personalization.hideCoverText(false);
								}
								if ( tGalFirstImgShown == true )
								{
									// show the popup gallery after they click on a thumbnail
									//showPopupGallery();
								}
								tGalFirstImgShown = true;
								
							}
						}
					})[0];
					
					// if we've got six or less thumbs, hide the scroller arrows on the sides of the thumb gallery
					/*if( $('.ad-thumb-list li').length <= 6 )
					{
						$('.ad-nav').css('margin-left','0px');
						$('.ad-thumbs').css('width','230px');
						$('.ad-forward').hide();
						$('.ad-back').hide();
					}*/
				
				} else {
					//old IE setup
					//alert('what??');
					forceImgIndex = true;
					$('.ad-thumb-list').css('width','100%');
					//alert('boogity');
					$('.ad-thumbs').css('overflow','none');
					$('.ad-nav').css('width','100%');
					$('.ad-nav').css('margin-left','0px');
					
					// show the popup gallery after they click on a thumbnail
					/*$('.ad-thumb-list a').click(function(ev){
						ev.preventDefault();
						showPopupGallery(ev);
					});*/
					
					//scSite.itemOptions.enableOptionsDropdowns();
					
					
				}
			});
		}
		
	});
});

scSite.popupImageGallery = scSite.addComponent('popupImageGallery', function(comp)
{
	$.extend(comp,
	{
		Gallery: function(images, index, popupEle, html)
		{
			this.imgList = images;
			this.index = isNaN(index) ? 0 : index;
			this.popupEle = popupEle;
			this.html = html;
			
			var selfGal = this;
			
			this.open = function(newIndex)
			{
				if( ! isNaN(newIndex) )
				{
					selfGal.index = newIndex;
				} else {
					selfGal.index = 0;
				}
				selfGal.popupEle.dialog('open');
				comp.repositionAndResize(selfGal);
			}
			
			this.close = function()
			{
				this.popupEle.dialog('close');
			}
		},
		
		galleries: [],
		
		// Creates a hidden dialog window with the large image gallery
		newImageGallery: function(imgList, imgIndex)
		{
			// Gallery Id
			var galId = $.scuid('itemPhotoGallery');
			
			var galleryIsOpen = false;
			var galleryIsResizing = false;
			
			if( isNaN(imgIndex) )
			{
				imgIndex = 0;
			}
			
			var igEle = $('<div />')
				.dialog(
				{
					close: function()
					{
						scSite.overlay.close(galId);
						galleryIsOpen = false;
					},
					open: function()
					{
						scSite.overlay.open(galId);
						galleryIsOpen = true;
					},
					autoOpen: false,
					resizable: false,
					modal: true
				})
							
							
				$('<div />').css({'position': 'fixed', 'z-index':'2000'}).appendTo('body')
					.append(igEle.closest('.ui-dialog'))
					// Get the widget element and make its position fixed
					//.closest('.ui-dialog')
					//	.css({'position': 'fixed', 'top': '2px'})
			;
			
			var igHTML =
			(
				'<div id="'+ galId +'" class="sc-item-image-gallery ad-gallery" style="margin: 0 auto;">'+
					'<div class="ad-image-wrapper" />'+
					'<div class="ad-controls" />'+
					'<div class="ad-nav">'+
						'<div class="ad-thumbs">'+
							'<ul class="ad-thumb-list">'
			);
				
			// Using each although its for one item.
			for( var k in imgList )
			{
				var i = imgList[k];
				if(i.src == comp.videoPlaceHolder)
					continue;

				igHTML += '<li><a href="'+ i.src +'"><img src="'+ i.thumb +'" /></a></li>';
			}

			igHTML +=
			(
							'</ul>'+
						'</div>'+
					'</div>'+
				'</div>'
			);
			
			var gal = new scSite.popupImageGallery.Gallery(imgList, imgIndex, igEle, igHTML);
			comp.galleries.push(gal);
			
			var resizeNotTooOften =
					$.notTooOften(100, function()
					{
						galleryIsResizing = false;
						comp.repositionAndResize(gal)
					});
			
			$(window).resize(function()
			{
				if( galleryIsOpen )
				{
					galleryIsResizing = true;
					resizeNotTooOften();
				}
			});
			
			return gal;
		},
		
		repositionAndResize: function(gal)
		{
			// Be aware of a resizing "hack". When the browser is resized, the gallery html gets canned and is completely regenerated.
			// This means resizing it is slow, but luckily resizing it isn't common.

			if( gal.popupEle && gal.popupEle.dialog("isOpen"))
			{
				var winHeight = $(window).height() - 10;
				var winWidth = 
						Math.min(
							winHeight,
							$(window).width() - 10
						);

				var imgLength = winWidth - 120;

				if( gal.el )
				{
					gal.popupEle.empty();
				}
				
				gal.popupEle.html(gal.html)
				gal.adEle = gal.popupEle.children('.ad-gallery');
				
				gal.adEle.adGallery(
				{
					thumb_opacity: 1,
					width: imgLength,
					height: imgLength,
					start_at_index: gal.index,
					description_wrapper: false,
					slideshow: { enable: false },
					callbacks:
					{
						afterImageVisible: function()
						{
							gal.index = this.current_index;
							gal.popupEle.dialog('option', 'title', gal.imgList[gal.index].alt);
						}
					}
				});

				gal.popupEle.dialog({width: winWidth, height: winHeight})

				// Running the position separately helps with glitch where its slightly higher than it should be.
				gal.popupEle.dialog({position: 'top'})

				gal.popupEle.closest('.ui-dialog')
						.addClass('sc-popup-image-gallery')
			}
		}
		
	});
});

scSite.itemZoom = scSite.addComponent('itemZoom', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			//alert( $('.jTscroller').outerWidth() )
			//if ( !scSite.browser.isIE7orLess() )
			//{
				$(document).ready(function () {
					
				});
			
			//}
			
			if( !scSite.browser.isIE6orLess() )
			{
				$('#productThumbScroller').thumbnailScroller({
					scrollerType:"clickButtons",
					scrollerOrientation: "horizontal"
				})
				
				$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
				if( scSite.itemVideo.hasVideo )
				{
					$("#wrap").css('visibility','hidden');
				}
				
				// toggle personalization overlay when switching images
				$('#productThumbScroller .jTscroller a').click(function(ev){
					ev.preventDefault()
					if ( $(this).attr('href') == $('#productThumbScroller .jTscroller a:first').attr('href') )
					{
						scSite.personalization.hideCoverText(false);
					} else {
						scSite.personalization.hideCoverText(true);
					}
				})
				
			} else {
				// in IE6, reformat this to make all the thumbnails visible
				$('.jTscrollerNextButton, .jTscrollerPrevButton').hide()
				$('.jThumbnailScroller').css({'overflow':'show','height':'100px'})
				$('.jTscroller').css({'display':'block'})
				$('.jTscroller').addClass('lightbox-link-group')
				$('.jTscroller a').addClass('lightbox-link').css('margin','0px 5px 3px 0px')
				$('#productZoom, .see_larger_image_link').addClass('lightbox-open')
				$('#productZoom').css('cursor','url("/images/magnify.cur")')
				scSite.lightboxLink.init()
			}
			
			
			
			
			
		}	
	})

});

scSite.zoomPopupGallery = scSite.addComponent('zoomPopupGallery', function(comp)
{
	$.extend(comp,
	{
		hasInitThumbScroller: false,
		createdZoom: [],
		
		figureZoomBoxWidth: function() {
			imgUrl = $('#productZoomPopup').attr('href')
			imgOb = new Image();
			imgOb.src = imgUrl;
			newZoomWidth = $('#productImagePopup').css('width').match(/[0-9]+/) - $('#productZoomPopup img').css('width').match(/[0-9]+/) - 50;
			if ( imgOb.width < newZoomWidth && imgOb.width != 0 )
			{
				newZoomWidth = imgOb.width
			}
			return newZoomWidth
		},
		
		figureZoomBoxHeight: function() {
			imgUrl = $('#productZoomPopup').attr('href')
			imgOb = new Image();
			imgOb.src = imgUrl;
			newZoomHeight = $('#productImagePopup').css('height').match(/[0-9]+/) - $('#productThumbScrollerPopup2').css('height').match(/[0-9]+/) - 35;
			if ( imgOb.height < newZoomHeight && imgOb.height != 0)
			{
				newZoomHeight = imgOb.height
			}
			return newZoomHeight
		},
		
		init: function()
		{
			if( !scSite.browser.isIE6orLess() )
			{
				// $('#productImagePopup').dialog({autoOpen:false,modal:true,width:800, height: $(window).height() - 10}) // ver 1
				$('#productImagePopup').dialog({autoOpen:false,modal:true,show:'clip', hide:'clip',width:  $(window).width() * .8, height: $(window).height() * .9}) // ver 2
				
				$('#productThumbScrollerPopup2').live( 'mouseout', function() {
					//alert('blarg')
					//$('#productImagePopup .cloud-zoom-lens').remove()
				})
				
				$('#itemZoomGallery, .see_larger_image_link').live( 'click', function(ev) {
					ev.preventDefault()
					
					//$('#productImagePopup').dialog({height: $(window).height() - 10}) // ver 1
					$('#productImagePopup').dialog({width:  $(window).width() * .8, height: $(window).height() * .9}) // ver 2
					// $('#productThumbScrollerPopup').css('max-height', $('#productImagePopup').dialog('option','height') - 220 - 65 + 'px' ) // ver 1
					var toBeClicked;
					$('#productImagePopup a.cloud-zoom-gallery').each(function(){
						if ( $(this).attr('href') == $('#productZoom').attr('href') )
						{
							toBeClicked = $(this)
						}
					})
					
					$('#productImagePopup').dialog('open')
					toBeClicked.click()
					
					if ( !comp.hasInitThumbScroller )
					{
						$('#productThumbScrollerPopup2').thumbnailScroller({
							scrollerType:"clickButtons",
							scrollerOrientation: "horizontal"
						})
						comp.hasInitThumbScroller = true
					}
				})
				
				$(window).bind( 'resize', function() {
					//$('#productImagePopup').dialog({height: $(window).height() - 10})
					if ( $('#productImagePopup').dialog('isOpen') === true )
					{
						$('#productImagePopup').dialog({width:  $(window).width() * .8, height: $(window).height() * .9}) // ver 2
						$('#productImagePopup').dialog({position:'center'})
					// $('#productThumbScrollerPopup').css('max-height', $('#productImagePopup').dialog('option','height') - 220 - 65 + 'px' ) // ver 1
					
						comp.createdZoom = []
					}
				})
				
				$('#productThumbScrollerPopup2 a').click( function(ev) {
					ev.preventDefault()
					$('#productImagePopup').dialog({title: $('img', this).attr('title')})
				})
				
			}
		}
	})
});


//
// Item Video
////////////////////////////////

scSite.itemVideo = scSite.addComponent('itemVideo', function(comp)
{
	$.extend(comp,
	{
		
		hasVideo: false,
		
		init: function()
		{
			comp.flashPlayer = $('#player1')
				.css('position', 'absolute');
			
			var imageG = $('#itemThumbGallery')
			if ( !imageG.size() )
			{
				var imageG = $('#itemZoomGallery')
			}
			
			comp.imageGallery = imageG
				.css('position', 'relative');
				
			comp.hasVideo = $.elFull( comp.flashPlayer )
			
			if( comp.hasVideo )
			{
				comp.imageGallery.prepend(comp.flashPlayer);
				
				$('.sc-item-play-video').live('click', function( ev )
				{
					ev.preventDefault();
					comp.playVideo();
				});

				if( comp.intializedOptions )
				{
					comp.loadVideo();
				}
			}
		},
		
		initOptions: function(itemId, videoUrl, mainImage)
		{
			comp.itemId = itemId;
			comp.demoVideoUrl = videoUrl;
			comp.defaultMainImage = mainImage;
			comp.intializedOptions = true;
		},
		
		itemId: 0,
		demoVideoUrl: '',
		defaultMainImage: '',
		intializedOptions: false,
		
		timeRemaining: -1,
		timeElapsed: -1,
		
		flashPlayer: $(),
		imageGallery: $(),
		
		
		loadVideo: function()
		{
			var FO = {	movie:"./flvplayer.swf",id:"flashplayerwoot",display:"none",width:"250",height:"200",majorversion:"8",build:"0",bgcolor:"#FFFFFF",wmode:"transparent",
					flashvars:"file="+ comp.demoVideoUrl +"&showdigits=true&autostart=true&showfsbutton=false&fsreturnpage=flvplayer.html&overstretch=true&enablejs=true&image="+ comp.defaultMainImage };

			UFO.create(	FO, "player1");
			$('#wrap').css('visibility', 'hidden')
			$('item_image_'+ comp.itemId +'_0').css( 'display', 'none' );
			$('.click-to-zoom').hide()
		},
		
		playVideo: function() {
			if( comp.hasVideo )
			{
				comp.flashPlayer.show();
				comp.imageGallery
					.find('.ad-image-wrapper').css('visibility', 'hidden')
				$('#wrap').css('visibility', 'hidden')

				$('#enlargeClicker').css('display', 'none');
				$('#overlayImageDiv').css('display', 'none');
				//$('#item_image_{/literal}{$item_info.id}{literal}_0').css('display', 'none');
				
				$('.click-to-zoom').hide()
			}
		},
		
		stopVideo: function() {
			if( comp.hasVideo )
			{
				comp.flashPlayer.hide();
				comp.imageGallery
					.find('.ad-image-wrapper').css('visibility', '')
				$('#wrap').css('visibility', '')

				$('#enlargeClicker').css('display', '');
				var id5 = $('#overlayImageDiv');
				$('#item_image_{/literal}{$item_info.id}{literal}_0').css('display', 'block');
				if( id5.size() )
				{
					id5.css('display', '');
					scSite.item.placeEditorsPickOverlay();
				}
				

				$('.click-to-zoom').show()
			}
		},
		
		updateVideoTime: function(timeElapsed, timeRemaining)
		{
			if( comp.hasVideo && ! isNaN(timeRemaining) )
			{
				comp.timeRemaining = timeRemaining;
				comp.timeElapsed = timeElapsed;
			}
			
		},
		
		updateVideoState: function(state)
		{
			if( comp.hasVideo && state == 0 )
			{
				comp.stopVideo();
			}
		},
		
		// Function is here just to have.
		swap: function()
		{
			if( comp.flashPlayer.is(':visible') )
			{
				comp.stopVideo();
			}
			else
			{
				comp.playVideo();
			}
		}
		
	});
});





////////////////////////////////////////////////////////////////
// Promo Tip
////////////////////////////////////////////////////////////////
scSite.itemPromoTip = scSite.addComponent('itemPromoTip', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			//alert('why');
			var promoTip = $('#promoTip');

			if( $('*', promoTip).size() )
			{
				//alert('why not?');
				$('#promoIntroBox').qtip(
				{
					content: function()
					{
						return $('#promoTip').html();
					},
					position: {
						my: 'bottom left',
						at: 'top left',
						target: $('#promoIntroBox')
					},
					hide: {
						//event: 'unfocus'
						delay: 3000
					}	
				});
			}
		}
	});
});

////////////////////////////////////////////////////////////////
// Promo Business Time
// Only show certain promo text during our business hours
// to let customers know they can call in for special pricing
////////////////////////////////////////////////////////////////
scSite.itemPromoBusinessTime = scSite.addComponent('itemPromoBusinessTime', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			var promoBTContent = $('.promo-business-time');
			var promoBox = $('#promoIntroBox');
			if ( promoBTContent.size() && promoBox.size() )
			{
				jDate = new Date( promoBox.data('server-time') );
				if ( 
					( jDate.getDay() != 0 && jDate.getDay() != 6 && jDate.getHours() >= 7 && ( jDate.getHours() < 18 || ( jDate.getHours() == 18 && jDate.getMinutes() <= 30 ) ) ) || // weekdays between 7-630
					( jDate.getDay() == 6 && jDate.getHours() >= 9 && ( jDate.getHours() < 14 || ( jDate.getHours() == 14 && jDate.getMinutes() <= 30 ) ) ) // saturday between 9-230
				)
				{
					promoBTContent.show();
				} else {
					promoBTContent.hide();
				}
			}
		}
	});
});

////////////////////////////////////////////////////////////////
// Item Bread Crumbs
////////////////////////////////////////////////////////////////

scSite.itemBreadcrumbs = scSite.addComponent('itemBreadcrumbs', function(comp)
{
	var crumbToggle = false;

	$.extend(comp,
	{
		init: function()
		{
			$('#more_cats_hide, #more_cats_expand').click(comp.toggleMoreDepts);
		},

		toggleMoreDepts: function()
		{
			var toggle = $('#more_cats_table');
			var toggle2 = $('#more_cats_expand');

			var newDisplay;

			if( crumbToggle )
			{
				crumbToggle = false;
				toggle.css('display', 'none');
				toggle2.css('display', 'inline');
			}
			else
			{
				crumbToggle = true;
				toggle.css('display', 'block');
				toggle2.css('display', 'none');
			}

			var id5 = $('#overlayImageDiv');
			if( id5.size() )
			{
				scSite.item.placeEditorsPickOverlay();
			}
		}
	});
});



////////////////////////////////////////////////////////////////
// Item Overly Image (Editers Pick)
////////////////////////////////////////////////////////////////
//
// ?WhereIsThisUsed? (this seems to have some references but never actually makes a difference because the '#overlayImage' element never exists in the HTML)
//		/item_item_9382.html  <- this item is suppost to be an editors pick.
//

scSite.item.placeEditorsPickOverlay = function()
{
	var mainI = $('#productImageMain');
	var overlayI = $('#overlayImage');
	
	if( mainI.size() && overlayI.size() )
	{
		overlayI.css({position: 'absolute', display: 'inline'});
		
		// Doing this twice, because the code that this was converted from did it twice (to get around a bug).
		overlayI.offset(mainI.offset());
		overlayI.offset(mainI.offset());
	}
};



////////////////////////////////////////////////////////////////
// SpinPB (Formerly TurnPB / Turn Progress Bar)
////////////////////////////////////////////////////////////////

scSite.item.spinPB = function()
{
	/*var pb = $('#progressbarholder');
	pb.css('display', 'inline');
	setTimeout(function()
	{
		$('image[name="pbar"]').attr('src', 'http://sc-marketing.s3.amazonaws.com/loading.gif');	
	}, 200);*/
	scSite.loadingSpinner.showSpinner({ 
		contextElement: '.cartaddbutton',
		contextTop: 20,
		contextLeft: -5
	});	
}




////////////////////////////////////////////////////////////////
// Personlization
////////////////////////////////////////////////////////////////
scSite.personalization = scSite.addComponent('itemPersonalization', function(comp)
{
	$.extend(comp,
	{
		persId: null,
		itemId: null,
		config: null,
		persFieldName: null,
		
		personalizeErrorShown: {},
		
		fillPersBoxFunc: jQuery.noop,
		
		errorPopup: null,
		
		init: function()
		{
			comp.fillPersBoxFunc();
		},
		
		
		textCache: {},
		
		/*
		 * AKA "CheckForPersCookieAndFill"
		 *
		 * Checks to see if a cookie exists for an item's customization.
		 * If so set the Personalize Input Field's value to it.
		 */
		setPersonalizationFieldFromCookie: function(pers_type, fill_box)
		{
			if (pers_type && pers_type !='')
			{
				var persCookieVal = readCookie('persCookie'+pers_type);
				
				if (persCookieVal && persCookieVal != '')
				{
					var persText = $('#'+fill_box);
					if (persText.size() && persText.is(':visible'))
					{
						persText.val(persCookieVal);
						return true;
					}
				}
			}	
			return false;
		},

		fillPersBoxForReal: function(config)
		{
			var pTxtBox = $('#persTextBox'+ config.persid +'-' + config.itemid);
			
			function doIt1()
			{
				comp.moveCoverText(pTxtBox.val(), config);
			}

			function doIt2() 
			{
				comp.persFromDropDown(config);
			}
			
			var idSuffix = config.persid +'-'+ config.itemid;
			
			comp.setPersonalizationFieldFromCookie(config.perstype, 'persTextBox'+ config.persid +'-'+ config.itemid);
			
			if (config.usePersonalizeFromDropdown )
			{
				comp.fillPersBoxFunc = doIt2;
			}
			else
			{
				comp.fillPersBoxFunc = doIt1;
				
				// Reposition when the window is resized.
				var resizeTimer;
				$(window).resize(function()
				{
					if( resizeTimer )
					{
						clearTimeout( resizeTimer );
					}
					resizeTimer = setTimeout(doIt1, 100);
					
				});
			}
			
			// Add listeners to the text input and color select to update the preview.
			$('#persTextBox'+ idSuffix +', #persColorDrop'+ idSuffix)
				.bind('keyup change', doIt1);
			
			if( config.lastGroup )
			{
				$("#options_accessories_select_"+ config.lastGroup).change(comp.fillPersBoxFunc);
			}
		},
		
		
		hideCoverText: function(doHide)
		{
			$('.personalizeTextOverlay').css('visibility', doHide ? 'hidden' : 'visible');
		},
		
		
		// Formerly "MoveGrillCoverText" of "personalization.js"
		moveCoverText: function(text, config)
		{
			var mainI = $('#productImageMain');
			var coverText = $('#personalizeTextDiv'+config.persid);
			
			var elTxtInput = $('#persTextBox'+ config.persid +'-'+ config.itemid);
			
			var cartvalue;
			
			// Just resizing the page seems to trigger this function, so this ensures there actually was a change.
			var oldText = comp.textCache[config.persid +'-'+ config.itemid];
			if( !scSite.browser.isIE7orLess() && scSite.itemThumbGallery.galAd && scSite.itemThumbGallery.galAd.current_index != 0 && oldText != text)
			{
				// There was personalization text change, to show it we must be on the first image.
				scSite.itemThumbGallery.selectFirstImage();
				comp.textCache[config.persid +'-'+ config.itemid] = text;
			}
		
			var hasError = false;
			var errTxt = '';
						
			if( text && text != '' && config)
			{

				config.imageheight = parseInt(config.imageheight);
				config.imagewidth = parseInt(config.imagewidth);

				text = $.trim(text);
				var plaintext = text;

				if (text.search(config.regex) != -1)
				{

					//if we dont have a font color passed, go look for the dropdown and get current color
					//alert(config.fontcolor);
					//if (config.fontcolor == '')
					//{
					//	alert('trying to find color');
						var colordrop = $('#persColorDrop' + config.persid + '-' + config.itemid);
						if (colordrop.size())
						{
							config.fontcolor = colordrop.val();
						} else if ( config.fontcolor == '' ) {
							config.fontcolor = 'black';
						}
					//}
					
					//set value in cart form
					if (config.optionsgroup && config.optionsgroup != '' && config.optionsgroup > 0)
					{
						cartvalue = $('#personalization_cart_'+config.persid+'_'+config.optionsgroup);
					} else {
						cartvalue = $('#personalization_cart_'+config.persid+'_'+config.itemid);
					}

					cartvalue.val(plaintext + ":" + config.fontcolor);

					//store in cookie for further use
					if (config.perstype != '')
					{
						createCookie('persCookie'+config.perstype, plaintext, 30);
					}

					if (config.sale_price && config.sale_price != '')
					{
						persPrice = parseFloat(config.sale_price);
						if (persPrice > 0)
						{
							$('#persPriceHolder-' + config.persid + '-' + config.itemid)
								.data('is-active', 'true')
						}				
					}

					if ( mainI.size() && coverText.size() )
					{
						if (config.showonpic && config.showonpic == 'Yes')
						{
							var mOff = mainI.offset();

							if (config.fontface == 'image' && config.fontcolor != '' && config.brand != '')
							{
								var imgTxtArry = [];

								var imgTxt = '';
								for( k=0; k<text.length; k++ )
								{
									var imagesrc = '/images/personalization/'+config.brand.toLowerCase()+'/'+config.fontcolor+'_text_'+text.charAt(k)+'.png';

									imgTxt += '<img src="'+ imagesrc +'" ';

									if (config.imageheight > 0 && config.imagewidth > 0)
									{
										imgTxt += ' width="'+ config.imagewidth +'" height="'+ config.imageheight +'" />';
									}

									if (config.orientation == 'v')
									{
										imgTxt += '<br/>';
									}
								}
								text = imgTxt;
							}
							else
							{
								if (config.fontcolor != '') {
									coverText.css('color', config.fontcolor);
								}
								if (config.fontsize != '') {
									coverText.css('font-size', config.fontsize);
								}
								if (config.fontface != '') {
									coverText.css('font-family', config.fontface);
								}
								if (config.fontface != '') {
									coverText.css('font-weight', config.fontweight);
								}
							}

							coverText.css(
							{
								'display': 'block',
								'z-index': 18
							});

							if (config.orientation == 'v' && config.fontface != 'image')
							{
								coverText.css('line-height', '0.9em');
								coverText.css('text-align', 'center');
								var verttext = '';
								for( k=0; k < text.length; k++ )
								{
									verttext += text.charAt(k) + "<br>";
								}
								text = verttext;
							}
							coverText.html( text );

							if (config.centered && config.centered == 'Yes')
							{
								var textWidth = coverText.width();
								var textHeight = coverText.height();

								if
								(
									textHeight==0 && textWidth == 0 &&
									imgheight == 0 && imgwidth == 0 &&
									config.fontface == 'image' && config.imagewidth > 0 && config.imageheight > 0
								)
								{
									if (config.orientation == 'h') {
										textWidth += config.imagewidth;
										if (plaintext.length == 1)
										{
											textHeight += config.imageheight;
										}
									}
									else if (config.orientation == 'v')
									{
										textHeight += config.imageheight;
										if (plaintext.length == 1)
										{
											textWidth += config.imagewidth;
										}
									}
								}

								if ((config.x + config.y) > 0)
								{
									if (config.orientation == 'h')
									{
										var centeredX = mOff.left + (config.x - (textWidth / 2));
										var centeredY = mOff.top + config.y;
									}
									else if (config.orientation == 'v')
									{
										var centeredX = mOff.left + config.x;
										var centeredY = mOff.top + (config.y - (textHeight / 2));
									} 
								}
								else
								{
									var centeredX = mOff.left + ((250 - textWidth) / 2);
									var centeredY = mOff.top + ((250 - textHeight) / 2);
								}

								coverText.css({left: centeredX, top: centeredY});
							}

							// Removed[PersonalizationAlert2]
						}
					}
				}
				else
				{
					hasError = true;
					errTxt = config.errormsg;
				}
			}
			else
			{

				if (text == '' && config.is_required == 'No')
				{
					//erase value in cart form
					if (config.optionsgroup && config.optionsgroup != '' && config.optionsgroup > 0)
					{
						cartvalue = $('#personalization_cart_'+config.persid+'_'+config.optionsgroup);
					}
					else
					{
						cartvalue = $('#personalization_cart_'+config.persid+'_'+config.itemid);
					}
					cartvalue.val('N:A');
				}
				if (text == '' && coverText.size() )
				{
					coverText.html( '' );	
					if (config && config.perstype != '')
					{
						createCookie('persCookie'+config.perstype, '', 30);
					}
				}
				if (text == '')
				{
					$('#persPriceHolder-' + config.persid + '-' + config.itemid)
						.data('is-active', 'false')
				}
			}
			scSite.item.calculatePriceWithCustomization();
			
			if( hasError )
			{
				if( ! comp.personalizeErrorShown[config.persid] )
				{
					coverText.html( '' );

					elTxtInput
						.qtip(
						{
							content: errTxt,
							style:
							{
								classes: 'ui-tooltip-error'
							},
							position: 
							{
								my: 'right center',
								at: 'left center'
							}
						})
						.qtip('show')
						.addClass('sc-field-error');

					comp.personalizeErrorShown[config.persid] = true;
				}
			}
			else
			{
				elTxtInput
					.qtip('hide')
					.qtip('disable')
					.removeClass('sc-field-error');
				
				comp.personalizeErrorShown[config.persid] = false;
			}
			
			// Hide the error on The Button of Truth if we don't have any errors here.
			var errorFree = true;
			for( var k in comp.personalizeErrorShown )
			{
				if( comp.personalizeErrorShown[k] )
				{
					errorFree = false;
					break;
				}
			}
			if( errorFree )
			{
				scSite.addToCart.hideError();
			}

		},
		
		
		validatePersonalizationText: function(itemid, persid, regex, required, optionacc)
		{
			var errTxt = null;
			
			function _validate()
			{
				if (itemid && persid && regex && required && optionacc)
				{
					var testTextBox = $('#persTextBox'+persid+'-'+itemid);
					if (optionacc == 'Yes')
					{
						//kind of a goofy way to check for it, but if the text box for the required selection customization is hidden, ignore it and push to cart
						//otherwise, if it is showing, proceed with checks
						var testX = testTextBox.offset().left;
						if( isNaN(testX) || testX == 0)
						{
							// !DoHideErrors
							return true;
						}
					}
					var validateText = testTextBox;
					if( validateText.size() )
					{
						if (required == 'No' && validateText.val() == '')
						{
							// !DoHideErrors
							return true;				
						} else if (required == 'Yes' || (required == 'No' && validateText.val() != ''))
						{
							var testValidateText = validateText.val().search(regex);
							if( testValidateText != -1 )
							{
								// !DoHideErrors
								return true;
							}
							else
							{
								if (required == 'No')
								{
									errTxt = 'Please make corrections to your personalization before adding to the cart.';
								} else {
									errTxt = 'You must personalize this item before you purchase it.';
								}
								return false;
							}
						} else if (required == 'No' && validateText.value == '') {
							//the personalization is not required, but the text box is blank so no big deal
							return true;
						}
					}
				}
			};

			if( ! _validate() )
			{
				scSite.addToCart.showError(errTxt);
				return false;
			}
			else
			{
				scSite.addToCart.hideError();
				return true;
			}
		},
		
		// Formerly "PersonalizeFromDropdown" of "personalization.js"
		persFromDropDown: function(config)
		{
			if( config )
			{
				var mainI = $('#productImageMain');

				var oaPersCover = $('#reqSelectionPersCover'+config.persid);
				var oaPersSelect = $('#persOptionDrop'+config.persid+'-'+config.itemid);
				if( mainI.size() && oaPersCover.size() && oaPersSelect.size() )
				{
					var showPersOnImage = false;
					var persImageUrl = '';

					oaPersSelect.each(function()
					{
						if( this.selected == true)
						{
							var persClassPieces = this.className.split(" ");
							showPersOnImage = persClassPieces[0];
							persImageUrl = persClassPieces[1];
						}
					});

					if (showPersOnImage == 'Yes' && oaPersSelect.offset().left > 0)
					{
						var mOff = mainI.offset();

						var xfinal = parseInt(mOff.left + parseInt(config.x));
						var yfinal = parseInt(mOff.top + parseInt(config.y));

						//To strip whitespace and make lower case
						var rel_brand_folder = config.brand.toLowerCase().replace(/[^A-Za-z0-9]/, '');

						var elImage = $('<img />')
								.attr('src', '/images/personalization/'+rel_brand_folder+'/'+persImageUrl);

						oaPersCover
							.append( elImage )
							.css('display', 'block')
							.offset( {x: xfinal, y: yfinal} );

						// FGD - Removed[PersonalizationAlert]
					}
				}
			}
		}
	});
});



////////////////////////////////////////////////////////////////
// Item Add to Cart
////////////////////////////////////////////////////////////////
scSite.addToCart = scSite.addComponent('itemAddToCart', function(comp)
{
	$.extend(comp,
	{
		errorShown: false,
		errorTimeout: null,
		BoT: null,
		
		init: function()
		{
			comp.BoT = $('#buttonOfTruth');
			
			$('.sc-item-add-to-cart').live('click', function()
			{
				// Check to see if [window.]checkEverythingAndSubmit is defined, if so use that one.
				if( typeof checkEverythingAndSubmit === 'function' )
				{
					checkEverythingAndSubmit();
				}
				else
				{
					comp.checkEverythingAndSubmit();
				}
			});
			
			$('.sc-related-item-add-to-cart').live('change', function()
			{
				$(this).siblings('.related-item-qty').val(this.checked ? 1 : 0)
			});
			
		},
		
		validators: [],
		
		addValidator: function(validationFunc)
		{
			comp.validators.push(validationFunc);
		},
		
		addPersonalizationValidator: function(itemId, personalizationId, regex, isRequired, optionAcc)
		{
			comp.addValidator(function()
			{
				return scSite.personalization.validatePersonalizationText(itemId, personalizationId, regex, isRequired, optionAcc);
			});
		},
		
		checkEverythingAndSubmit: function()
		{
			//check through everything we can, submit if everything looks okay
			var submitcart = true;
			
			for( var i = 0; i < comp.validators.length; i++ )
			{
				submitcart = submitcart && comp.validators[i]();
			}
			
			if (submitcart == true)
			{
				scSite.item.spinPB();
				if ( $.isDefined('scSite.google.ga.pageTracker') )
				{
					scSite.google.ga.pageTracker._linkByPost(document.cartForm);
				}
				document.cartForm.submit();
			}
		},
		
		showError: function(txt)
		{
			clearTimeout(comp.errorTimeout);
			
			comp.errorTimeout = setTimeout(comp.hideError, 5000);
			
			if( ! comp.errorShown )
			{
				comp.BoT
					.qtip(
					{
						content: txt,
						style:
						{
							classes: 'ui-tooltip-error'
						},
						position: 
						{
							my: 'right center',
							at: 'left center'
						}
					})
					.qtip('show')
					.addClass('sc-field-error');

				comp.errorShown = true;
			}
		},
		
		hideError: function()
		{
			if( comp.errorShown )
			{
				clearTimeout(comp.errorTimeout);

				comp.BoT
					.qtip('hide')
					.qtip('disable')
					.removeClass('sc-field-error');

				comp.errorShown = false;
			}
		}
	});
});



////////////////////////////////////////////////////////////////
// Item Reviews
////////////////////////////////////////////////////////////////

scSite.itemReviews = scSite.addComponent('itemReviews', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			comp.initializeListeners();
		},
		
		updateKeysList: [ 'page', 'sort' ],

		MESSAGE_FLAGGED: "The requested review has been flagged to be screened by our staff.",
		MESSAGE_HELPFUL_YES: "This review has been marked as helpful.",
		MESSAGE_HELPFUL_NO: "This review has been marked as not helpful.",


		responsePageChange: function( o )
		{
			var container = $('#review-body-container');
			if( container.size() )
			{
				comp.removeListeners();
				container.html( o );
			}
			// comp.initializeListeners();				
		},

		responseHelpful: function( data, o )
		{
			if ( o == 'TRUE' )
			{
				if ( data.toLowerCase() == 'no' )
				{
					alert( comp.MESSAGE_HELPFUL_NO )
				}
				else if ( data.toLowerCase() == 'yes' )
				{
					alert( comp.MESSAGE_HELPFUL_YES )
				}
			}
		},

		responseFlag: function( data, o )
		{
			if ( o == 'TRUE' )
			{
				alert( comp.MESSAGE_FLAGGED )
			}
		},

		updateGeneric: function( type, data )
		{
			var updateDataList = [];
			for( i = 0; i < comp.updateKeysList.length; i++ )
			{
				if ( type == comp.updateKeysList[ i ] )
				{
					updateDataList[ i ] = data;
					continue;
				}

				var dataSingle = null;
				switch ( comp.updateKeysList[ i ] )
				{
					case 'page' :
						dataSingle = comp.getPage();
						break;
					case 'sort' :
						dataSingle = comp.getSort();
						break;
				}
				updateDataList[ i ] = dataSingle;
			}

			comp.ajax.updatePage( updateDataList, comp.responsePageChange )
		},

		setGeneric: function( review_id, type, data, func_callback )
		{
			return comp.ajax.setData( review_id, type, data, func_callback )
		},

		getPage: function()
		{
			var elCurPage = $('#review-page-current');
			if ( elCurPage.size() )
			{
				return elCurPage.val();
			}
			return 0;
		},

		getSort: function()
		{
			var elCurSorting = $('#review-sorting-current');
			if ( elCurSorting.size()  )
			{
				return elCurSorting .val();
			}
			return '';
		},

		updatePaging: function( new_page )
		{
			comp.updateGeneric( 'page', new_page );
		},

		updateSorting: function( new_sort )
		{
			comp.updateGeneric( 'sort', new_sort );
		},

		setHelpful: function( review_id, is_helpful )
		{
			comp.setGeneric( review_id, 'helpful', is_helpful, comp.responseHelpful )
		},

		setFlag: function( review_id )
		{
			comp.setGeneric( review_id, 'flag', 'Yes', comp.responseFlag )
		},

		input:
		{
			pagingChange: function( e, o )
			{
				e.preventDefault();

				if ( e && e.which && ( e.which == 13 ) )
				{
					if ( this && this.value )
					{
						if ( this.value != comp.getPage() )
						{
							comp.updatePaging( this.value );
						}
					}
				}
			},

			pagingBlur: function( e, o )
			{
				e.preventDefault();

				if ( this && this.value )
				{
					if ( this.value != comp.getPage() )
					{
						comp.updatePaging( this.value );
					}
				}
			},

			pagingClick: function( e, o )
			{
				e.preventDefault();

				var regex_paging = /^review-page-change-(?:arrow-)?([1-9][0-9]*)$/
				if ( regex_paging.test( this.id ) )
				{
					var new_page = regex_paging.exec( this.id )[ 1 ];
					comp.updatePaging( new_page );
				}
			},

			sortingChange: function( e, o )
			{
				e.preventDefault();

				if ( this && this.options && ( this.selectedIndex >= 0 ) && this.options[ this.selectedIndex ] && this.options[ this.selectedIndex ].value )
				{
					if ( this.options[ this.selectedIndex ].value != comp.getSort() )
					{
						comp.updateSorting( this.options[ this.selectedIndex ].value );
					}
				}
			},

			helpfulYesClick: function( e, o )
			{
				e.preventDefault();

				var regex_helpful_yes = /^review-helpful-yes-([1-9][0-9]*)$/;
				if ( regex_helpful_yes.test( this.id ) )
				{
					var review_id = regex_helpful_yes.exec( this.id )[ 1 ];
					comp.setHelpful( review_id, 'yes' );
				}
			},

			helpfulNoClick: function( e, o )
			{
				e.preventDefault();

				var regex_helpful_no = /^review-helpful-no-([1-9][0-9]*)$/;
				if ( regex_helpful_no.test( this.id ) )
				{
					var review_id = regex_helpful_no.exec( this.id )[ 1 ];
					comp.setHelpful( review_id, 'no' );
				}
			},

			flagClick: function( e, o )
			{
				e.preventDefault();

				var regex_flag = /^review-flag-([1-9][0-9]*)$/;
				if ( regex_flag.test( this.id ) )
				{
					var review_id = regex_flag.exec( this.id )[ 1 ];
					comp.setFlag( review_id );
				}
			}
		},

		ajax:
		{
			url: '',
			
			executing: false,
			updatePage: function( data, func )
			{				
				if ( comp.ajax.executing == false )
				{
					comp.ajax.executing = true;

					var query_string_list = [ 'page_change=yes' ];
					if ( comp.updateKeysList.length == data.length )
					{
						for( i = 0; i < comp.updateKeysList.length; i++ )
						{
							query_string_list.push( comp.updateKeysList[ i ] + '=' + data[ i ] );
						}
					}

					if ( query_string_list.length > 0 )
					{
						var query_string = query_string_list.join( '&' );
						
						$.ajax(
						{
							url: comp.ajax.url,
							type: 'POST',
							success: function(ajaxData)
							{
								func( ajaxData );
							},
							complete: comp.ajax.complete,
							data: query_string
						});
					}
				}
			},

			setDataSuccess: function( data, func1, param1 )
			{
				if ( data && func1 && param1 )
				{
					func1( param1, data );
				}
			},

			complete: function( o )
			{
				comp.ajax.executing = false;
			},

			setData: function( review_id, type, data, func_callback )
			{
				if ( comp.ajax.executing == false )
				{
					comp.ajax.executing = true;
					
					$.ajax(
					{
						url: comp.ajax.url,
						type: 'POST',
						success: function(ajaxData, textStatus, jqXHR)
						{
							comp.ajax.setDataSuccess(ajaxData, func_callback, data)
						},
						complete: comp.ajax.complete,
						data: 'review=' + review_id + '&' + type + '=' + data
					});
				}
			}
		},

		removeListeners: function()
		{
			var cont = $('#review-body-container');
			if ( cont.size() )
			{
				cont.find
				(
					'#review-page-change-input, .review-page-change-click, #review-sorting-select, '+
					'.review-helpful-yes-click, .review-helpful-no-click, .review-flag-click'						
				).unbind();
			}
		},

		initializeListeners: function()
		{
			$('#review-body-container')
				.delegate( '#review-page-change-input', 'blur', comp.input.pagingBlur )
				.delegate( '#review-page-change-input', 'keyup', comp.input.pagingChange )
				.delegate( '.review-page-change-click', 'click', comp.input.pagingClick )
				.delegate( '#review-sorting-select', 'change', comp.input.sortingChange )
				.delegate( '.review-helpful-yes-click', 'click', comp.input.helpfulYesClick )
				.delegate( '.review-helpful-no-click', 'click', comp.input.helpfulNoClick )
				.delegate( '.review-flag-click', 'click', comp.input.flagClick )
			;
		}

	});
});





////////////////////////////////////////////////////////////////
// Item Options
////////////////////////////////////////////////////////////////

scSite.itemOptions = scSite.addComponent('itemOptions', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			comp.enableOptionsDropdowns();
			
			$(window).resize(function()
			{
				comp.imageOverlays.reposition();
			})
		},
		
		// Handles (re)positioning image overlays.
		imageOverlays: 
		{
			overlays: {},
			Overlay: function(ele, xRel, yRel, width, height, of, xScale, yScale)
			{
				this.ele = ele;
				this.xRel = xRel;
				this.yRel = yRel;
				this.width = width;
				this.height = height;
				this.of = of;
				this.xScale = xScale;
				this.yScale = yScale;
				
				this.scaled = {
					left: Math.round(xRel * xScale),
					top: Math.round(yRel * yScale),
					width: Math.round(width * xScale),
					height: Math.round(height * yScale)
				}
			},
			
			addOverlay: function(ele, xPos, yPos, width, height, of, xScale, yScale)
			{
				var imgO = new comp.imageOverlays.Overlay(ele, xPos, yPos, width, height, of, xScale, yScale);
				comp.imageOverlays.overlays[ele.attr('id')] = imgO;
				return imgO;
			},
			
			removeOverlay: function(id)
			{
				if( typeof id !== 'string' )
				{
					// Must be an jQuery element and not a string Id.
					id = id.attr('id')
				}
				delete comp.overlays[id];
			},
			
			hideOverlays: function(doHide)
			{
				$('.sc-item-image-overlay').css('visibility', doHide ? 'hidden' : 'visible')
			},
			
			reposition: function()
			{
				for(var n in comp.imageOverlays.overlays)
				{
					var ovl = comp.imageOverlays.overlays[n];
					var scl = ovl.scaled;
					ovl.ele
						.css('z-index', 18)
						.position({
							of: ovl.of,
							my: 'left top',
							at: 'left top',
							offset: scl.left +' '+ scl.top,
							collision: 'none'
						})
						.find('img')
							.width(scl.width)
							.height(scl.height)
					;
				}
			}
		},
		
		enableOptionsDropdowns: function()
		{
			$('select.options_accessories')
				.attr('disabled', false)
		},
		
		initSelect: function(groupId)
		{
			var lastSelect = $('#options_accessories_select_'+groupId);
			if( lastSelect.size() )
				comp.toggleOptionsAccessories(groupId, lastSelect.val());
		},
		
		toggleOptionsAccessories: function(group_id, summaryData)
		{
			var mainOffset, xx, yy, replace_image_x, replace_image_y, xfinal, yfinal, rel_brand_folder, image_url;
			var model_number, sale_price, shipping_price, replace_image, related_item_id, related_group_id, rel_brand_name;
			
			if( ! scSite.itemOptions.isInit )
			{
				$(function()
				{
					jQuery.timeoutRepeat(function()
					{
						scSite.itemOptions.toggleOptionsAccessories(group_id, summaryData);
					}, 200, 6);
				});
			}
			else
			{
				var name="",
					item_id=0,
					model="",
					price=0,
					qty=0,
					shipping=0;
				var dataArr = summaryData.split('|');

				if ( $.isArray(dataArr) && dataArr.length == 12)
				{
					name = dataArr[0];
					item_id = dataArr[1];
					model_number = dataArr[2];
					sale_price = dataArr[3];
					qty = dataArr[4];
					shipping_price = dataArr[5];
					replace_image = dataArr[6];
					replace_image_x = dataArr[7];
					replace_image_y = dataArr[8];
					related_item_id = dataArr[9];
					related_group_id = dataArr[10];
					rel_brand_name = dataArr[11];
				}

				//$('#qty_accessory_' + group_id)		.val( qty );
				$('#qty_accessory_' + group_id)		.val( qty * parseInt( $('#main-item-qty').val() ) ) ;
				$('#shipping_accessory_' + group_id).val( shipping_price );
				$('#price_accessory_' + group_id)	.val( sale_price );
				$('#item_accessory_' + group_id)	.val( name );
				$('#partno_accessory_' + group_id)	.val( item_id + ":" + model_number );

				if( related_group_id != 0 && related_group_id != '0' )
				{
					$('.reqSelClass'+related_group_id).css('display', 'none');
				}

				if( replace_image != '0' && replace_image != '' )
				{
					var mainI = $('#productImageMain').find('.ad-image img').first();
					if ( !mainI.size() )
					{
						var mainI = $('img.main_image');
					}
					
					//alert(replace_image);
					//alert(mainI);
					
					if( mainI.size() )
					{
						var iOD = mainI.data('orig-dimensions');
						if( ! iOD )
						{
							iOD = {width: mainI.width(), height: mainI.height()};
							mainI.data('orig-dimensions', iOD);
						}
						
						var normalWidth = 250;
						var normalHeight = 250;
						
						var xScale = iOD.width / normalWidth;
						var yScale = iOD.height / normalHeight;
						
						var xRel = parseInt(replace_image_x);
						var yRel = parseInt(replace_image_y);
						
						rel_brand_folder = (""+ rel_brand_name).toLowerCase();
						rel_brand_folder = rel_brand_folder.replace(/[^A-Za-z0-9]/, '');
						
						var imgUrl = '/images/personalization/'+ rel_brand_folder +'/'+ replace_image;
						
						// asynchronously grab the overlay image's width and height
						if ( !scSite.browser.isIE7orLess() )
						{
							$.imageDimensions(imgUrl, function(width, height)
							{
								var coverImg = $('#reqSelectionCover'+ related_item_id)
									.addClass('sc-item-image-overlay')
									.html( '<img src="'+ imgUrl +'" />' )
									.css('display', 'block');

								var ioo = coverImg.data('sc-item-option-overlay');
								if( ! ioo )
								{
									ioo = comp.imageOverlays.addOverlay(coverImg, xRel, yRel, width, height, mainI, xScale, yScale);
									coverImg.data('sc-item-option-overlay', ioo);
								}
								comp.imageOverlays.reposition();
							})
						}
					}
				}

				//show personalization if applicable
				//$('.oa_pers_holder').css('display', 'none');

				var oaPersHolder = $('#oa_pers_holder_'+ related_group_id);
				if( oaPersHolder.size() )
				{
					//alert('should be doing this');
					oaPersHolder.css('display', 'none');
					$('.oa_pers_for_item', '#oa_pers_holder_'+ related_group_id)
						.css('display', 'none')
					;

					//hide personalization price fields
					$('.oaPers').val('');

					var availablePerses = $('.oa_pers_item_'+ item_id, '#oa_pers_holder_'+ related_group_id);
					if( availablePerses.size() )
					{
						oaPersHolder.css('display', 'block');
						availablePerses.css('display', 'block');
						
						// Removed[PersonalizationAlert_Item.js]
					}								
				}

				scSite.item.calculatePriceWithCustomization();
			}
		}
	});
});						




////////////////////////////////////////////////////////////////
// Unknown Functions
////////////////////////////////////////////////////////////////

//
// calculatePriceWithCustomization
////////////////////////////////

scSite.item.calculatePriceWithCustomization = function()
{	
	//add up prices of all active Personalizations

	/*
	** Removing 2011-12-06 - DGP - new item page layout forced changes to display and how this logic needs to work
	var allPersPriceDivs = $('div.persPrice');

	var persPriceTotal = 0;
	if( allPersPriceDivs.size() )
	{
		allPersPriceDivs.each(function()
		{
			if( this.style.display != 'none' )
			{
				var divIDsplit = this.id.split("-");
				if (divIDsplit[1] != '' && divIDsplit[1] > 0)
				{
					var thisPersPriceDiv = $('#persPriceHolder-'+ divIDsplit[1] +'-'+ divIDsplit[2]);
					if (thisPersPriceDiv.size())
					{
						persPriceTotal += parseFloat(thisPersPriceDiv.val());
					}
				}

			}
		});
	}*/
	
	var allPersPriceInputs = $('input.persPriceHolder');
	var persPriceTotal = 0;
	if ( allPersPriceInputs.size() )
	{
		allPersPriceInputs.each(function()
		{
			if ( $(this).data('is-active') == 'true' )
			{
				persPriceTotal += parseFloat(  parseInt( $('input.main-item-qty-text').val() ) * $(this).val() );
			}
		});
	}
	

	//add up prices of all active Options
	var totalOptionsPrice = 0;
	$('select.options_accessories').each(function()
	{
		var optionVals = this.value;
		
		var qty_2, sale_price_2, shipping_price_2;
		
		var dataArray = optionVals.split('|');
		if( dataArray.length == 12 )
		{
			sale_price_2 = dataArray[3];
			qty_2 = dataArray[4];
			shipping_price_2 = dataArray[5];
		}
		
		var qty = parseFloat(qty_2);
		var sale_price = parseFloat(sale_price_2);
		var shipping_price = parseFloat(shipping_price_2);
		
		var thisTotal = qty * (sale_price + shipping_price);
		thisTotal = parseFloat( parseInt( $('#main-item-qty').val() ) * thisTotal);
		//alert(thisTotal)
		totalOptionsPrice = totalOptionsPrice + thisTotal;
	});
	
	var currentTotaler = $('#running_total_holder');
	if (currentTotaler.size())
	{
		//var currentTotal = parseFloat(currentTotaler.val());
		var currentQty = parseInt( $('#main-item-qty').val() )
		if ( isNaN( currentQty ) )
		{
			currentQty = 1;
		}
		//var currentTotal = parseFloat( currentQty * $('#main-item-price').val() );
		var currentTotal = parseFloat( currentQty * parseFloat(currentTotaler.val()) );
		var newTotal = $('#running_total_div');
		var shipTotal = parseFloat($('#ship-price-holder').data('ship-price-holder'))
		var subTotal = currentTotal + persPriceTotal + totalOptionsPrice;
		if ( scSite.item.itemQuantityFlatrateShipping.detectFreeShipping( subTotal ) )
		{
			var finalTotal = subTotal;
		} else {
			var finalTotal = currentTotal + persPriceTotal + totalOptionsPrice + shipTotal;
		}
		finalTotal = finalTotal.toFixed(2);
		newTotal.html('$'+ $.CommaFormatted(finalTotal));
	}
}





//
// placeSpecialCaseOverlay
////////////////////////////////
//
// ?WhereIsThisUsed?
// Relocated[placeSpecialCaseOverlay] from "html\generic\Templates\items.html"
//

function placeSpecialCaseOverlay( e, item_id )
{
	if (item_id && item_id && item_id != '')
	{
		var thumb = $('#item_thumb_'+ item_id.id);
		var overlay = $('#thumb_overlay_'+ item_id.id);
		var offset = thumb.offset();
		if( thumb.size() && overlay.size() )
		{
			overlay.css({position:'absolute', display: 'inline', left: offset.left, top: offset.top});
		}
	}
}


scSite.item.itemQuantityFlatrateShipping = scSite.addComponent('itemQuantityFlatrateShipping', function(comp)
{
	$.extend(comp,
	{
		minimumPrice: 249,
		flatratePrice: 6.95,
		init: function()
		{
			// copy quantity changes to other textbox & main-item-qty form input
			$('input.main-item-qty-text').live('keyup', function(ev) {
				var self = $(this)

				$('input.main-item-qty-text, #main-item-qty').val( self.val() )
				var regTest = /[\D]/i;
				var regTestZero = /^0+$/i;
				if ( regTest.test( self.val() ) || regTestZero.test( self.val() ) )
				{
					$('input.main-item-qty-text').qtip('show')
					$('#main-item-qty').val( 1 )
				} else {
					$('input.main-item-qty-text').qtip('hide')
				}
				
				$('select.options_accessories').each( function() {
					scSite.itemOptions.initSelect( $(this).data('rig-id') )
				})
				
				scSite.item.calculatePriceWithCustomization();
			});
			
			// check to make sure textboxes aren't empty, and if they are, reset to 1
			$('input.main-item-qty-text').live('blur', function() {
				var valSeen = 0;
				$('input.main-item-qty-text').each( function(){
					if ( $(this).val() != '' )
					{
						valSeen = $(this).val()
					}
				})
				if ( valSeen == 0 )
				{
					$('input.main-item-qty-text, #main-item-qty').val( 1 )
					$('input.main-item-qty-text').qtip('hide')
				}
				
				$('select.options_accessories').each( function() {
					scSite.itemOptions.initSelect( $(this).data('rig-id') )
				})
				
				scSite.item.calculatePriceWithCustomization();
			});
			
			$('input.main-item-qty-text').qtip({
				content:"Please enter numbers greater than zero only.",
				style:
				{
					classes: 'ui-tooltip-error'
				},
				position: 
				{
					my: 'right bottom',
					at: 'left top'
				},
				show:
				{
					event: false
				},
				hide:
				{
					delay: 5000
				}
			});	
		},
		detectFreeShipping: function( totalPrice )
		{
			if ( $('#ship-price-holder').data('shipping-override') == 'FlatRate' )
			{
				if ( totalPrice >= comp.minimumPrice )
				{
					comp.showFreeShipping();
					return true;
				} else if ( totalPrice < comp.minimumPrice ) {
					comp.resetToOriginal();
					return false;
				}
			}			
			return false;
		},
		resetToOriginal: function()
		{
			if ( $('#ship-price-holder').data('shipping-override') == 'FlatRate' )
			{
				if ( $('#main-item-price').val() < comp.minimumPrice )
				{
					// only hide if the main item's price is < 249
					$('.shippingpricetext').hide();
					$('.shipping-flatrate').show();
				}
				$('#main-item-shipping').val( $('#main-item-shipping').data('orig-price') );
				$('#ship-price-holder').data( 'ship-price-holder', $('#ship-price-holder').data('ship-price-orig') );
			}
		},
		showFreeShipping: function()
		{
			$('.shippingpricetext').show();
			$('.shipping-flatrate').hide();
		}
	});
});
