(function($){
  $.fn.carouselController = function(o) {
    return this.each(function() {
      var carouselControl = $(this);
      var carouselHolder = $(this).parent();
      var customSelect = $(".carousel_controller select", carouselHolder);
      var isbn10 = $('#hidden_isbn10').text();

      var setupCarousel = function(data) {
        var name = carouselHolder.find(".jquery-selectbox-currentItem").text();
        $('.book_carousel', carouselHolder).remove();
        //alert(data);
        carouselControl.after(data);
        $(".book_carousel", carouselHolder).jPerspectiveCarousel({
          nextBtnName: ".carousel_next_button",
          prevBtnName : ".carousel_prev_button",
          totalNumHolder : "span.total_books",
          currentPositionHolder : "span.current_book",
          mainCarouselDiv : ".carousel_main",
          secondaryCarouselDiv : ".carousel_secondary",
          noBackgroundClass: "no_background",
          currentLinkText: "See all "+ name+" books",

          onBuild :function(carousel) {
            $(".carousel_secondary ul .bookTitle", carousel).truncateText({length: '30'});
            $(".carousel_main ul li", carousel).each(function() {
              if ($(".bookTitle",this).text().length > 70 ) { $(".bookBlurb", this).hide(); }
            });
          }
        });
      }

      var updateCarousel = function(e) {
        setupCarousel(e);
      }

      var change = function(e) {
        var id = customSelect.val();
        var updateURL = $('input.url_path', carouselHolder).val();
        $('.book_carousel .book_carousel_content', carouselHolder).html("").addClass("loading");
        
        $.ajax({
          url: updateURL + "/" + id,
          type: "GET",
          dataType:"html",
          success: updateCarousel
        });
      };

      var init = function(e) {
        customSelect.selectbox({fixWidth:true});
        customSelect.bind('change',change)
      };

      init();
    });
  }
})(jQuery);

$(document).ready(function() {
  $('.carousel_controller').carouselController();
});


var Ads = function() {
  var site_variable = '', receivedMessages = [], expectedMessages = [];
  return {
    display_ads: function() {
      if (showAds === true) {
					$("#ad_openx").remove();
					var ads_url = '/ads',
							request_url,
							openx_parameters = Ads.constructOpenxParameters(),
							main_content_height = $("#main_content").outerHeight(),
							sidebar_height = $("#sidebar").outerHeight() - $("#ad_openx").outerHeight(),
							ad_space_height = sidebar_height + 25;
					if (Ads.shouldDisplayAds(main_content_height, ad_space_height)) {
							Ads.createOpenxDiv();
							request_url = ads_url + "?main_content_height=" + main_content_height + "&sidebar_height=" + ad_space_height + "&openx_parameters=" + encodeURIComponent(this.site_variable) + encodeURIComponent(openx_parameters);
							$("#ad_openx").load(request_url, Ads.handleResponseForAds);
          }
      }
    },
    setSiteVariable: function(genres) {
				this.site_variable = "&exclusion=" + genres;
    },
    handleResponseForAds: function(response) {
      $("#ad_openx").remove();
      if (response !== "") {
        var main_content_height = $("#main_content").outerHeight(),
						sidebar_height = $("#sidebar").outerHeight() - $("#ad_openx").outerHeight(),
						div_height;
        if ((main_content_height - sidebar_height) > 110) {
						Ads.createOpenxDiv();
						div_height = main_content_height - sidebar_height - 54;
						$("#ad_openx").addClass("ad_openx lightGreyBg").css({ height:div_height + "px" });
						$("#ad_openx").html("<script type='text/javascript'>" + response + '</script>');
        }
      }
    },
    shouldDisplayAds: function(main_content_height, sidebar_height) {
				return $("#sidebar").length !== 0 && (sidebar_height < main_content_height);
    },
    constructOpenxParameters: function() {
				var openx_parameters = '';
				openx_parameters += "&amp;cb=" + Math.floor(Math.random() * 99999999999);
				openx_parameters += document.charset ? '&amp;charset=' + document.charset : (document.characterSet ? '&amp;charset=' + document.characterSet : '');
				openx_parameters += "&amp;loc=" + encodeURIComponent(window.location);
				if (document.referrer) openx_parameters += "&amp;referer=" + encodeURIComponent(document.referrer);
				if (document.context) openx_parameters += "&amp;context=" + encodeURIComponent(document.context);
				if (document.mmm_fo) openx_parameters += "&amp;mmm_fo=1";
				return openx_parameters;
    },
    createOpenxDiv: function() {
				var newDiv = document.createElement('div');
				newDiv.id = "ad_openx";
				$("#sidebar").append(newDiv);
    },
    display_page_specific_ads: function(domain, secure_domain, adserver_url, zone_id, adClassName) {
				var m3_u = (location.protocol == 'https:' ? secure_domain + adserver_url : domain + adserver_url),
						m3_r = Math.floor(Math.random() * 99999999999),
						adHolderEnd = (adClassName) ? '</div>' : '',
						adHolder = (adClassName) ? '<div class="' + adClassName + '">' : "";
				if (!document.MAX_used) document.MAX_used = ',';
				document.write(adHolder + "<script type='text/javascript' src='" + m3_u);
				document.write("?zoneid=" + zone_id);
				document.write('&amp;cb=' + m3_r);
				if (document.MAX_used != ',') document.write("&amp;exclude=" + document.MAX_used);
				document.write(document.charset ? '&amp;charset=' + document.charset : (document.characterSet ? '&amp;charset=' + document.characterSet : ''));
				document.write("&amp;loc=" + encodeURIComponent(window.location));
				if (document.referrer) document.write("&amp;referer=" + encodeURIComponent(document.referrer));
				if (document.context) document.write("&context=" + encodeURIComponent(document.context));
				if (document.mmm_fo) document.write("&amp;mmm_fo=1");
				document.write("'><\/script>" + adHolderEnd);
				if (adClassName) {
            $(document).ready(function() {
								$(".ad_holder").each(function() {
										var $this = $(this),
												AdContent = $("div[id~=beacon_]", $this).length;
										if (AdContent < 1) {
												$this.remove();
										} else {
												$("a[target=_blank]", this).each(function() {
														$(this).removeAttr("target");
												});
										}
								});
            });
				}
    },
    expectMessages: function(messageArray) {
				this.expectedMessages = messageArray;
				this.receivedMessages = [];
    },
    notify: function(message) {
				$.merge(Ads.receivedMessages, message);
				var receivedAll = true;
				$.each(Ads.expectedMessages, function() {
						if ($.inArray($.trim(this), Ads.receivedMessages) == -1) {
								receivedAll = false;
						}
        });
				if (receivedAll) Ads.display_ads();
		}
  };
}();

$(document).ready(function() {
	$(".ad_holder").each(function() {
		var $this = $(this),
				AdContent = $("div[id~=beacon_]", $this).length;
		if (AdContent < 1) {
				$(".flexi_ad", $this).remove();
		} else {
				$("a[target=_blank]", this).each(function() {
						$(this).removeAttr("target");
				});
		}
	});
});

Ads.expectMessages(["message_board", "bv_tab_show", "bazaar_voice"]);

function hideFormats() {
  $('#book-format-dropdown div.slider, #excerpt .selection-box ul').hide();
  $(document).unbind('click', hideFormats);
}

$(document).ready(function() {
  $('#book-format-dropdown .selected').click(function() {
    $(document).bind('click', hideFormats);
		$('#book-format-dropdown  div.slider').toggle();
		return false;
  });

  $('#excerpt .selection-box .selected ').click(function() {
    $(document).bind('click', hideFormats);
    $('#excerpt .selection-box ul').toggle();
    return false;
  });

  if ($('#book-format-dropdown ul.list li').length > 0)
      $('.retailer_cart_link a.add_to_cart_link').click(function(){ alert('Please select an eBook format.'); return false; })
	
  $('#book-format-dropdown ul.list li a').each(function() {
    $(this).parent().attr('href',$(this).attr('href'));
    $(this).attr('href','#');
  });

  $('#book-format-dropdown ul.list li').click(function() {
    $('#book-format-dropdown div.selected').html($(this).html());
    $('.retailer_cart_link a.add_to_cart_link').attr('href', $(this).attr('href')).unbind().click(function(){return true;});
    $('#book-format-dropdown div.slider').hide();
    return false;
  });

		var PopupActive = false;
		$("#about_lexile").click(function(){
				if(PopupActive) { return false; }
				var link = $(this),
						contentHolder = link.attr("href"),
						popupHolder = $('<div id="inlinePopupHolder"></div>'),
						popupClose = $('<div id="inlinePopupClose">close</div>'),
						linkOffset = link.offset(),
						popupTop = (linkOffset.top - 50) + "px",
						popupLeft = (link.outerWidth() + 80) + "px";

			PopupActive = true;

				popupClose.click(function(){
						$("#inlinePopupHolder").remove();
						PopupActive = false;
				});

				popupHolder.html($(contentHolder).html());
				popupHolder.css({ top: popupTop, left: popupLeft });
				popupHolder.prepend(popupClose);

				$("#wrapper > .wrap_content").css("position", "relative").append(popupHolder);
				return false;
		});
});

$(document).ready(function() {
  $('#truncated_awards_list li:not(:last)').each(function(index) {
    $(this).text($(this).text()+", ");
  });
  $('#see_all_awards_message').toggle(function() {
    $('#all_awards_list').show();
    $('#see_all_awards_message').removeClass('bg-right-arrow').addClass('bg-down-arrow').text('Minimize');
  }, function() {
    $('#all_awards_list').slideUp('fast');    
    $('#see_all_awards_message').removeClass('bg-down-arrow').addClass('bg-right-arrow').text('See all');
  });
});

$(document).ready(function() {
	Ads.display_ads();
});

$(document).ready(function(){
  if ($('#categories_carousel .carousel ul li').length < 6) $('#categories_carousel .next').add('#categories_carousel .prev').hide();
  $('#categories_carousel .carousel_container').jCarouselLite({
    btnNext: '#categories_carousel .next',
    btnPrev: '#categories_carousel .prev',
    visible: 5,
    speed: 250,
    scroll: 1,
    easing: 'swing'
  });
});

$(document).ready(function(){
  var handlethickBoxForAuthorsAlert = function(){
    var parameters = $("#alert_signup_form").formSerialize();
    tb_show("", $("#alert_signup_form").attr("action") + "?height=350&width=520&" + parameters);
  };
  var initializeAuthorAlertSignup = function() {
				var emailField = $("#alert_signup_form #subscriber_email");
		    emailField.setHintText({ defaultText : "Email" });

			  var authorAlertSignupFormSubmission = function() {
					var hintTxt = $.trim(emailField.val()).toLowerCase();
					if ( hintTxt == "" || hintTxt == "email") {
						emailField.val("").focus().removeClass("setHint");
						return false;
					}

          if($("#alert_signup_form input:checked").length == 0){
            $("#alert_signup_form .inRed").show();
            return false;
          }
          $("#alert_signup_form").unbind('click');
          handlethickBoxForAuthorsAlert();
          return false;
		    };

	      $("#alert_signup_form #alert_subscriber_submit").click(authorAlertSignupFormSubmission);
	      $("#alert_signup_form").submit(authorAlertSignupFormSubmission);
  };

  initializeAuthorAlertSignup();
});
