// social.star-rating.js

function $(v,o) { return((typeof(o)=='object'?o:document).getElementById(v)); }
function $S(o) { return((typeof(o)=='object'?o:$(o)).style); }
function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function abPos(o) { var o=(typeof(o)=='object'?o:$(o)), z={X:0,Y:0}; while(o!=null) { z.X+=o.offsetLeft; z.Y+=o.offsetTop; o=o.offsetParent; }; return(z); }
function XY(e,v) { var o=agent('msie')?{'X':event.clientX+document.body.scrollLeft,'Y':event.clientY+document.body.scrollTop}:{'X':e.pageX,'Y':e.pageY}; return(v?o[v]:o); }

var star_offset = 10;
var star_width = 84;

star={};

star.mouse = function(e,o) {

	if(star.stop || isNaN(star.stop)) {
	
		star.stop=0;
		$S('starCur').backgroundPosition = '0px -51px';
	    document.onmousemove=function(e) {
	    
	    	var n=star.num;
	        var p=abPos($('star'+n)), x=XY(e), oX=x.X-p.X, oY=x.Y-p.Y; star.num=o.id.substr(4);
	
			if ((oX>(star_width + star_offset) && oX<=(star_width + 2*star_offset)) && (oY>1 && oY<21)){
	    		$S('starCur'+n).width=(star_width)+'px';
	            $S('starUser'+n).color='#111';
	            $('starUser'+n).innerHTML=100+'%';
	        }else if ((oX< star_offset && oX>0) && (oY>1 && oY<21)){
	    		$S('starCur'+n).width=0+'px';
	            $S('starUser'+n).color='#111';
	            $('starUser'+n).innerHTML=0+'%';
	        }else if(oX<1 || oX>(star_width + 2*star_offset) || oY<0 || oY>20) {
	        	star.stop=1; star.revert();
	    	}else{
				$S('starCur'+n).width=(oX - star_offset)+'px';
	            $S('starUser'+n).color='#111';
	            $('starUser'+n).innerHTML=Math.round(((oX - star_offset)*100)/84)+'%';
	        }
	    };
	}
};

star.update=function(e,o) {
	var n=star.num, v=parseInt($('starUser'+n).innerHTML);
    n=o.id.substr(4); 
    
    name =$('rated_domain_name').value; // TODO: allow to have more than one rating item per page. Use the "n" parameter to do it.
    req = new XMLHttpRequest(); req.open('GET','../vote_domain/'+ name + '/' + v,false); req.send(null); // send it to "/user_domains/vote_domain"
	
	//alert(req.responseText);
	var rate = eval('(' + req.responseText + ')');
	if (rate.Rating.isnew == true) {
		str_votes = String($('starNumRates').innerHTML);
		votes = parseInt(str_votes);
		str_votes = str_votes.replace(String(votes),String(votes + 1));
		$('starNumRates').innerHTML = str_votes;
	}
	v=rate.Rating.newrating;
	// set the domain average value
	$('starCur' + n).title=v;
	star.stop=1;
	star.revert();
};

star.revert=function() { 
	var n=star.num, v=parseInt($('starCur'+n).title);
    $S('starCur'+n).width=Math.round(v*84/100)+'px';
    $('starUser'+n).innerHTML=(Math.round(v)+'%');
    $S('starCur'+n).backgroundPosition = '0px -1px';
    $('starUser'+n).style.color='#888';
    document.onmousemove='';
};

star.num=0;
