/* eBooks 2.0 JavaScript */

var ebooks = {};

$(document).ready(function()	{
	ebooks.ui.search(); //place label over search form
  ebooks.ui.coverartZoom(); //function to put large coverart in modal dialog
  ebooks.ui.overlay(); // function to append an overlay to each page for use when needed
  ebooks.ui.tabs(); // function to set up the tabs functionality on product/bundle detail pages
  ebooks.ui.excerpt(); // function to read excerpt in modal dialog on product detail page
  ebooks.ui.spotlightMore(); // function to animate the opening of "more" links in the spotlight boxes
  ebooks.ui.mainPromote(); // function for the main promote on the home page
  ebooks.ui.download(); // function to show the download message
  ebooks.pagination.featureBox(); // function to paginate horizontal feature boxes
  ebooks.pagination.spotlightBox(); // function to paginate spotlight boxes (1 at a time)
  ebooks.pagination.featureBoxLarge(); // function to paginate large horizontal feature boxes
  //ebooks.behavior.taf(); // function to async call the tell a friend form
  ebooks.behavior.externalLinks(); //function to open links in a new window
  ebooks.behavior.messageCount(); //function to count the length of the message field for taf
  ebooks.behavior.resetPasswordValidation(); // function to validate password entry in reset password form
  ebooks.behavior.videoPlayer(); // function to insert video player if flash is available
	if ( /MSIE ((5\.5)|[6])/.test(navigator.userAgent) && navigator.platform == 'Win32' ) {
		ebooks.iehelper.fixPngs(); // help ie6 render transparent pngs correctly
    ebooks.iehelper.cssHelpers(); //help ie6 render css classes, etc. correctly
	}
  ebooks.ebss.EBLdetectionCheck(); //function to check if EBL is installed on the computer
});

ebooks.config = {
	blankSrc: 'http://ebooks.connect.com/webassets/images/spacer.gif'
};

ebooks.ui = {
	search: function() { //place label on top of search input, hide on focus
    var label = $('#header label[for="keyword"]');
    label.addClass('overlabel');
    var searchInput = $('#header #keyword');
    searchInput.bind('focus', function() {
        label.hide();
    });
    searchInput.bind('blur', function() {
        if ( $(this).val() == '' ) {
            label.show();
        }
    });
    $('#header form').bind('submit',function(){
      if (!searchInput.val()) {
        return false;
      }
    });
	},
  
  excerpt: function() {
    $('#readExcerpt').hide();
    var header = $('#readExcerpt h2').text();
    var body = $('#readExcerpt .excerpt p').html();
    $('a[href="#readExcerpt"]').bind('click', function() {
      $('div.overlay').show();
      $('body').append("<div class='lightbox'><h2>" + header + "<span class='close'>Close <img src='/webassets/images/btn_close.gif' alt='Close'></span></h2><div class='lightbox-body'><div class='text-wrap'><p>" + body + "</p></div></div><div class='lightbox-footer'></div></div>");
      ebooks.ui.overlayClose();
      return false;
    });
  },

  coverartZoom: function()  { //show full resolution coverart image in lightbox onclick of zoom anchors
    $('a.zoom, .zoom a').bind('click', function() {
      $('div.overlay').show();
      $('body').append("<div class='lightbox'><h2>View Larger<span class='close'>Close <img src='/webassets/images/btn_close.gif' alt='Close'></span></h2><div class='lightbox-body'><div class='image-wrap'><img></div></div><div class='lightbox-footer'></div></div>");
      //ebooks.iehelper.fixPngs();
      var image = $(this).attr('href');
      $('.lightbox-body img').attr('src',image);
      ebooks.ui.overlayClose();
      return false;
    });
  },
  
  overlayClose: function() { //hide the lightbox of the large coverart
    $('.overlay, .close').bind('click', function() {
      $('.overlay').hide();
      $('.lightbox').remove();
    })
  },
  
  overlay: function() {
    $('body').append('<div class="overlay"></div>');
    $('div.overlay').hide();
  	if ( /MSIE ((5\.5)|[6])/.test(navigator.userAgent) && navigator.platform == 'Win32' ) {
  		var overlay = $('div.overlay');
      var bodyHeight = $('body').height();
      overlay.css("height",bodyHeight+'px');
  	}
  },
  
  tabs: function() {
    var tabContainers = $('div.productInfo > div');
    tabContainers.children('h2').hide();
    $('ul.productTabs a').bind('click', function() {
      tabContainers.hide().filter(this.hash).fadeIn();
      $('ul.productTabs li').removeClass('current');
      $(this).parent('li').addClass('current');
      if ( /MSIE ((5\.5)|[6]|[7]|[8])/.test(navigator.userAgent) && navigator.platform == 'Win32' ) {
        $('.productTabs li a.noborder').removeClass('noborder');
        $('ul.productTabs li.current-first-child').removeClass('current-first-child'); //IE helper
        $('ul.productTabs li.current-last-child').removeClass('current-last-child'); //IE helper
        $(this).parent('li.first-child').addClass('current-first-child'); //IE helper
        $(this).parent('li.last-child').addClass('current-last-child'); //IE helper
        $('.productTabs li.current').next().children('a').addClass('noborder');
      }
      return false;
    }).filter(':first').click();
    // send a click on 'read reviews' to the customer reviews tab
    $('#readreview a, .readreview a, #video a').bind('click', function() {
      var hash = $(this).attr('href');
      $('ul.productTabs a[href=' + hash + ']').click();
      return false;
    });
  },
  
  spotlightMore: function() {
    $('.threecol #mainContent .spotlight .description').addClass('limitHeight');
    $('.threecol #mainContent .spotlight .more')
      .addClass('position')
      .bind('click', function() {
        $(this).parents('.spotlight').addClass('heightAuto');
        $(this).prev('.description').removeClass('limitHeight');
        $(this).hide();
      return false;
    });
  },
  
  mainPromote: function() {
    $('#mainPromo ul.panels').css({ overflow:'hidden'});
    $('#mainPromo ul.panels li').css({ position:'absolute',top:0,right:2,zIndex:100 }).filter(':first').css({zIndex:200})
    var promotes = $('#mainPromo ul.panels li');
    
    //set up main promote
    promotes.hide().filter(':first').show();
    $('#mainPromo ul.tabs li').animate({opacity: 0.6}, 300).filter(':first').animate({opacity: 1.0}, 50);
    $('#mainPromo ul.tabs a').filter(':first').addClass('activeTab').end().filter(':last').addClass('lastTab');
    

    //bind click event to main promote tabs
    $('#mainPromo ul.tabs a').bind('click', function() {
      promotes.fadeOut().filter(this.hash).fadeIn();
      $(this).parents('li').animate({opacity: 1.0}, 300).siblings().animate({opacity: 0.6}, 300).find('a').removeClass('activeTab');
      $(this).addClass('activeTab');
      return false;
    });
    
    var rotateInt = '';
    function startRotation() {
      if (rotateInt == '') {
        rotateInt = window.setInterval('ebooks.ui.mainPromoteAnimate()', 5000);
      } else {
        stopRotation();
      }
    }
    function stopRotation() {
      if (startRotation != '') {
        window.clearInterval(rotateInt);
        rotateInt = '';
      }
    }
    startRotation();
    
    $('#mainPromo').hover(
      function() {
        stopRotation();
      },
      function() {
        startRotation();
      }
    );
  },
  
  mainPromoteAnimate: function() {
    var $active = $('#mainPromo ul.tabs a.activeTab');
    if ($active.hasClass('lastTab')) {
      var $next = $active.parents('li').parents('ul').find('li a:first').click();
    } else {
      var $next = $active.parents('li').next('li').find('a').click();
    }
  },
    
  download: function()  {
    $('.wantit a.download').attr('title', '').bind('click', function(){
      $(this).siblings('span').slideDown(300);
      return false;
    });
	$('p.wantit span').bind('click', function(){
		$(this).slideUp(300);
	});
  }
};

ebooks.pagination = {
  featureBox: function() { // init
    $('ul.featureThree').each(function() {
      var itemsPerPage = 3;
      var list = jQuery(this);
      var items = list.children('li').length;
      var currentPage = 1;
      var pages = Math.ceil(items/itemsPerPage);
      var container = list.parents('div.content');
      container.css({ overflow:"hidden" });
      if (pages > 1) {
        // hide all but first 'page'
        list.children('li').each(function(i){
          if ( i >= itemsPerPage) {
            var li = jQuery(this);
            li.hide();
          }
        });
        // draw the pagination
        ebooks.pagination.drawLinks(pages,container,currentPage,itemsPerPage); 
      }
    });
  },
  
  featureBoxLarge: function() { // init
    $('ul.featureFour').each(function() {
      var itemsPerPage = 4;
      var list = jQuery(this);
      var items = list.children('li').length;
      var currentPage = 1;
      var pages = Math.ceil(items/itemsPerPage);
      var container = list.parents('div.content');
      container.css({ overflow:"hidden" });
      if (pages > 1) {
        // hide all but first 'page'
        list.children('li').each(function(i){
          if ( i >= itemsPerPage) {
            var li = jQuery(this);
            li.hide();
          }
        });
        // draw the pagination
        ebooks.pagination.drawLinks(pages,container,currentPage,itemsPerPage); 
      }
    });
  },
  
  spotlightBox: function() { // init
    $('ol.spotlight').each(function() {
      var itemsPerPage = 1;
      var list = jQuery(this);
      var items = list.children('li').length;
      var currentPage = 1;
      var pages = Math.ceil(items/itemsPerPage);
      var container = list.parents('div.content');
      list.css({ overflow:"hidden" });
      container.css({ overflow:"hidden" });
      if (pages > 1) {
        // hide all but first 'page'
        list.children('li').each(function(i){
          if ( i >= itemsPerPage) {
            var li = jQuery(this);
            li.hide();
          }
        });
        // draw the pagination
        ebooks.pagination.drawLinks(pages,container,currentPage,itemsPerPage); 
      }
    });
  },
  
  drawLinks: function(end,container,currentPage,itemsPerPage)  { // draw pagination links
    container.siblings('.pagination').remove();
    var nextPage = parseInt(currentPage) + 1;
    container.before('<ol class="pagination"></ol>');
    // Add previous link
    if (currentPage == 1) {
      container.siblings('.pagination').append('<li><img src="/webassets/images/btn_featurebox_prev_inactive.gif"></li>');
    } else {
      container.siblings('.pagination').append('<li><a href="1" class="prev"><img src="/webassets/images/btn_featurebox_prev_active.gif"></a></li>');
    }
    // Create page numbers
    for (i=1; i<=end; i++) {
      if (i == currentPage) {
        container.siblings('.pagination').append('<li>' + i + '</li>');
      } else {
        container.siblings('.pagination').append('<li><a href="' + i + '">' + i + '</a></li>');
      }
    }
    //Add next link
    if (currentPage == end) {
      container.siblings('.pagination').append('<li><img src="/webassets/images/btn_featurebox_next_inactive.gif"></li>');
    } else {
      container.siblings('.pagination').append('<li><a href="' + nextPage + '" class="next"><img src="/webassets/images/btn_featurebox_next_active.gif"></a></li>');
    }
    //add click events 
    ebooks.pagination.buttons(end,container,currentPage,itemsPerPage);
  },
  
  buttons: function(end,container,prevPage,itemsPerPage) { // change pages
    var pagination = container.siblings('.pagination');
    //number links
    pagination.find('a').bind('click', function() {
      if ( $(this).hasClass('prev') ) {
        var currentPage = parseInt(prevPage) - 1;
      } else if ( $(this).hasClass('next')) {
        var currentPage = parseInt(prevPage) + 1;
      } else {
        var currentPage = $(this).text();
      }
      ebooks.pagination.drawLinks(end,container,currentPage,itemsPerPage);
      ebooks.pagination.changePage(currentPage,container,itemsPerPage);
      container.find('.heightAuto').removeClass('heightAuto');
      container.find('.description').addClass('limitHeight');
      container.find('.more').show();
      return false;
    });
  },
  
  changePage: function(currentPage,container,itemsPerPage) {
    var firstItem = (currentPage-1) * itemsPerPage;
    var lastItem = (firstItem -1) + itemsPerPage;
    var list = container.find('ul.featureThree, ul.featureFour, ol.spotlight');
    list.children('li').each(function(i){
      var li = jQuery(this);
      if ( i < firstItem || i > lastItem) {
        li.fadeOut();
      } else {
        li.fadeIn();
      }
    });
  }
};

ebooks.behavior = {
  messageCount: function(){
    var bodyId = $('body').attr('id');
    if (bodyId == 'tellAFriend')  {
      var maxlength = 900;
      var textarea = $('#tellAFriend .taf textarea');
      var length = textarea.val().length;
      textarea.parents('p').css('position','relative').append('<span id="counter"><span>' + (maxlength - length) + '</span> remaining</span>');
      textarea.bind('keyup',function(){
        var currentCount = $(this).val().length;
        $('#counter span').text(maxlength-currentCount);
      });
    }
  },

  taf: function() {
    $('.productBox p.taf a ').bind('click', function() {
      var href = $(this).attr('href');
      $('div.overlay').show();
      $('body').append('<div class="lightbox"><h2>Tell a Friend <span class="close">Close <img src="/webassets/images/btn_close.gif" alt="Close"></span></h2><div class="lightbox-body"><div class="waiting"></div></div><div class="lightbox-footer"></div></div>');
      $('.lightbox-body').load(href,{},function(){
        ebooks.behavior.ajaxSubmit();
      });
      ebooks.ui.overlayClose();
      return false;
    });
  },
  
  ajaxSubmit: function() {
    //handle form if present (first show of lightbox or if there is an error)
    $('.taf form input[value="submit"]').bind('click', function(){
      var form = $('.taf form');
      var url = form.attr('action');
      var formData = form.serialize();
      $.get(url,formData,function(data){
        $('.lightbox-body>div').html(data);
        ebooks.behavior.ajaxSubmit();
      }, "html");
      return false;
    });
    //handle links in confirmation page - append link to close window
  },

  externalLinks: function() {
    $('a[rel="external"]').click(function(){
        window.open(this.href);
        return false;
    });
  },
  
  resetPasswordValidation: function() {
    $('#resetPassword #password')
      .bind('blur', function() {
        if ( $(this).val().length < 6 || $(this).val().length > 16) {
          $(this).css({ backgroundColor:'#e9a090' });
          $(this).parents('p').append('<span>Password must be between 6 and 16 characters long.</span>');
          $('#resetPassword form p span').fadeIn();
        }
      })
      .bind('focus', function() {
        $(this).siblings('span').fadeOut().remove();
        $(this).css({ backgroundColor:'#ffffff' });
      });
    $('#resetPassword #password2')
      .bind('blur', function() {
        if ( $(this).val() != $('#password').val()) {
          $(this).css({ backgroundColor:'#e9a090' });
          $(this).parents('p').append('<span>Passwords do not match.</span>');
          $('#resetPassword form p span').fadeIn();
        }
      })
      .bind('focus', function() {
        $(this).siblings('span').fadeOut().remove();
        $(this).css({ backgroundColor:'#ffffff' });
      });
  },
    
  videoPlayer: function() {
    if ($("#bookTrailer").length > 0 ) {
      $('#bookTrailer').flash({
        swf: swfUrl,
        height: 275,
        width: 320,
        flashvars: { flvAddress: flvVideo1}
      });
    }
  }
};

ebooks.iehelper = {
  cssHelpers: function() {
    $('.twocol #mainContent .browseBox ol+h3').addClass('ieBorder');
    $('.twocol #mainContent .productTabs>li.current.first-child').addClass('current-first-child');
    $('.twocol #mainContent .productTabs>li.current.last-child').addClass('current-last-child');
    $('.twocol #mainContent .productTabs li.current').next().children('a').addClass('noborder');
  },

	fixPngs: function() {
		var type, background_image, background_repeat;

		$('.pngfix').each(function() {
			type = this.tagName.toLowerCase();

			if ( type == 'input' || type == 'img' ) {
				if ( (type == 'input' && this.getAttribute('type') == 'image') || this.src.toLowerCase().search(/\.png$/) ) {
					ebooks.iehelper.fixPng(this);
					$(this).bind('propertychange', function() {
						ebooks.iehelper.fixPng(this);
					});
				}
			}

			background_image = $(this).css('background-image');

			if ( background_image.toLowerCase().search(/\.png"\)$/) < 0 ) return;

			background_image = background_image.substring(5, background_image.length-2);
			background_repeat = $(this).css('background-repeat');
			this.style.background = 'none';

			if ( background_repeat == 'no-repeat' ) {
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + background_image + "', sizingMethod='crop')";
			} else {
				this.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + background_image + "', sizingMethod='scale')";
			}
		});
	},

	fixing: false,
	fixPng: function(obj) {
		if ( ebooks.iehelper.fixing ) return;

		ebooks.iehelper.fixing = true;

		var src = obj.src;

		if ( new RegExp(ebooks.config.blankSrc).test(src) ) {
			ebooks.iehelper.fixing = false;
			return;
		}

		obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src  + "', sizingMethod='image')";

		$(obj).bind('beforeprint', function(imgObjSrc) {
			return function() {
				this.src = imgObjSrc;
			}
		}(obj.src));

		$(obj).bind('afterprint', function() {
			this.src = ebooks.config.blankSrc;
		});

		obj.src = ebooks.config.blankSrc;
		ebooks.iehelper.fixing = false;
	}
};

ebooks.ebss = {
	EBLdetectionCheck: function() {
		
		var bodyId = $('body').attr('id');
		var result = false;
		var pluginName = "";
		var originalUrl = document.getElementById('original_url');
		//alert("original URL is: " + originalUrl);
		var redirectUrl = document.getElementById('redirect_url');
		//alert("redirect URL is: " + redirectUrl);
	
		if (bodyId == 'TestEBSSSpecification') {
			
			//check plugin for Mozilla based browser
			if (navigator.plugins && navigator.plugins.length > 0 ) {
				for (var i = 0; i < navigator.plugins.length && !result; i++) {
					var plugin = navigator.plugins[i];
					pluginName = plugin.name;
					if (pluginName.indexOf("eBook Library") > -1) {
						result = true;
					}
				}
			}
			//check for IE active X if no plugin were found
			if (!result) {
				//alert("plugin for Mozilla not found, try to find it using ActiveX control");
				var detectObj = document.getElementById('SonyeBookIdentifier');				
				
				if ( (detectObj != null) && (typeof(detectObj) != "undefined") ) {
					//alert("detectObj is not null is not undefined");
					if (typeof(detectObj.IsSEBLInstalled) != "undefined") {
						pluginName = "SonyeBookIdentifier";
						result = true;
					} 
				}
			}
			
			//alert("result is: " + result);
			
			//confirm("Proceed with using EBSS protocol?")
			if (result) {
				//alert("using EBSS URL");
				location.replace(originalUrl);
			} else {
				//alert("plugin not found, using redirect URL");
				location.replace(redirectUrl);
			}
		}
	}
};
