// JavaScript Document
/*************************************************
Star Rating System
First Version: 21 November, 2006
Second Version: 17 May, 2007
Author: Ritesh Agrawal (http://php.scripts.psu.edu/rja171/widgets/rating.php)
Inspiration: Will Stuckey's star rating system (http://sandbox.wilstuckey.com/jquery-ratings/)
Half-Star Addition: Karl Swedberg
Demonstration: http://examples.learningjquery.com/rating/
Usage: $('#rating').rating('url-to-post.php', {maxvalue:5, curvalue:0});
Modified by: Amir Hoagland
Modifications include: ability to have average rating displayed as text; ability for the user's rating to be written to the page; adds popup after n number of ratings prompting action.

arguments
url : required -- post changes to
options
  increment : 1, // value to increment by
	maxvalue: number of stars
	curvalue: number of selected stars


************************************************/
var ratelimit=0;
var thisrater;
var origcurvalue = ""; // set to empty value initially
var oldcurvalue;
var minratings = 3; // minimum number of ratings before user receives prompt box
var ismember = $.cookie('site_auth');


jQuery.fn.rating = function(url, options) {
  if(url == null) return;

  var settings = {
    url : url,     // post changes to
    increment : 1, // value to increment by
    maxvalue  : 7, // max number of stars
    curvalue  : 0, // number of selected stars
    usrvalue  : 0, // default user rating
    ratingid  : ""
  };

  var rtinput = '<input class="ratingBox" type="hidden" name="'+url+'" value="'+settings.curvalue+':'+settings.usrvalue+'" />';
  if (url.match(/^\/music\/track\/\d+\/$/)) {
    settings.url = "/liveweb/comments/for"+url;
  }

  if(options) {
    jQuery.extend(settings, options);
  };
  jQuery.extend(settings, {cancel: (settings.maxvalue > 1) ? true : false});

  var container = jQuery(this);
  jQuery.extend(container, {
  url: settings.url,
         averageRating: settings.curvalue,
         userRating: settings.usrvalue
         });
  /* Append the Rate it/Your rating div */
  var rate = '<div class="clear">Rate it:</div>';
  container.html(rtinput+rate);
  settings.increment = (settings.increment < .75) ? .5 : 1;

  var s = 0;
  for(var i= 0; i <= settings.maxvalue ; i++){
    if (i == 0) {
      if(settings.cancel == true){
        /*var div = '<div class="cancel"><a href="#0" title="Cancel Rating">Cancel Rating</a></div>'; Cancel button has been removed*/
        var div = "";
        container.append(div);
      }
    } else {
      var $div = $('<div class="star"></div>')
        .append('<a href="#'+i+'" title="Give it '+i+'/'+settings.maxvalue+'">'+i+'</a>')
        .appendTo(container);
      if (settings.increment == .5) {
        if (s%2) {
          $div.addClass('star-left');
        } else {
          $div.addClass('star-right');
        }
      }
    }
    i=i-1+settings.increment;
    s++;
  }

  var avguserrating = settings.curvalue;
  if (settings.usrvalue == 0) {
    if (settings.curvalue != 0) {
      $(this).attr("title", "Avg. rating: "+settings.curvalue+'/'+settings.maxvalue); //sets the title attribute to the average rating
    }
    else {
      $(this).attr("title", "Avg. rating: N/A");
    }
  }
  else {
    $(this).attr("title", "Your rating: "+settings.usrvalue+'/'+settings.maxvalue); //sets the title attribute to the users rating
    $(this).find(".clear").html('Your rating: '+settings.usrvalue+'/'+settings.maxvalue);
  }

  var stars = jQuery(container).children('.star');
  var cancel = jQuery(container).children('.cancel');

  stars
  .mouseover(function(){
    event.drain();
    event.fill(this);
  })
  .mouseout(function(){
    event.drainhover();
  })
  .focus(function(){
    event.drain();
    event.fill(this);
  })
  .blur(function(){
    event.drain();
  });

  stars.click(function(){
    if(settings.cancel == true){
      $(".membernag").remove();

      if ( thisrater != settings.ratingid) {
        thisrater = settings.ratingid;
        ratelimit = ratelimit+1;
      }
      var x = ratelimit % minratings; //determines if the user has rated three things, if so they get popup asking to become a member
      var dns_rateit = $.cookie('dns_rateit'); // Get the cookie to see if user elected not to see the box again
      if (x == 0 && ismember == null && dns_rateit != 'yes') {
        var extra ='<div class="membernag"><div class="close"><a href="" title="close (x)">close (x)</a></div>Your feedback helps make us an even better radio station. If you\'d also like to participate in other music or opinion surveys we conduct, let us know by telling us a little bit more about yourself. You can continue to rate songs here without signing up. <a href="http://'+location.host+'/newmember/add.html">Sign up now</a>. <br />Have you already registered with '+location.host+'? <a href="http://'+location.host+'/newmember/login.html">Sign in here</a>';
        if (ratelimit < 6) {
          var end = '</div>';
          extra = extra + end;
        }
        else {
          var end = '<div class="right">[<a href="" id="dns_rateit">Do not show this again</a>]</div></div>';
          extra = extra + end;
        }

        // Append the membernag div
        jQuery(this).parent().append(extra);

        // Closes the membernag dialog box
        $(".membernag > .close").click(function() {
          $(this).parent().remove();
          return false;
        });

        $(".membernag").hover(
                              function() {
        },
                              function() {
                                $(this).hide(); //hide on mouse out
                              }
                              );


        $("#dns_rateit").click(function() {
          $.cookie('dns_rateit', 'yes', {path: "/"});
          $(".membernag").remove();
          return false;
        });


      }

      var rtitle = jQuery(this).parent().attr("title"); //grab the old value from the title attribute
      var rtitlearray = rtitle.split(": ");
      var rsub = rtitlearray[1];
      var rsubarray = rsub.split("/");
      oldcurvalue = rsubarray[0];

      settings.curvalue = (stars.index(this) * settings.increment) + settings.increment;

      //sets the original current value, sets the yellow average star rating on initial load
      if ( (origcurvalue == "") && (container.userRating == 0) ) {
        origcurvalue = container.averageRating;
        stars.slice(0,oldcurvalue).removeClass('onyellow');
        stars.slice(0,settings.curvalue).addClass('on').end();

      }
      else if ( (origcurvalue == "") && (container.userRating > 0) ) { //sets the red user's star rating on initial load
        origcurvalue = settings.usrvalue;
        oldcurvalue = settings.usrvalue;
        stars.slice(0,oldcurvalue).removeClass('on');
        stars.slice(0,settings.curvalue).addClass('on').end();
      }

      else {
        stars.slice(0,oldcurvalue).removeClass('onyellow');
        stars.slice(0,oldcurvalue).removeClass('on');
        stars.slice(0,settings.curvalue).addClass('on').end();
      }

      var avgdiv;
      //console.log(avgdiv);
      if (avguserrating == 0) {
        avgdiv = '<div class="avgrating">Avg. rating: N/A</div>';
      }
      jQuery(this).parent().attr("title", "Your rating: "+settings.curvalue+'/'+settings.maxvalue);
      jQuery(this).parent().find(".clear").html('Your rating: '+settings.curvalue+'/'+settings.maxvalue);

      //post the rating
      jQuery.post(container.url, {
        "rating": jQuery(this).children('a')[0].href.split('#')[1]
          });
      return false;

    } else if (settings.maxvalue == 1) {
      settings.curvalue = (settings.curvalue == 0) ? 1 : 0;
      $(this).toggleClass('on').end();
      jQuery.post(container.url, {
        "rating": jQuery(this).children('a')[0].href.split('#')[1]
        });
      return false;
    }
    return true;

  });





  // cancel button events
  if(cancel){
    cancel
      .mouseover(function(){
        event.drain();
        jQuery(this).addClass('on');
      })
      .mouseout(function(){
        jQuery(this).removeClass('on');
      })
      .focus(function(){
        event.drain();
        jQuery(this).addClass('on');
      })
      .blur(function(){
        event.reset();
        jQuery(this).removeClass('on');
      });

    // click events.
    cancel.click(function(){
      event.drainhover();
      event.drainred();
      settings.curvalue = origcurvalue;

      if (container.userRating > 0) {
        event.add();
      }
      else {
        event.reset();
      }
      jQuery.post(container.url, {
         "rating": jQuery(this).children('a')[0].href.split('#')[1]
         });
      return false;
    });
  }

  var event = {
    fill: function(el){ // fill to the current mouse position.
      var index = stars.index(el) + 1;
      stars
      .children('a').css('width', '100%').end()
      .slice(0,index).addClass('hover').end();
    },
    drain: function() { // drain all the stars.
      stars
      .filter('.on').removeClass('onyellow').end()
      .filter('.hover').removeClass('hover').end();
    },
    drainred: function() { // drain all the stars.
      stars
      .filter('.on').removeClass('on').end()
      .filter('.hover').removeClass('hover').end();
    },
    drainhover: function() { // drain all the stars.
      stars
      .filter('.hover').removeClass('hover').end();
    },
    add: function(){ // Reset the stars to the default index.
      stars.slice(0,settings.usrvalue).addClass('on').end();
    },
    reset: function(){ // Reset the stars to the default index.
      stars.slice(0,settings.curvalue / settings.increment).addClass('onyellow').end();
    }
  };

  if (container.userRating > 0) {
    event.add();
  }
  else {
    event.drain();
  }

  return(this);

};







