	(function($){
	$.fn.jTruncate = function(options) {
	   
		var defaults = {
			length: 25,
			minTrail: 5,
			moreText: "",
			lessText: "",
			ellipsisText: "&hellip;",
			moreAni: "",
			lessAni: ""
		};
		
		var options = $.extend(defaults, options);
	   
		return this.each(function() {
			obj = $(this);
			var body = obj.html();
			
			if(body.length > options.length + options.minTrail) {
				var splitLocation = body.indexOf(' ', options.length);
				if(splitLocation != -1) {
					// truncate tip
					var splitLocation = body.indexOf(' ', options.length);
					var str1 = body.substring(0, splitLocation);
					var str2 = body.substring(splitLocation, body.length - 1);
					obj.html(str1 + '<span class="truncate_ellipsis">' + options.ellipsisText + '</span>');
					//obj.find('.truncate_more').css("display", "none");
					
					// insert more link
					//obj.append(
						//'<div class="clearboth">' +
						//	'<a href="#" class="truncate_more_link">' + options.moreText + '</a>' +
						//'</div>'
					//);

					// set onclick event for more/less link
					var moreLink = $('.truncate_more_link', obj);
					var moreContent = $('.truncate_more', obj);
					var ellipsis = $('.truncate_ellipsis', obj);
					moreLink.click(function() {
						if(moreLink.text() == options.moreText) {
							moreContent.show(options.moreAni);
							moreLink.text(options.lessText);
							ellipsis.css("display", "none");
						} else {
							moreContent.hide(options.lessAni);
							moreLink.text(options.moreText);
							ellipsis.css("display", "inline");
						}
						return false;
				  	});
				}
			} // end if
			
		});
	};
})(jQuery);



/*global window,document,jQuery */

/*!
* Fitted: a jQuery Plugin
* @author: Trevor Morris (trovster)
* @modifiedBy: Richard Davies http://www.richarddavies.us
* @url: http://www.trovster.com/lab/code/plugins/jquery.fitted.js
* @documentation: http://www.trovster.com/lab/plugins/fitted/
* @published: 11/09/2008
* @updated: 26/02/2011
* @license Creative Commons Attribution Non-Commercial Share Alike 3.0 Licence
*		   http://creativecommons.org/licenses/by-nc-sa/3.0/
*
* @notes:
* Also see BigTarget by Leevi Graham - http://newism.com.au/blog/post/58/bigtarget-js-increasing-the-size-of-clickable-targets/
*
*/
if (typeof jQuery !== 'undefined') {
	jQuery(function ($) {
		$.fn.extend({
			fitted: function (options) {
				var settings = $.extend({}, $.fn.fitted.defaults, options),
					getSelectedText;

				getSelectedText = function () {
					if (window.getSelection) {
						return window.getSelection().toString();
					} else if (document.getSelection) {
						return document.getSelection();
					} else if (document.selection) {
						return document.selection.createRange().text;
					}
				};

				return this.each(function () {
					var $t	= $(this),
						o	= $.metadata ? $.extend({}, settings, $t.metadata()) : settings,
						$a,
						href,
						title;

					if ($t.find(':has(a)')) {
						$a		= $t.find('a:first');
						href	= $a.attr('href');
						title	= $a.attr('title');

						/**
						* Setup the Container
						* Add the 'container' class defined in settings
						* @event hover
						* @event click
						*/
						$t.addClass(o.className.container).hover(
							function (event) {
								var $$ = $(this);

								// Add the 'hover' class defined in settings
								$$.addClass(o.className.hover);

								// Add the Title Attribute if the option is set, and it's not empty
								if (typeof o.title !== 'undefined' && o.title === true && title !== '') {
									$$.attr('title', title);
								}

								// Set the Status bar string if the option is set
								if (typeof o.status !== 'undefined' && o.status === true) {
									if ($.browser.safari) {
										// Safari Formatted Status bar string
										window.status = 'Go to "' + href + '"';
									} else {
										// Default Formatted Status bar string
										window.status = href;
									}
								}
							},
							function (event) {
								var $$ = $(this);

								// Remove the Title Attribute if it was set by the Plugin
								if (typeof o.title !== 'undefined' && o.title === true && title !== '') {
									$$.removeAttr('title');
								}

								// Remove the 'hover' class defined in settings
								$$.removeClass(o.className.hover);

								// Remove the Status bar string
								window.status = '';
							}
						).bind('click.fitted', function (event) {
							// Don't do anything if selecting text inside fitted element
							if (getSelectedText().length > 0) {
								return true;
							}

							// Don't override clicks on form elements
							if ($(event.target).is('input, select, option, optgroup textarea, button')) {
								return true;
							}

							if ($(event.target).closest('a').length) {
								$a		= $(event.target).closest('a');
								href	= $a.attr('href');
							}

							// Trigger the Anchor / Follow the Link
							if ($a.is('[rel*=external]')) {
								window.open(href);
								event.preventDefault();
							} else {
								window.location = href;
							}
						});
					}
				});
			}
		});
		
		$.fn.fitted.defaults = {
			title:	true,
			status:	true,
			className: {
				'container':	'fitted',
				'hover':		'hovered'
			}
		};
		
	}(jQuery));
}


$(function(){

	//carousels
	$('#scroller .scrollable').scrollable({ easing: 'swing', speed: 300, circular: true });
	$('#bestsellers .best-sellers-carousel').scrollable({ easing: 'swing', speed: 300, circular: false });

	//picker
	$('#bestsellers .title a').jTruncate({ length: 20, minTrail: 0, moreAni: 'fast', lessAni: 2000 });
	$('#picker-list li:first').addClass('carot');
    $('#bestsellers #picker').click(function () {
		$('#picker-list').slideToggle(400);
		$(this).toggleClass('selected');
		var labelText = $('#picker-list li:first a').text();
		$('#picker').text(labelText);
    });
	$('#picker-list').click(function () {
		$('#picker-list').slideToggle(400);
		$('#picker').addClass('active');
		$(this).toggleClass('selected');
    });
	$('#picker-list li a').click(function(e){
		e.preventDefault();
		$('#bestsellers #picker').toggleClass('selected');
		var textVal = $(this).text();
		$('#picker').text(textVal);
		var clickedRel = $(this).attr('rel');
		if ( $.browser.msie ) {
			$.ajax({
			    url: '/proxies/ajax.asp?PID=' + clickedRel,
			    xhr: function() { return new window.ActiveXObject("Microsoft.XMLHTTP"); },
			    success: function(data) {
			        $('#bestsellers #top10').html(data);
				    $('#bestsellers .best-sellers-carousel').scrollable({ easing: 'swing', speed: 500, circular: false });
				    $('#bestsellers .title a').jTruncate({ length: 20, minTrail: 0, moreAni: 'fast', lessAni: 2000 });
			    }
			});
		} else {
			$('#bestsellers #top10').load('/proxies/ajax.asp?PID=' + clickedRel, function() {
			    $('#bestsellers .best-sellers-carousel').scrollable({ easing: 'swing', speed: 500, circular: false });
			    $('#bestsellers .title a').jTruncate({ length: 20, minTrail: 0, moreAni: 'fast', lessAni: 2000 });
			});
		}
		$('#bestsellers .top10').fadeIn('slow');
		$(this).addClass('active-item');
		$('#picker-list li a').click(function() {
			$('#picker-list li a').removeClass('active-item');
			$(this).addClass('active-item');
		});	
	});
	
	// truncations
	$("#gridBN .pod-4 .title, #gridBN .pod-4 .contributor, #gridBN .trending-items .title a").jTruncate();
	$(".g-dotd-title a").jTruncate({length: 55});

	// product block anchors
	$(".pod-4 div.block").fitted();
	$(".pod-4 div.block").hover(function() {
		$(this).children("div.data-box-1").hide();
		$(this).children("div.data-box-2").show();
	}, function() {
		$(this).children("div.data-box-2").hide();
		$(this).children("div.data-box-1").show();	
	});
	
	// recommendations detection
	$(".trending-items .item:gt(2)").hide();
	
});


window.youBoughtCopurchasedEanExists = false;
window.trendingCount = 0;
$(document).bind('WidgetInserted.asynch', function(e,a,b) {
	BN(['BN.Widget.Sets'],function($,Sets){
	   	var myWidget = a.widget.getWidgetName();
	   	var mySet = Sets.itemSet.findObjects(function(node,api){
	   	    return api.getWidgetIdentification().getWidgetName() === myWidget;			
	    });

		if (mySet.length === 1){
			$(".trending-items .item:gt(2)").show();
			window.trendingCount = 6;
			window.youBoughtCopurchasedEanExists = true;
		} else {
			$("div.rec-copurchased").css("margin-bottom","0");
			window.trendingCount = 3;
		}
	});
});

window.youBoughtAuthorEanExists = false;


// Coremetrics Gateway Real-Estate tagging
$(function() {	   

	$(".g-left").not(".g-rec").each(function(i){
		$(this).attr("id","Left_Row_" + (i + 1));
	});
	$(".g-right").not(".g-rec").each(function(i){
		$(this).attr("id","Right_Row_" + (i + 1));
	});

	$(".g-left + div").add(".g-right + div").each(function(){
	
	// get top level
	var gw_top_level = $(this).attr("id");
	
	// get second level
	var gw_second_level;
	var gw_second_level_id = $(this).children().eq(0).attr("id");
	var gw_second_level_class = $(this).children().eq(0).attr("class");
	switch(gw_second_level_id) {
	case "merch-4":
		gw_second_level = "4_Across";
		break;
	case "featured-categories":
		gw_second_level = "Featured_Categories";
		break;
	case "featured-author":
		gw_second_level = "Featured_Author";
		break;
	case "best-new":
		gw_second_level = "Best_New";
		break;
	case "advertisement1":
		gw_second_level = "Advertisement";
		break;
	case "facebook":
		gw_second_level = "Facebook_Module";
		break;
	case "bestsellers":
		gw_second_level = "Bestsellers";
		break;
	case "g-dotd":
		gw_second_level = "Deal_of_the_Day";
		break;
	case "prime":
		gw_second_level = "BN_Membership_AMZNPrime_Comparison";
		break;
	default:
		gw_second_level = "Unknown_Module";
	} // end switch
	
	if (gw_second_level_class == "trending-items"){
		gw_second_level = "Trending_NOOK_Books";
	}
	if (gw_second_level_class == "module st-carousel"){
		gw_second_level = "Carousel";
	}
	
	// get local level
	$(this).find("a").each(function(i){

	if ($(this).attr("rel")){
		var gw_local_level = $(this).attr("rel");
	} else {
		var gw_local_level = "Local_Link_" + (i + 1);
	}
	
	// combine
	var cm_re_tag = gw_top_level + "-_-" + gw_second_level + "-_-" + gw_local_level;
	
	// set cm_re tag
	$(this).attr("manual_cm_re",cm_re_tag);
	});
	
	});
	
//special cases

// rotating billboard
var bb_name = $("#gw-wrap div").attr("data-promoname");
$("ul.bb-rotate li a").add("ul.bb-rotate li area").each(function() {
	slide = $(this).parent("li").attr("class");
	$(this).attr("manual_cm_re", "LeadPromo-_-Promo1-_-" + bb_name + "-" + slide).attr("data-bntrack",slide).attr("name", slide);
});

// special footlights
$(".special-footlight-1 a").attr("manual_cm_re","Footlights-_-Special-Footlight-1-_-PromoImageLeft").attr("data-bntrack","Sub-Promo 1");
$(".special-footlight-2 a").attr("manual_cm_re","Footlights-_-Special-Footlight-2-_-PromoImageRight").attr("data-bntrack","Sub-Promo 2");

});



$(window).load(function(){

// Web Instrumentation supplements
if(youBoughtCopurchasedEanExists == true) {
	youBoughtCopurchasedEan = $(".g-rec a.linked-image").eq(0).attr("href").match(/[0-9]{13}/);
} else {
	youBoughtCopurchasedEan = null;
}
/*if(youBoughtAuthorEanExists == true) {
	youBoughtAuthorEan = $(".g-rec.rec-author a.linked-image").eq(0).attr("href").match(/[0-9]{13}/);
} else {
	youBoughtAuthorEan = null;
}*/

//featuredAuthorName = $("#featured-author").attr("data-topic");
featuredAuthorName = $("#featured-author h3").text();
primaryPromoName = $("#gw-wrap div").attr("data-promoname");
if ($("#gw-fl-wrap")) {
subPromo1Name = $(".footlight-1").attr("data-promoname");
subPromo2Name = $(".footlight-2").attr("data-promoname");
subPromo3Name = $(".footlight-3").attr("data-promoname");
subPromo4Name = $(".footlight-4").attr("data-promoname");
} else {
subPromo1Name = "";
subPromo2Name = "";
subPromo3Name = "";
subPromo4Name = "";
}
if ($("#special-footlights")) {
subPromo1Name = "SpecialFootlightLeft";
subPromo2Name = "SpecialFootlightRight";
subPromo3Name = "";
subPromo4Name = "";
}
	
trendingNookbookRecs = trendingCount;

$("#g-hero area").each(function(i){
		$(this).attr("data-bntrack","ImageMapLink-" + (i + 1));
	});
$(".module.st-carousel h3 a").attr("data-bntrack","Header Link");
$(".module.st-carousel span.see-all a").attr("data-bntrack","See All Link");
$(".module.st-carousel .product-root-node a").attr("data-bntrack","Product Link");
$(".module.st-carousel .product-title a").attr("data-bntrack","Title Link");
$(".module.st-carousel .contributers-line a").attr("data-bntrack","Contributor Link");
$(".author-photo img").attr("data-bntrack-root","true")
	.attr("data-bntrack","Position 0");
	

if (typeof BN_YUI != "undefined") {

    BN_YUI.use('analytics-internaltracking', function(Y) {

        var BNHomePageTrackingObj = {
                pageType: 'CDS',
                pageName: 'Home Page',
                userId: wi_userId,
                signedIn: userSignedIn,
                serverTime: serverTime,
                url: trueURL,
                siteId : '0001',
                environment: 'unknown',
                parameters : {
                    "PrimaryPromoName": primaryPromoName,
                    "SubPromo1Name": subPromo1Name,
                    "SubPromo2Name": subPromo2Name,
                    "SubPromo3Name": subPromo3Name,
                    "SubPromo4Name": subPromo4Name,
                    "YouBoughtCopurchasedEan": youBoughtCopurchasedEan,
                    "FeaturedAuthorName": featuredAuthorName,
                    "TrendingNOOkbookRecsTotal": trendingNookbookRecs
                }
        };

        Y.Analytics.Tracker.WebInstrumentationBootstrap(BNHomePageTrackingObj);

    });

}
	
});
