var i1 = null; // the "off" image
var i2 = null; // the "on" image (see preloadStars() function below for initialization of these vars)
var xmlHttp = null; // this is the core of the AJAX functionality, see getXMLHttp() and rateSong()
var singleSong = true; // indicates whether we're on show_sng.php page or not
var songRatings = null; // contains song(s) rating(s) displayed on the page. 
                         // is an array: keys are song ids and values are song ratings
                         // default value is array in which each song id has -3 rating.
var starsShowing = false; // see toggle_stars() function below
var star_width = 26; // NOTE: if you modify the star images, you must change this to show effect
var star_height = 25; // NOTE: if you modify the star images, you must change this to show effect

function getXMLHttp()
{
    if (window.ActiveXObject)
    {
        // user is using IE
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        // user is using Safari/Mozilla/Netscape
        xmlHttp = new XMLHttpRequest();
    }
    else
    {
        alert("Your web browser does not support AJAX; you must upgrade your browser to the newest version!");
        return false;
    }

    return true;
}

// this function sets the song's actual rating, by using the xmlHttp object to communicate with the
// ratesong.php script.  Essentially sends a GET request, but in the background, so the communication with
// the server is quick and unnoticed for the most part
function rateSong(rating, song_id)
{
    var url;

	getXMLHttp();
	if (xmlHttp == null)
	{
        // if their browser doesn't support ajax
		alert("Your web browser does not support AJAX!");
		return false;
	}

    // this is our handler function for the onreadystatechange event
    // the event takes place when we receive the HTTP header from the PHP script (ratesong.php)
  xmlHttp.onreadystatechange=function()
    {
      // state change goes here
      if (xmlHttp.readyState == 4)
      {
          if(singleSong)
          {
              // get the data from server's response
              // the server responds with the rating, and the rating alone
              document.getElementById("rating"+song_id).innerHTML = xmlHttp.responseText;
              // getElementById gets the <div></div> pair that surround the overall rating number, and this code
              // modifies that number to the new one
          }
          else
          {
              document.getElementById("rating"+song_id).innerHTML = xmlHttp.responseText + "";
          }

          AJAXRefreshData();
      }
    }

    // here is the magic:  this uses the xmlHttp object to communicate with the server
	url = "ratesong.php?id="+song_id+"&rating="+rating;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);

	songRatings[song_id] = rating;
}

function toggle_stars(num, defaultrating, sngid)
{
    if (starsShowing==true) {
        starsShowing = false;
        hide_stars();    
    }
    else {
        starsShowing = true;
        preloadStars(num, defaultrating, sngid);
    }
}

// if the user re-clicks the "Rate this song" link, this function is called and the stars are removed from the
// page

function hide_stars()
{
    document.getElementById('userstardata' + song_id).innerHTML = '';
}

// write_stars()  this function is called on initialization (if the user has rated this song, it fills in the
// appropriate amount of stars.  It's also called by the onMouseOut event of the <div></div> pair that replaced
// the original rating form on show_sng.tpl so when the mouse moves outside the stars it will fill in the right
// amount of stars for the users' old rating
function write_stars(num, defaultrating, song_id)
{
    // if you change the size of the star images, you need to change these values accordingly!
    star_width=26;
    star_height=25;

    // check if the songRating is = to -3 .. if it is, the user has not yet clicked on a star and set a new
    // rating so we show their rating that was stored in the database (defaultrating)
    if (songRatings[song_id] == -3)
        defaultrating = defaultrating + 3;
    else
        defaultrating = songRatings[song_id] + 3; // otherwise, we use the rating that they literally just set

    // the following code is fairly self explanitory, it creates the HTML needed to display the right
    // amount of filled stars.

    txt = '<table style="border:0px;padding:0px;border-collapse:collapse;" align="right">';
    txt = txt + '<tr>';

    for (var i=0;i<num;i++)
    {
        starnum = i+1;
        ratingNum = i - 2;
        txt = txt + '<td style="border:0px;padding:0px;">';
        txt = txt + '<a href="javascript:rateSong(' + ratingNum + ', ' + song_id +
                    ');" onMouseOver="javascript:mouse_on(' + starnum + ', ' + num + ', ' + song_id +
                    ');">';

        if (i < defaultrating)
            txt = txt + '<img style="border:0px;" src="./templates/1/pics/stars_full.gif" width="' + star_width + 
                        '" height="' + star_height + '" id="star' + song_id + starnum + '" />';
        else
            txt = txt + '<img style="border:0px;" src="./templates/1/pics/stars_empty.gif" width="' + star_width + 
                        '" height="' + star_height + '" id="star' + song_id + starnum + '" />';

        txt = txt + '</a></td>';
    }   

    txt = txt + '</tr></table>';

    document.getElementById('userstardata' + song_id).innerHTML = txt;
}

//
// this function preloads the stars and calls the initial write_stars() function
// used for show_sng.
//

function preloadStars(numstars, rating, sngid)
{
    // first we preload both of the images: empty star, and full star (half star can be added later relatively easily)
    i1 = new Image(star_width,star_height);
    i1.src = "./templates/1/pics/stars_empty.gif";

    // do the same for the full star
    i2 = new Image(star_width,star_height);
    i2.src = "./templates/1/pics/stars_full.gif";

    songRatings = new Array();
    songRatings[sngid] = -3;

    singleSong = true;

    write_stars(numstars, rating, sngid);
}


// this function preloads the stars and calls write_stars() in case when show_recommendations page is loading
// (with multiple songs)
//
function preloadMultipleStars(numstars, ratings, song_ids)
{
    // first we preload both of the images: empty star, and full star (half star can be added later relatively easily)
    i1 = new Image(star_width,star_height);
    i1.src = "./templates/1/pics/stars_empty.gif";

    // do the same for the full star
    i2 = new Image(star_width,star_height);
    i2.src = "./templates/1/pics/stars_full.gif";

    singleSong = false;

    songRatings = new Array();

    for (i = 0; i < song_ids.length; i++)
    {
      songRatings[song_ids[i]] = -3;
      write_stars(numstars, ratings[i], song_ids[i]);
    }
}


// this function is simple:  it takes the star the mouse is over, fills it, then fills all the stars before it
function mouse_on(image_id, numstars, song_id)
{
    var i = 0;

    for (i = image_id; i > 0; i--)
    {
        document.images['star' + song_id + i].src = i2.src;
    }

    for (i = numstars; i > image_id; i--)
    {
        document.images['star' + song_id + i].src = i1.src;
    }


    return true;
}

// after ajax update we need to reset the array of song ids and reload stars
function getElementsByClass(searchClass,tag) {
    var classElements = new Array();
    var els = document.getElementsByTagName('div'); // use "*" for all elements
    var pattern = new RegExp('\\b'+searchClass+'\\b');
    for (var i = 0; i < els.length; i++){
         if ( pattern.test(els[i].className) )
             classElements[classElements.length] = els[i];
    }
    for (var i = 0; i < classElements.length; i++){
     var thisID = classElements[i].id.match(/\d{1,}$/);
		 write_stars(5,0,thisID);
		}
//    return classElements;

}