﻿// StarList: creates a star list object
//      offImg: img url for off state
//      ratingImg: img url for rating state
//      id: id associating this star list with data.
//          gets passed when rated
function StarList(offImg, ratingImg, id, divId, postUrl) {
    this._offImg = offImg;
    this._ratingImg = ratingImg;
    this._id = id;
    if (postUrl != undefined && postUrl != '') {
        this._postUrl = postUrl;
    } else {
        this._postUrl = "/WebServices/RatingList.asmx/RateList"
    }
    this._divId = divId;
}

//add properties
StarList.prototype._offImg;
StarList.prototype._ratingImg;
StarList.prototype._id;
StarList.prototype._postUrl;
StarList.prototype._divId;

//add methods
StarList.prototype.setUpStars = function () {

	var listObj = this;

	if (jQuery(listObj._divId) == null)
		return;

	var ratedStars = jQuery('#' + listObj._divId + ' .rated_star');

	ratedStars.each(function (index, item) {
		jQuery(item).mouseover(function (event) {

			var img = event.target;

			var list = jQuery(img).parent('li').parent('ul');

			var nextList = jQuery(list).next('ul');

			//if this star has a list of rating_star with it (i.e. it can be rated)
			if (nextList != 'undefined') {
				var thisId = parseInt(img.id.substring(img.id.length - 1));

				nextList.children().each(function (index, item) {

					var itemImg = jQuery(item).children().children()[0];

					var id = parseInt(itemImg.id.substring(itemImg.id.length - 1));
					if (id <= thisId) {
						itemImg.src = listObj._ratingImg;
					} else {
						itemImg.src = listObj._offImg;
					}
				});

				nextList.show();
				list.hide();
			}
		});

	});

	var ratingStars = jQuery('#' + listObj._divId + ' .rating_star');
	ratingStars.each(function (index, item) {
		//add onclick ajax event
		var lnk = jQuery(item).parent('a');
		jQuery(lnk).click(function (event) {
			var img = event.target;
			var rating = parseInt(img.id.substring(img.id.length - 1));

			listObj.rateStar(jQuery(img).parents('ul'), rating);  //TODO: this isn't quite right b/c we need to REPLACE the ul (and possibly the one below it)
		});
		jQuery(item).mouseout(function (event) {
			var list = jQuery(event.target).parents('ul');

			list.prev().show();
			list.hide();
		});
	});

	jQuery('#' + listObj._divId + ' .rating_list').each(function (index, item) {
		jQuery(item).hide();
	});
}

StarList.prototype.rateStar = function (listDiv, rating) {
	var listObj = this;

	var url = listObj._postUrl + '?rating=' + rating + '&uniqueID=' + listObj._id;

	jQuery.ajax({
		url: url,
		success: function (msg) {
			var t = jQuery(msg).find("string").text();
			jQuery(listDiv).html(t);
		}
	});
}

