var currentRating;
var currentVotes;

function init() {
  YAHOO.util.Event.addListener('rating', 'click', rateMagazine);
  YAHOO.util.Event.addListener('rating', 'mouseover', goingToRate);
  YAHOO.util.Event.addListener('rating', 'mouseout', notGoingToRate);
  
  notGoingToRate();
}

function notGoingToRate() {
  var starImages = document.getElementById('rating').getElementsByTagName('img');
  if(null == currentRating) {
    YAHOO.util.Connect.asyncRequest('GET', 'http://' + window.location.host + '/php/rating.php?issue=' + window.location.pathname, getRatingCallback);
  } else {
    for(var i = 0; i < starImages.length; i++) {
      starImages[i].src = '../images/' + (i < currentRating ? 'rated' : 'empty') + '.gif';
    }
    document.getElementById('votes').innerHTML = currentVotes;
  }
}

var getRatingSuccess = function(asyncHTTP) {
  var response = asyncHTTP.responseText.split(';');
  currentRating = response[0];
  currentVotes = response[1];
  notGoingToRate();
}

var getRatingFailure = function(asyncHTTP) {}

var getRatingCallback = {
  success: getRatingSuccess,
  failure: getRatingFailure,
  cache: false,
  timeout: 10000
}

function rateMagazine(mouseEvent) {

  var cookies = document.cookie;
  if(-1 != cookies.indexOf(window.location.pathname + '=voted')) {
    //alert('Sorry, you can vote only once.');
    return;
  }

  var starImages = document.getElementById('rating').getElementsByTagName('img');

  var elem = mouseEvent.srcElement;//for IE
  if(!elem) {
    elem = mouseEvent.target;//for Other
  }

  var stars = elem.id.substring(4);

  YAHOO.util.Connect.asyncRequest('GET', 'http://' + window.location.host + '/php/rating.php?action=rateMagazine&stars=' + stars + '&issue=' + window.location.pathname, rateMagazineCallback);
}

var rateMagazineSuccess = function(asyncHTTP) {
  alert('Thank you for your vote.');
  var response = asyncHTTP.responseText.split(';');
  currentRating = response[0];
  currentVotes = response[1];
  notGoingToRate();
  document.cookie = window.location.pathname + '=voted;max-age=' + (60 * 60 * 24 * 30);
}

var rateMagazineFailure = function(asyncHTTP) {
  alert('There was an error processing your rating.\n\nPlease try it again later.');
}

var rateMagazineCallback = {
  success: rateMagazineSuccess,
  failure: rateMagazineFailure,
  cache: false,
  timeout: 10000
}

function goingToRate(mouseEvent) {
  var starImages = document.getElementById('rating').getElementsByTagName('img');

  var elem = mouseEvent.srcElement;//for IE
  if(!elem) {
    elem = mouseEvent.target;//for Other
  }

  var stars = elem.id.substring(4);

  for(var i = 0; i < starImages.length; i++) {
    starImages[i].src = '../images/' + (i < stars ? 'highlight' : 'empty') + '.gif';
  }
}
