$(document).ready(function() {

  /* rating */
  var vote = false;

  var itemtype;

  var nodeID;

  function unrate() {
    if (!vote) {
      var currRating = $("span#currRating").attr("title");
      for ( var i = currRating; i <= 5; i++) {
        $("a.star[title=" + i + "]").removeClass("On").addClass("Off");
      }
      for ( var i = 1; i <= currRating; i++) {
        $("a.star[title=" + i + "]").removeClass("Off").addClass("On");
      }
    }
  }

  // 

    function rateCallback(content) {
      alertRate("thanks");
    }

    function rate(whichA) {

      var whichStar = $(whichA).attr("title");

      for ( var i = whichStar; i <= 5; i++) {
        $("a.star[title=" + i + "]").removeClass("On").addClass("Off");
      }
      for ( var i = 1; i <= whichStar; i++) {
        $("a.star[title=" + i + "]").removeClass("Off").addClass("On");
      }
    }

    function dorate(whichA) {

      var whichStar = $(whichA).attr("title");

      var url = contextPath + "/actions/registered/rating.action";

      $.get(contextPath + "/actions/registered/rating.action", {
        'nodeID' : nodeID,
        'vote' : whichStar * 20,
        'type' : itemtype
      }, function(responseText) {
        alertRate("thanks");
      });

    }

    function alertRate(whichAlert) {
      $("p.status").hide();
      if (whichAlert == "already")
        $("p.already").show();
      if (whichAlert == "thanks")
        $("p.thanks").show();
    }

    var mainul = $("ul.stars");
    if (mainul.length > 0) {

      if (mainul.attr("title") == 'votedtrue') {
        vote = true;
        alertRate("already");
      }

      var tobreak = mainul.attr("id");
      itemtype = tobreak.substr(0, tobreak.indexOf('_'));
      nodeID = tobreak.substr(tobreak.indexOf('_') + 1, tobreak.length);

      jslog.debug("itemtype: " + itemtype);
      jslog.debug("nodeID: " + nodeID);
      jslog.debug("vote: " + vote);

      $("a.star").bind("mouseenter", function(e) {
        if (!vote)
          rate(this);
      });

      $("ul.stars").bind("mouseleave", function(e) {
        unrate();
      });

      $("a.star").bind("click", function(e) {
        if (!vote) {
          dorate(this);
          vote = true;
        } else {
          alertRate("already");
        }
      });

    }

  });
