(function( $ ) {
  $.fn.Rater = function(settings) {

 settings = $.extend({
   ratingContSelector:    "div.star-rating",
   ratingContPrefix:    "rating-",
   ratingStatsContPrefix:   "stats-for-"
 }, settings);

 // return each of the submitted forms
 return this.each(function(){
   var theForm =    this,      // the form
   theRatingConts =  $(settings.ratingContSelector, theForm), // the containers holding the select rating elements
   ratedForms = $.cookie("exp_rating-" + $(theForm).attr("name")),  // the existing cookie
   rated =    $(theForm).is(".rated") ? true : false   // everything is unrated by default
   
   // if there is a cookie
   if(ratedForms && !rated){
       // match the current form.id and the users rating to the cookie string
       matchRegExp = new RegExp("(("+theForm.id+"):([1-5]))");
       rated = matchRegExp.exec(ratedForms);
   }
   
   var FID = $(this).attr("id");

   $(settings.ratingContSelector, theForm).each(function(){
    if ($("#" + FID + "-overall").val() != ""){
    	overallCount = parseFloat($("#" + FID + "-overall").val().split("|")[1]);
    	overallAvg = parseFloat($("#" + FID + "-overall").val().split("|")[0]);
    	overallSum = parseFloat($("#" + FID + "-overall").val().split("|")[2]);
    } else {
       overallCount = 0;
       overallAvg = 0;
       overallSum = 0;
    }

    var theRatingCont =   $(this),    // The container that holds the select and the rating stats
    theRater =   $("select", theRatingCont).get(0), // The rating select box
    theRaterOpts = $("option", theRater),    // The rating options
    
    theRaterEntryId =   this.id.replace(settings.ratingContPrefix, ""),
    
    theStats =   $("#" + settings.ratingStatsContPrefix + theRaterEntryId),
    //overallCountEl =  $("#" + $(theForm).attr("id") + "-overall").val().split("|")[1],   // The number of ratings
    //overallAvgEl = $("#" + $(theForm).attr("id") + "-overall").val().split("|")[0],   // The average rating
    overallSumEl = $(".overall_sum", theStats),   // The sum of all the ratings
    maxOverallSumEl =   $(".max_overall_sum", theStats), // The maximum sum of all the ratings
    maxRating =  theRaterOpts.length,    // The maximum rating
    maxOverallSum =   maxRating * overallCount;    // The maximum sum of all the ratings

  // create a new UL star rating container
  var starRater = $("<ul class='" + overallSum + "'></ul>")
    .insertBefore(theRater)
    .hide()
    .addClass(this.className)
    .fadeIn("slow");

  // create and append the current rating list item
  if(overallCount != 0){
    var currentRating = $('<span> | ' + overallCount + ' votes</span>');
  } else {
    var currentRating = $("<span> | 0 votes</span>");
  }

    if(!rated){
        // create and append the rating anchors
        theRaterOpts.each(function(i){
            starRater.append("<li class='star-" + ( i + 1 ) + "'><a href='#' title='Give it a " + this.value + " Star Rating'>" + this.value + "</a></li>");
        });
    } else {
        $("#submission-status-for-" + theRaterEntryId).show();
    }
    starRater.after(currentRating);
    
    starRater.find("li:lt(" + overallAvg + ")").find("a").addClass("active");

    $("a", starRater).click(function(){
        // set the anchor to active
        $(this).addClass("active").blur();
        // Get the clicked elements rating
        var rating = parseFloat($(this).html());
        // update the select element with the new value
        theRater.selectedIndex = rating - 1;
    
        // Get the latest cookie
        var ratedForms = $.cookie("exp_rating-" + $(theForm).attr("name")); // the existing cookie

        // if there is not a cookie
        if(!ratedForms){
            ratedForms = "|";
        }

        // Add the new form id and the rating to the front of the cookie
        // |theForm.id:rating|theForm.id:rating|
        $.cookie("exp_rating-" + $(theForm).attr("name"), ratedForms + theForm.id + ":" + rating + "|", {path: "/", expires: 365});

        $('input[type=submit]', theForm).click();

        return false;
      })
      .mouseover(function(){
          var curIndex = parseInt($(this).parent().attr("class").split("-")[1]);
          $(starRater).find("a.active").removeClass("active");
      	  $(starRater).find("li:lt(" + curIndex + ")").find("a").addClass("active");
      })
      .mouseout(function(){
          $(starRater).find("a.active").removeClass("active");
      	  $(starRater).find("li:lt(" + overallAvg + ")").find("a").addClass("active");
      });
   });

   // add classes to the form
   $(theForm).addClass("has-rateables" +
       // auto-submit or button-submit
       ((settings.autoSubmit)?" auto-submit":" button-submit") +
       // submitted or not-submitted
       ((rated)?" submitted":" not-submitted")
   );
  });
  }
})(jQuery); 
