// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/* Here lie the constants! */
var yourRatingStars = {
  srcs   : [
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/unrated._V47082245_.gif',
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/1-star._V47082241_.gif',
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/2-star._V47082180_.gif',
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/3-star._V47060083_.gif',
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/4-star._V47082181_.gif',
             'http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/5-star._V47060077_.gif'
            ],
  images : [],
  text   : [
              'Unrated', 
              'I hate it', 
              'I don\'t like it', 
              'It\'s okay', 
              'I like it', 
              'I love it' 
             ],
  length :  6,
  removeSrc: "http://g-ecx.images-amazon.com/images/G/01/x-locale/personalization/ratings-bar/nav2/clear._V47060355_.gif",
  removeImage : null,
  initialized : false
};
/* There ends the constants! */


function escape_id(id) {
  return id.replace(/(\[|\])/g, '\\$1');
}

function limitedText() {
  if(this.value.length > this.limit) {
    this.value = this.value.substring( 0, this.limit );
  }

  document.getElementById(this.callbackId).value = (this.limit - this.value.length);
}

jQuery(document).ajaxSend(function(event, request, settings) {
    if (typeof(AUTH_TOKEN) == "undefined") return;
    if (/authenticity_token=/.test(settings.data)) return;
    settings.data = ((settings.data) ? settings.data + "&" : "") +
        "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
});

function readyFunction() {

    var popoverSkin = jQuery.browser.msie && jQuery.browser.version < 7 ? 'classic' : 'default';

    $('a.whatsThis').livequery(function() {
            $(this).amazonPopoverTrigger({
                    showOnHover: true,
                    destination: this.href,
                    closeEventInclude: 'MOUSE_LEAVE',
                    hoverShowDelay: 200,
                    title: this.title,
                    skin: popoverSkin
            });
        });
 
     $('a.whatsThisLink').livequery('click', function() {
          $('#' + this.rel).slideToggle();
          return false;
        });
     
     $('a.seeEntireReview').each(function() {
            $(this).amazonPopoverTrigger({
                    showOnHover: false,
                    destination: this.href,
                    closeEventInclude: 'CLICK_OUTSIDE',
                    hoverShowDelay: 200,
                    width: 500,
                    title: $(this).attr('alt'),
                    skin: popoverSkin

            });
        });

    $('div.ap_content > div.review').livequery(function() {
            if ($(this).height() > 300) {
                $(this).height(300);
            }
        });

    $("a.rjs").livequery('click', function() {
      $.ajax({
            url: this.href,
            dataType: "script",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "text/javascript");
            }
        });
      return false;
    });

    $("form.rhtml").livequery(function() { 
        var formTag = this; 
        $(this).ajaxForm({
            type: 'post',    
	    beforeSend: function(xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
	    },
            success: function(data) { 
                $('#' + formTag.title).html(data);
            },
	    resetForm: true
        });                  
    });

    $("form.rjs").livequery(function() {
	$(this).ajaxForm({
	    dataType: 'script',
	    beforeSend: function(xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
	    },
	    resetForm: true
	});
    });

    // for a link of the form <a href="controller/action" rel="myId" class="rhtml">Click</a>, the html
    // returned for the given href is loaded into the html element with the id of myId
    $("a.rhtml").livequery('click', function() {
	var itemId = '#' + this.rel;
	$.get(this.href, function(data) {
	    $(itemId).html(data);
	});
        return false;
    });

    $(".selectSubmit").livequery( 'change', function(e) {
      location.href = e.target.options[e.target.selectedIndex].value;
    });

    // Note that disabling the button should be done here
    // and not e.g. in 'livequery('click'' b/c a disabled button 
    // won't submit the form in IE
    $("form.rjsNoReset").livequery(function() {
	$(this).ajaxForm({
	    dataType: 'script',
            beforeSubmit: function() {
                   $('input.submitWithDisable').attr('disabled',true);
            },
	    beforeSend: function(xhr) {
		xhr.setRequestHeader("Accept", "text/javascript");
	    }
	});
    });


   bindYourRating($); 
}


function bindYourRating($) {
  /*
   *  START "Your Rating" 
   *   personal ratings
   */

  //Uses an event (click on image) to resolve which star a user pressed
  function resolveStarNum(e ) {
    var x = e.pageX;
    var pos = x - $(e.target).offset().left;

    return (Math.ceil(pos * (yourRatingStars.length - 1) / ($(e.target).width()+1)) )
  }

  var saveInFade = 100;
  var saveOutFade = 2000;

  //Sets "Status" widget to READ status if it wasn't in read before. 
  //Essentially simulates the ajax request
  function setToReadIfUndefined(id) {
    $("#" + id).each( function(i,e) {
      if( e.selectedIndex == 0 ) {
        e.selectedIndex = 1;
      }
    });
  }

  //This event is fired when a user clicks on a star to rate
  //it sends an ajax request to update the rating
  function yourRatingClick(e) {
    var star = resolveStarNum(e);
    var removeRating   = $(e.target).next(".yourRatingDelete")[0];
    var ratingText=  $(e.target).siblings(".yourRatingText");

    if(e.target.rating != star ) {
      e.target.rating = star;

      ratingText.stop();
      ratingText.text("Saving");
      ratingText.fadeTo(saveInFade,1);
      $.ajax( {
                type: "POST",
                url : "/kindle/create_or_update_edition_relation",
                data: {
                        asin: e.target.asin,
                        rating : e.target.rating
                      },
                success: function() { ratingText.text("Saved"); 
                                      ratingText.fadeTo(saveOutFade,0); 
                                      removeRating.style.visibility = ""; 
                                      setToReadIfUndefined(e.target.statusWidgetId); 
                                    },
                failure: function() { ratingText.text("Failed to save"); }
              }
      );
    }
  }

            
  //This event is fired when the user clicks "delete rating"
  //it sends an ajax request to delete the rating
  function yourRatingDelete(e) {
    var star = resolveStarNum(e);
    var starDom = $(e.target).prev(".yourRatingStars")[0];
    var ratingText =  $(e.target).siblings(".yourRatingText");

    starDom.rating = 0;
    starDom.src = yourRatingStars.images[0].src;

    ratingText.stop();
    ratingText.text("Saving");
    ratingText.fadeTo(saveInFade,1);
    $.ajax( {
              type: "POST",
              url : "/kindle/remove_edition_relation_attribute",
              data: {
                      asin: starDom.asin,
                      rating : true
                    },
              success: function() { ratingText.text("Saved"); ratingText.fadeTo(saveOutFade,0); e.target.style.visibility = "hidden"; },
              failure: function() { ratingText.text("Failed to save"); }
            }
    );
  }

  //This sets the widget to what the user rated the book
  function yourRatingOut(e) {
    e.target.src = yourRatingStars.images[e.target.rating].src;
  }

  //This gives a "preview" of what the rating will be as you hover over the widget
  function yourRatingHover(e) {
    var starNum =  resolveStarNum(e);
    e.target.src = yourRatingStars.images[starNum].src;
    e.target.alt = yourRatingStars.text[starNum];
  }


  $('.yourRatingWidget').livequery( function() {
    var asin           = $(this).children(".yourRatingEditionAsin").text();
    var relationRating = parseInt($(this).children(".yourRatingEditionRelationRating").text());
    var imageTag       = $(this).children(".yourRatingStars");
    var domImageTag    = imageTag[0];
    var removeRating   = $(this).children(".yourRatingDelete");
    var statusWidgetId = $(this).children(".yourRatingStatusWidgetId").text();

    if( !yourRatingStars.initialized ) {
      yourRatingStars.images = jQuery.map( yourRatingStars.srcs, function(e) { var x = new Image(); x.src = e; return x; });
      yourRatingStars.removeImage = new Image();
      yourRatingStars.removeImage.src = yourRatingStars.removeSrc;
      yourRatingStars.initialized = true;
    }

    domImageTag.rating = relationRating;
    domImageTag.asin = asin;
    domImageTag.statusWidgetId = statusWidgetId;
    domImageTag.src = yourRatingStars.images[relationRating].src;
    removeRating[0].src = yourRatingStars.removeImage.src;

    removeRating.bind('click', yourRatingDelete);
    imageTag.bind( 'click', yourRatingClick );
    imageTag.bind( 'mouseout', yourRatingOut );
    imageTag.bind( 'mousemove', yourRatingHover );
  });

}

$(document).ready(readyFunction);
