if(typeof CMS == "undefined") {
  var CMS = {};
}

if(typeof g == "undefined") {
  var g = {};
}

CMS.Rating = function(steps,messages) {
   if(!steps) steps = 5;
   this.steps = steps;
   this.rated = false;
   this.messages = messages;
}

CMS.Rating.prototype.getPanel = function(elm) {
      var panel;
      if(DOM.hasClass(elm,"rating-block")) {
         panel = elm;
      } else {
         panel = DOM.getParentByClass(elm,"rating-block");   
      }
      return panel;
}

CMS.Rating.prototype.show = function(elm,rating,force) {
      if(this.rated && !force) return;

      var panel = this.getPanel(elm);
      
      var childs = panel.getElementsByTagName("img");

      var add = rating - parseInt(rating);
      if(add != 0) {
         rating  = parseInt(rating) + (add > 0.5 ? 1 : 0.5);
      }

      for(var i=1;i<=this.steps;i++) {
         if(i<=rating) {
            childs[i-1].src = "/images/ico/star-full.gif";
         } else {
            if(i - 0.5  <= rating && i-1 == parseInt(rating)) {
               childs[i-1].src = "/images/ico/star-half.gif";
            } else {
               childs[i-1].src = "/images/ico/star-empty.gif";
            }
         }
      }

      if(this.rated) {
         panel.className = "";
      }
      if($(panel.id+"-message")) {
         $(panel.id+"-message").innerHTML = this.messages[parseInt(rating)];
      }
   },

CMS.Rating.prototype.rate = function(elm,item_id,rate,clb) {
      var result = Utils.Json.eval(HTTP.getText("?ajaxCall=CMS_Rate.rate&id="+item_id+"&rate="+rate));

      var panel = this.getPanel(elm);
      
      $(panel.id+"-rank").innerHTML = result.result.count;
      var childs = panel.getElementsByTagName("img");
      for(var i=0;i<childs.length;i++) {
          childs[i].onmouseout  = "void";
          childs[i].onmouseover = "void";
          childs[i].onclick     = "void";
      }
      this.rated = true;

      for(var i=0;i<childs.length;i++) {
         if(i<rate) {
            childs[i].src = "/images/ico/star-vote.gif";
         }
      }
      var rating = this;
      setTimeout(function() {
         rating.show(elm,result.result.rank,true);
         setTimeout(function() {
            if(clb) clb();
         },3000);
      },1000);
}

g['rating'] = {};
