//**********************************
//	Class: eBook Commerce Module
//**********************************
$.commerceModule = {
	init : function() {
		var self = this;
		this.settings = {
			activeCssClass: "active",
			tabSelector: "#cdsPDP #commerceModule .tabs li a",
			sectionSelector: "#cdsPDP #commerceModule .sections .",
			allSectionsSelector: "#cdsPDP #commerceModule .sections .section",
			zipCodeTextboxSelector: "#cdsPDP #commerceModule .sections .inStore input",
			findBtnSelector: "#cdsPDP #commerceModule .sections .inStore .btnFind",
			zipCodeErrorSelector: "#cdsPDP #commerceModule .sections .inStore .error",
			storeResultsSelector: "#cdsPDP #commerceModule .storeResults",
			defaultZipText: "Enter zip code"
		};
		
		$(self.settings.tabSelector).click(function(e) { self.toggleSection(this); e.preventDefault(); });
		$(self.settings.findBtnSelector).click(function(e) { self.findStores(this); e.preventDefault(); });
		
		if ($(self.settings.zipCodeTextboxSelector).val() == "") {
			$(self.settings.zipCodeTextboxSelector).val(self.settings.defaultZipText);
		}

		$(self.settings.zipCodeTextboxSelector)
		.keypress(function(e) { if(e.keyCode == 13) { self.findStores(this); e.preventDefault(); } })
		.focus(function() { if(this.value == self.settings.defaultZipText) { this.value = ""; } })
		.blur(function() { if(this.value == "") { this.value = self.settings.defaultZipText; } });
	},
	
	toggleSection : function(link) {
		var section = $(link).parent().attr("class");
		
		$(this.settings.tabSelector).removeClass(this.settings.activeCssClass);
		$(this.settings.allSectionsSelector).hide();
		$(link).addClass(this.settings.activeCssClass);
		$(this.settings.sectionSelector + section).show();
		
		this.resetTabs();
	},
	
	resetTabs : function() {
		$(this.settings.zipCodeErrorSelector).hide();
		$(this.settings.storeResultsSelector).hide();
		
		 if (!this.validateZipCode($(this.settings.zipCodeTextboxSelector).val())) {
			$(this.settings.zipCodeTextboxSelector).val(this.settings.defaultZipText);
		 }
	},
	
	findStores : function() {
		var 
			zip = $(this.settings.zipCodeTextboxSelector).val(),
			self = this;
		
		if (this.validateZipCode(zip)) {
			/*
			ui.request({
				baseURL: "http://store-locator.barnesandnoble.com/storelocator/stores.aspx?",		   
				parameters: "uiaction=getstores&zip=" + zip + "&sze=3&device=y",
				callback: {
					name: "cbf", 
					value: "$.commerceModule.processStoreInfo"
				}
			});
			*/
			document.location = "/nook/instore/?zipcode=" + zip;
		} else {
			$(this.settings.zipCodeErrorSelector).show();
			//$(this.settings.storeResultsSelector).hide();
		}
	},
	
	processStoreInfo: function(response) {
		//$.commerceModule.populateResults(response, $(this.settings.zipCodeTextboxSelector).val());
	},
	
	populateResults : function(response, zip){
		/*
		var 
			container 	= $(this.settings.storeResultsSelector),
			tbody 		= container.find("tbody"),
			moreLink	= container.find("div.more a"),	
			trArr 		= [],
			sUrl		= "http://store-locator.barnesandnoble.com/",
			stores 		= response.Request.Stores;
			
		for (var i=0, l = stores.length; i < l; i++){
			trArr.push('<tr><td><a href="', sUrl, 'store/', stores[i].StoreNumber, '">', stores[i].Nickname, '</a></td>');
			trArr.push('<td><div class="x">No</div></td>'); //all no for now since not released and no data returned
			
			if (/Barnes/.test(stores[i].StoreCorporateName)){ //BDalton doesn't have store demos
				trArr.push('<td><div class="check">Yes</div></td>');
			}
			else {
				trArr.push('<td><div class="x">No</div></td>');
			}
			trArr.push('</tr>');
		}
		
		tbody.html(trArr.join(''));
		moreLink.attr("href", "/nook/storelocator/?zipcode=" + zip)
		$(this.settings.zipCodeErrorSelector).hide();		
		container.show();
		*/
	},
	
	validateZipCode : function(value) {
		var zipRegEx = /^\d{5}$/;
		
		return zipRegEx.test(value);
	}
}


// INITIALIZE STUFF
$(function() {
	$.commerceModule.init();	   
	if($("#shareLink").get(0) != null) {
		generateShareAnyLink(document.getElementById("shareLink"));
	}
	
	// TRACKING
		$("#shareLink .shareLink a").click(function(e) {
			var $target = $(e.target);
			var shareText = $target.parents(".shareLink").find(".shareLinkText");
			var type = $.trim(shareText.html());
			shareTrack(type);		
		});
		$("#printLink").click(function() { 
			shareTrack("Print");	
		});
		$("#tellafriendLink").click(function() { 
			shareTrack("Email");	
		});
		
		function shareTrack(type) {
			var elementID = "nook: Share: " + type;
			var elementCategoryID = "NOOK: UTILITY BAR"
			//console.log("elementID: ", elementID);
			cmCreatePageElementTag(elementID, elementCategoryID);
		}
		
		/*$("#cdsPDP .manualClick").click(function(e) {
			e.preventDefault(e);
			var $target = $(e.target);
			var name = $target.attr("name");
			//cmCreateManualPageviewTag(pageId, categoryId, "XXX", pageURL)
			//cmCreateManualPageviewTag(pageId, "NOOK: PDF", "XXX", pageURL)
			cmCreateManualPageviewTag("Livescribe PDF: The Scarlet Letter","promotions:livescribe",$(e.target).attr("href"), document.location.href)
			
			
			//cmCreateManualLinkClickTag(document.location, name);
		});*/
	// END TRACKING 

	
	var $container = $("#cdsPDP");
	
	if($container.hasClass("accessories")) {
		if($container.hasClass("upsell")) {
			var cbm = new $.CheckboxManager();
			$("#cdsPDP input").each(function(index, itm) {
				cbm.addCheckbox($(itm));
			});	
			
			$("#cdsPDP").delegate("click",{
				".contributor" : function(e){
					e.preventDefault();
					cbm.toggle($(e.target).parents("li.product").find(":checkbox"));
				},
				"img" : function(e){
					e.preventDefault();
					cbm.toggle($(e.target).parents("li.product").find(":checkbox"));
				}
			});
			
			var $accessoriesForm = $("#accessoriesForm");
			var $hiddenFields = $("#hiddenFields");
			var where = "confirm";  // fullCart || confirm
			
			$("a.btn_checkout").click(function(e) {
				e.preventDefault();			
				
				var fields = '<input type="hidden" name="stage" value="'+where+'" />';
				fields += '<input type="hidden" name="uiAction" value="multAddToCart" />';
				
				var $checkedInputs = $("#cdsPDP input:checked");
				if($checkedInputs.length > 0) {
					$checkedInputs.each(function(index, itm) {
						var vals = $(itm).attr("name").split("_");
						var ean = vals[0];
						var productCode = vals[1];
						
						var $product = $(itm).parents(".product");
						var title = $product.find(".contributor").html() || $product.find(".title").html();
						var price = $product.find(".listPrice").html();
						var catId = $product.find(".categoryId").html() || "777aa";
						
						
						// ADD TRACKING CALL TO TRACKING ARRAY
						cmCreateShopAction5Tag(ean, title, "1", price, catId);
						//console.log(ean, title, "1", price, catId);
						
						fields += '<input type="hidden" name="ean'+index+'" value="'+ean+'" />';
						fields += '<input type="hidden" name="productCode'+index+'" value="'+productCode+'" />';
					});
					
					$hiddenFields.html("");
					$hiddenFields.html(fields);
					
					// to make sure they don't get added to the querystring since we have to keep it small as a get request
					$checkedInputs.remove();		
					
					// SEND TRACKING DATA
					cmDisplayShop5s();
					
					$accessoriesForm.submit();
				} else {
					document.location = e.target.href;
					//$accessoriesForm.attr("action", e.target.href)
					//$accessoriesForm.submit();
				}
				
			});		

			// Warranty Popup
			var warrantyDialog = new $.Dialog({
				closeButton : "X", 
				additionalClass : "warranty_dialog",
				yAlign : "topline",
				xAlign : "innerLeft",
				yOffset: -100,
				xOffset: -35,
				showCallback: function() {
					$(".n_dialog_content span").eq(1).jScrollPane({
						scrollbarWidth:15,
						showArrows:true
					})
				}
				//initCallback: function() {}
			});
			
			
			$(".warranty_popup").click(function(e) {
				e.preventDefault();
				
				warrantyDialog.setContent($(e.target).parents("#warranty").find("p.full_description").html());
				warrantyDialog.setAnchor($(e.target)).show();
			});
			
		}
		else {
			$.QuickViewManager.init();
		}
		
		if($('.ebook-carousel').get(0) != null) {
			$('.ebook-carousel').jcarousel({
				scroll: 5,	
				animation: 1500,
				buttonPrevHTML: null,
				buttonNextHTML: null
			});
			
			//hide quickview dialog if present
			$(document).delegate("click",{
				'.jcarousel-prev' : function(){
					if ($.QuickViewDialog){
						$.QuickViewDialog.hide();
					}
				},
				'.jcarousel-next' : function(){
					if ($.QuickViewDialog){
						$.QuickViewDialog.hide();
					}
				}
			});
			
		}
	} else if($container.hasClass("storelocator")) {
		$("#commerceModule li.inStore a").click();
	} else if($container.hasClass("mediaResources")) {
		$("#cdsPDP .embedLink").click(function(e) {
			e.preventDefault(e);
			$target = $(e.target);
			
			var mediaKitDialog = new $.Dialog({
				closeButton : "X", 
				additionalClass : "learn_more_dialog",
				yAlign : "middle",
				xAlign : "middle",
				xOffset : 0
			});
			
			mediaKitDialog.setContent($(e.target).parents("p").find("span.embedCode").html());
			mediaKitDialog.setAnchor($(e.target)).show();
			
			var $textarea = $(".n_dialog_content textarea");
			$textarea.focus()
			$textarea.select()
		});
	} else if($container.hasClass("support")) {
		
		$("#cdsPDP").delegate("click", {
			".q": function(e) {
				e.preventDefault();
				var $target = $(e.target);
				var $dd = $target.parent().next();
				if($dd.get(0).style.display == "block") {
					$dd.slideUp(200);
					$dd.find(".x").hide();
				} else {
					$dd.slideDown(500, function() {
					$dd.find(".x").show();																		
					});
				}
			},
			".x": function(e) {
				e.preventDefault();
				var $target = $(e.target);
				$target.parent().slideUp(200);
				$target.hide();
			}
		});
		
		var discussions = $("#discussions");
		if (discussions.get(0)){
		
			$.ajax({
				url : "/nook/inc/discussionCache.asp",
				type : "post",
				dataType : "text",
				data : {
					url: "http://bookclubs.barnesandnoble.com/bn/rss/board",
					board : "eBooks_Help",
					count : 3
				},
				success : function(response){
					//ie didn't like the xml from jquery so response is a string
					//and parsed the old fashion way
					var 
						xml = $.StringToXML(response).documentElement,
						link = xml.getElementsByTagName("link")[0].firstChild.nodeValue,
						items = xml.getElementsByTagName("item");
						
					for (var i=0; i < items.length; i++){
						var 
							item = items[i],
							title = item.getElementsByTagName("title")[0].firstChild.nodeValue,
							desc = item.getElementsByTagName("description")[0].firstChild.nodeValue;
						
						discussions.append("<h4>" + title + "</h4><p>" + $.StripTags($.Truncate(desc, 100, "...")) + "</p>")
					}
					discussions.append('<p><a href="'+ link + '">See all Discussions</a></p>');
				}
			});
		}
	} 
	else {
		var _counter = 0;
		if($('.accessories-carousel').get(0) != null) {
			$('.accessories-carousel').jcarousel({
				scroll: 6,	
				buttonPrevHTML: null,
				buttonNextHTML: null
			});
		}
		var eCarousels = $('#browseAccordion .ebook-carousel');
		if(eCarousels.get(0) != null) {
			$('.ebook-carousel').jcarousel({
				scroll: 5,	
				buttonPrevHTML: null,
				buttonNextHTML: null,
				initCallback : function(){
					_counter++;
					if (_counter == eCarousels.length){
						setTimeout(function(){
							if($('#browseAccordion').get(0) != null) {
								$('#browseAccordion').accordion({ 
									event: 'click', 
									active: '.selected', 
									selectedClass: 'active', 
									header: "dt"
								});
								// ACCORDION TRACKING								
								$("#browseAccordion dt a").click(function(e) {
									var trackingID = $(e.target).html();
									cmCreatePageElementTag(trackingID, "Nook: Carousel");
								});
								// END ACCORDION TRACKING
							}
						},500);
					}
				}
			});
		}
		
		if ($container.hasClass('home')){
			var 
				feedContainer 	= $("#knowMore div.feed p"),
				feed	 		= $("#twitterFeedHolder");

			if (feedContainer.get(0)){
				feed.css('display','none');
				feedContainer.append(feed.html());
				
				var					
					text = feedContainer.find(".text"),
					date = feedContainer.find(".date"),
					urlFormat = $.FormatUrlToLink(text.html()),
					dateFormat = new Date(date.html());
					
				if (isNaN(dateFormat)){ //ie doesn't like the date format twitter returns
					dateFormat = $.FormatIeTwitterDate(date.html());
				}				
				
				text.html(urlFormat);
				date.html(" "+dateFormat.toDateString());
			}
		}
	}
	
	//learn more popups
	
	var learnMoreDialog = new $.Dialog({
			closeButton : "X", 
			additionalClass : "learn_more_dialog",
			yAlign : "middle",
			xAlign : "middle",
			xOffset : 0
		});
	
	$(document).delegate("click",{
		".learn_more" : function(e){
			e.preventDefault();
			
			var 
				$tar = $(e.target),
				$tout = $tar.parents(".tout");
			
			if ($tout != null){
				
				var 
					title = "",
					desc = $tout.find("p.full_description").html(),
					content = [];
					
				if (!$tar.hasClass("no_title")){
					title = '<h4>' + $tout.find("h2").html() + '</h4>';
				}
				
				content.push(title, '<p>', desc, '</p>');
				learnMoreDialog.setContent(content.join('')).setAnchor($tar).show();
			}
		}
	});
});
(function($){
	$.FormatUrlToLink = function(str){
		var urlRegExp	= /https?:\/\/[^ ]+/ig;
		var matches		= null;
		(str) ? str.match(urlRegExp) : null;
		
		if (matches != null){
			for (var i = 0;i<matches.length;i++){
				var reg = new RegExp(matches[i]);
				str = str.replace(reg, '<a href="'+matches[i]+'">'+matches[i]+'</a>');
			}
		}
		return str;
	};
	
	$.FormatIeTwitterDate = function(str){
		var
			year = str.substr(str.length - 4, 4),
			newStr = str.substr(0,20) + year + " +0000";
		
		return new Date(newStr);
	};
	
	$.Truncate = function(str,len,suffix){
		var suff = suffix || "";
		
		if (str.length > len){
			str = str.substr(0, len) + suff;
		}
		
		return str;
	};
	
	$.StripTags = function(str){
		return str.replace(/(<|\&lt;)\/?\w+\/?(>|\&gt;)/gi,"");
	};
	
	$.StringToXML = function(str){
		var xmlDoc;
		try //Internet Explorer
		{
		  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		  xmlDoc.async="false";
		  xmlDoc.loadXML(str);
		}
		catch(e)
		{
		  parser=new DOMParser();
		  xmlDoc=parser.parseFromString(str,"text/xml");
		}
		
		return xmlDoc;
	};
})(jQuery);
(function($){
	$.DropShadowBg = function($element,$container,addClass){
		
		var 
			cont	= $('<div id="dropShadowContainer" class="'+addClass+'"></div>'),
			top		= $('<div class="top"></div>'),
			bottom 	= $('<div class="bottom"></div>'),
			offsets = $element.offset();
		
		cont.append(top);
		cont.append(bottom);
		$container.append(cont);
		
		adjust();

		this.adjust = function(){
			adjust();
		};
		
		this.destroy = function(){
			cont.remove();
		};
		
		function adjust(){
			cont.css({
				width : $element.outerWidth(),
				height : $element.outerHeight(),
				top : offsets.top,
				left : offsets.left,
				zIndex : $element.css('zIndex') - 1
			});
			
			bottom.height(7);
			top.height($element.outerHeight() - bottom.height());
		}
	};
})(jQuery);
(function($){

	var $win = $(window);
	$.Dialogs = [];
	
	$.Dialog = function(params){
		this.settings = $.extend({},this._defaults,params);
		this.anchor = this.settings.anchor;
		this.wrapper = $('<div id="dialogContainer_'+$.Dialogs.length+'" class="n_dialog"><div class="n_dialog_content"></div></div>');			
		this.content = this.wrapper.children(".n_dialog_content");
		this.container = this.settings.container || $(document.body);
		
		if (this.settings.additionalClass){
			this.wrapper.addClass(this.settings.additionalClass);
		}
		
		this.settings.initCallback();
		$.Dialogs.push(this);
	};
	
	$.Dialog.prototype = {
		
		//Public
		show : function(){
			this.container.append(this.wrapper);
			if (this.dropShadow) this.dropShadow.destroy();
			
			this._bindCloseButton();
			this._position();
			if (this.settings.animate){
				this.settings.animateIn();
			}
			else {
				this.wrapper.addClass("active_dialog");
				this.dropShadow = new $.DropShadowBg(this.wrapper, this.container, this.settings.additionalClass);
				this.settings.showCallback();
			}
			return this;
		},
		
		hide : function(){
			if (this.settings.animate){
				this.animateOut();
			}
			else {
				this.wrapper.removeClass("active_dialog");
				if (this.dropShadow){
					this.dropShadow.destroy();
				}
				this.settings.hideCallback();
			}
			return this;
		},
		
		setContent : function(content){
			this.content.html(content);
			return this;
		},
		
		setAnchor : function(anchor){
			this.anchor = anchor;
			return this;
		},
		
		//Private jazz
		_position : function(){
			var
				self		= this,
				aOffset 	= this.anchor ? this.anchor.offset() : {left:0, top:0},
				aWidth		= this.anchor ? this.anchor.width() : 0,
				aHeight		= this.anchor ? this.anchor.height() : 0,
				cWidth		= this.wrapper.outerWidth(),
				cHeight		= this.wrapper.outerHeight(),
				wWidth		= $win.width(),
				wHeight		= $win.height(),
				wScLeft		= $win.scrollLeft(),
				wScTop		= $win.scrollTop(),
				leftEdge	= wScLeft + self.settings.windowPadding,
				rightEdge	= wScLeft + wWidth + self.settings.windowPadding,
				topEdge		= wScTop + self.settings.windowPadding,
				bottomEdge	= wScTop + wHeight + self.settings.windowPadding,
				left		= aOffset.left - cWidth + self.settings.xOffset,
				right		= aOffset.left + aWidth + cWidth + self.settings.xOffset,
				top			= aOffset.top - cHeight + self.settings.yOffset,
				bottom		= aOffset.top + aHeight + cHeight + self.settings.yOffset,
				xFlipClass	= "",
				yFlipClass	= "",
				finalLeft, 
				finalTop;
			
			this.wrapper.removeClass(this.settings.flippedClass + "_x").removeClass(this.settings.flippedClass + "_y");
			
			//position x
			switch (this.settings.xAlign){
				case "outerLeft" : 
				
					if (left >= leftEdge || right >= rightEdge) finalLeft = left + cWidth;
					else {finalLeft = right - cWidth - this.settings.xOffset*2; xFlipClass = this.settings.flippedClass + "_x";}
					break;
				
				case "outerRight" : 
					
					if (right <= rightEdge || left <= leftEdge) finalLeft = right - cWidth;
					else {finalLeft = left + cWidth - this.settings.xOffset*2; xFlipClass = this.settings.flippedClass + "_x";}
					break;
				
				case "innerLeft" : 
				
					if (left + aWidth >= leftEdge || right - aWidth >= rightEdge) finalLeft = left + aWidth;
					else {finalLeft = right - cWidth - aWidth - this.settings.xOffset*2; xFlipClass = this.settings.flippedClass + "_x";}
					break;
				
				case "innerRight" : 
					
					if (right - aWidth <= rightEdge || left + aWidth <= leftEdge) finalLeft = right - cWidth - aWidth;
					else {finalLeft = left + aWidth - this.settings.xOffset*2; xFlipClass = this.settings.flippedClass + "_x";}
					break;
				
				default :
					
					var 
						tempLeft = aOffset.left + (aWidth / 2) - (cWidth / 2) + this.settings.xOffset,
						tempRight = tempLeft + cWidth;
						
					if (tempLeft < leftEdge) finalLeft = tempLeft - (tempLeft - leftEdge) + self.settings.windowPadding;
					else if (tempRight > rightEdge) finalLeft = tempLeft - (tempRight - rightEdge) - self.settings.windowPadding;
					else finalLeft = tempLeft;
					break;
			}
			
			//position y
			switch (this.settings.yAlign){
				
				case "top" : 
					
					if (top >= topEdge || bottom >= bottomEdge) finalTop = top;
					else finalTop = bottom - cHeight;
					break;
					
				case "bottom" :
				
					if (bottom <= bottomEdge || top <= topEdge) finalTop = bottom - cHeight;
					else finalTop = top;
					break;
					
				case "topline" : 
				
					finalTop = aOffset.top + this.settings.yOffset;
					break;
					
				case "baseline" : 

					finalTop = aOffset.top + aHeight - cHeight + this.settings.yOffset;
					break;
				
				default :
					
					var
						tempTop = aOffset.top + (aHeight / 2) - (cHeight / 2) + this.settings.yOffset,
						tempBottom = tempTop + cHeight;
						
					if (tempTop < topEdge) finalTop = tempTop - (tempTop - topEdge) + self.settings.windowPadding;
					else if (tempBottom > bottomEdge) finalTop = tempTop - (tempBottom - bottomEdge) - self.settings.windowPadding;
					else finalTop = tempTop;
					break;
			}
			
			this.wrapper.css({
				left : finalLeft,
				top : finalTop
			}).addClass(xFlipClass).addClass(yFlipClass);
		},
		
		_animateIn : function(){
			
		},
		
		_animateOut : function(){
		
		},
		
		_bindCloseButton : function(){
			var self = this;
			this._unbindCloseButton();
			if (this.settings.closeButton && this.settings.closeButton.length){
				this.closeButton = $('<a href="javascript:void(0);" class="close_button">'+this.settings.closeButton+'</a>');
				this.wrapper.append(this.closeButton);
				this.wrapper.children("a.close_button").click(function(e){
					e.preventDefault();
					self.hide();
				});
			}
		},	
		
		_unbindCloseButton : function(){
			if (this.closeButton){
				this.closeButton.unbind("click");
				this.closeButton.remove();
				this.closeButton = 0;
			}
		},
		
		_destroy : function(){
			this.wrapper.remove();
		},
		
		_defaults : {
			container : 0,
			anchor : 0,
			xAlign : "innerRight",
			yAlign : "top",
			xOffset : 0,
			yOffset : 0,
			windowPadding : 10,
			closeButton : "close",
			flippedClass : "dialog_flipped",
			additionalClass : 0,
			animate : 0,
			animateSpeed : 300,
			initCallback : function(){},
			showCallback : function(){},
			hideCallback : function(){}
		}
	};
	
})(jQuery);

(function($){
	$.QuickViewDialog = 0;
	$.QuickViewManager = {
		
		init : function(){	
			//DOM ready
			$(function(){
				
				$("#cdsPDP li.product").each(function(){
					new $.QuickViewItem($(this));
				});
				
				$(document).delegate("click", {
					"#quickView": function(e) {
						e.preventDefault();
						
						var product = $(e.target).parent('.product');
							
						if (product.data("QvItem") != null){
							product.data("QvItem").show();
						}
					}	
				});

			});
		}
		
		
	};
	
	$.QuickViewItem = function(item, params){
		this.settings = $.extend({},this._defaults,params);
		this.item = item;
		
		var self = this;
			
		if (!$.QuickViewDialog){
			$.QuickViewDialog = new $.Dialog(this._dialogOpts);
		}
		
		this.item.hover(function(){
		
			var 
				$this 		= $(this),
				btnWidth 	= 98,
				btnHeight	= 35,
				$img 		= $this.find("img");
			
			$this.prepend('<a href="#" id="quickView"></a>');
			
			$("#quickView").css({
				left: (($img.width() - btnWidth) / 2), 
				//top: ($img.height() - btnHeight) / 2
				top: 80
			});				
			
		},function(){
		
			$("#quickView").remove();
			
		}).data("QvItem",this);
	};
	$.QuickViewItem.prototype = {
	
		show : function(){
			this._populate();
			$.QuickViewDialog.setAnchor(this.item);
			$.QuickViewDialog.show();
			this._alignHeights();
		},
		
		_populate : function(){
			
			var 
				item 	= this.item,
				contrib	= item.find(".contributor").html(),
				title	= item.find(".title").html(),
				price	= item.find(".listPrice").html(),
				desc	= item.find(".description").html(),
				pdpUrl	= item.find(".product_image a").attr("href"),
				heading = contrib || title,
				subhead = (contrib == null) ? "" : title,
				content = [
							'<div class="qv_display"></div>',
							'<div class="qv_info">',
							'<h4>' , heading , '</h4>',
							'<em>' , subhead , '</em>',
							'<p class="listPrice">' , price , '</p>',
							'<p class="description">' , $.Truncate(desc, 300, "...") , '</p>',
							'<a class="details" href="' , pdpUrl , '">See details</a>',
							this._createAddToCart() , this._createAddToWishList(),
							'</div><div style="clear:both;"></div>'
						];
			
			$.QuickViewDialog.setContent(content.join(''));
			
			this._createImageRotator($.QuickViewDialog.content.children('.qv_display'));
			
		},
		
		//externalize into separate class if needed elsewhere
		_createImageRotator : function(context){
			var 
				self 			= this,
				regularImage 	= this.item.find(".regular_image > span").get(0),
				images			= this.item.find('.image_container'),
				mainUrls 		= images.find('> .images > span'),
				thumbUrls 		= images.find('> .thumbs > span'),
				mainStr 		= ['<div class="rotator_mains">'],
				thumbStr		= ['<div class="rotator_thumbs">'],
				container		= $('<div class="rotator_container"></div>'),
				maxHeight		= 190,
				url 			= this.item.find('.product_image a').attr("href"),
				id				= "rotatorImage";
			
			if (mainUrls.length == 0 || thumbUrls.length < 2){
				var img = new Image();
				img.src = regularImage.innerHTML + "?" + Math.random(1000000);
				
				img.onload = function(){
					var 
						dims = $.ImageResizer(img, 185, 195);
						ele = document.getElementById(id);

						ele.height = dims.height;
						ele.style.display = "inline";
				};
				
				container.append('<div class="rotator_mains"><a href="'+url+'"><img id="'+ id +'" class="active" src="'+ regularImage.innerHTML + '" style="display:none;" /></a></div>');
				context.append(container);
			}
			else {
				$(mainUrls).each(function(i){
					if (i < 2){
						var 
							img 	= new Image(),
							thumb 	= new Image(),
							_id 	= id + "_" + i;
						
						//random qs so the onload event always fires
						img.src = this.innerHTML + "?" + Math.random(1000000);
						thumb.src = thumbUrls.eq(i).html() + "?" + Math.random(1000000);

						img.onload = function(){
							var 
								dims = $.ImageResizer(img, 185, 195),
								ele = document.getElementById(_id);
								
							ele.height = dims.height;

							if (i==0){
								ele.className += " active";
							}
							else if (i == mainUrls.length){
								self._alignHeights()
							}
						};
						
						thumb.onload = function(){
							var 
								dims = $.ImageResizer(thumb, 0, 45),
								ele = document.getElementById(_id + "_thumb");
								
							ele.height = dims.height;
							ele.style.display = "inline";
							
						};
						
						mainStr.push('<a href="',url,'"><img id="', _id,'" src="', this.innerHTML, '" /></a>');
						thumbStr.push('<a href="#"><img id="', _id,'_thumb" src="', thumbUrls.eq(i).html(), '" style="display:none;" /></a>');
					}
				});
				
				mainStr.push("</div>");
				thumbStr.push("</div>");
				
				container.append(mainStr.join(''));
				container.append(thumbStr.join(''));
				context.append(container);
				
				container.find(".rotator_mains img").each(function(){
					if (maxHeight < this.height){
						maxHeight = this.height;
					}
				});
				
				container.find(".rotator_thumbs a").each(function(i){
					$(this).click(function(e){
						e.preventDefault();
						
						container.find(".rotator_mains img").each(function(j){
							if (j == i){
								$(this).addClass('active');
							}
							else {
								$(this).removeClass('active');
							}
						});
					});
				});
			}
		},
		
		_createAddToCart : function(){
			var 
				id = this.item.find(".pid").html().split('_'),
				orderType = this.item.find(".orderType").html(),
				inputs;
				
			//additional array item means already in cart
			if (id[2]){
				
			}
			else {
				if(orderType == "add") {
					inputs 	= [ 
						'<input type="hidden" name="ean" value="', id[0], '" />',
						'<input type="hidden" name="productcode" value="', id[1], '" />',
						'<input type="image" alt="Add To Cart" src="', this.settings.addToCart.btnSrc, '" />'
					];
				} else if(orderType == "pre") {
					inputs 	= [ 
						'<input type="hidden" name="ean" value="', id[0], '" />',
						'<input type="hidden" name="productcode" value="', id[1], '" />',
						'<input type="image" alt="Add To Cart" src="', this.settings.preOrder.btnSrc, '" />'
					];
				}
			}
			
			if(orderType == "add") {
				return '<form action="'+this.settings.addToCart.action+'" method="post">' + inputs.join('') + '</form>';
			} else if(orderType == "pre") {
				return '<form action="'+this.settings.preOrder.action+'" method="post">' + inputs.join('') + '</form>';				
			} else {
				return '';	
			}
		},
		
		_createAddToWishList : function(){
			
			var 
				meta = this.item.find(".wishlist"),
				orderType = this.item.find(".orderType").html(),
				link = "";
			
			if (meta.get(0)){
				if(orderType == "none") {
					link = '<a class="wishlist" href="' + meta.html() + '" style="float: right; margin-top: 20px;">Add to Wish List</a>';
				} else {
					link = '<a class="wishlist" href="' + meta.html() + '">Add to Wish List</a>';
				}
			}
			
			return link;
		},
		
		_alignHeights : function(){
			
			var 
				halves 	= $.QuickViewDialog.content.children('div'),
				h0		= halves.eq(0).height(),
				h1		= halves.eq(1).height();
			
			if ( h0 > h1 ){
				halves.eq(1).height(h0);
			}
			else {
				halves.eq(0).height(h1);
			}
			
			$.QuickViewDialog.dropShadow.adjust();
		},
		
		_dialogOpts : {
			xOffset : -40,
			yOffset : -40,
			yAlign : "topline",
			flippedClass : "qv_dialog_flipped",
			additionalClass : "qv_dialog",
			closeButton : "X"
		},
		
		_defaults : {
			addToCart : {
				action : "http://cart2.barnesandnoble.com/Shop/xt_manage_cart.asp?",
				btnSrc : "http://images.barnesandnoble.com/pImages/bravo/whiteout/btn_addToCart.png"
			},
			preOrder: {
				action: "http://cart2.barnesandnoble.com/Shop/xt_manage_cart.asp?",
				btnSrc: "http://images.barnesandnoble.com/pImages/bravo/whiteout/btn_preorder.png"
			}
		}		
	}
	
	$.ImageResizer = function(image, maxWidth, maxHeight){
		
		var
			width = image.width,
			height = image.height,
			div;
		
		if ((width >= height && maxWidth != 0) || maxHeight == 0){
			image.width = maxWidth;
			image.height = (Math.abs(width - Math.abs(width - maxWidth))/width) * height;
		}
		else {
			image.height = maxHeight;
			image.width = (Math.abs(height-Math.abs(height - maxHeight))/height) * width;
		}
		
		return {width : image.width, height : image.height};
	};
	
})(jQuery);
if ($.jcarousel){
	$.jcarousel.prototype.reload = function(){};
}

//Home page flash functionality
function swfIntroComplete(){
	setTimeout(function(){
		$("#navModule, #commerceModule, #utilityBar").fadeIn(400);
	}, 500);
	
	//check qs for loading video tutorial initially
	var 
		qs		= window.location.search.substr(1),
		qsPairs = qs.split("&");
	
	for (var i = 0; i < qsPairs.length; i++){
		var pair = qsPairs[i].split("=");
		
		if (pair[0] == "tutorial" && pair[1] == "on"){
			var movie = document.getElementById("bravoHero");

			if (movie && typeof(movie.loadVideoTour) == "function"){
				movie.loadVideoTour();
			}
			
			break;
		}
	}
}
