var stars = function (config) {
	this.config = config;
	this.stop = 1;
	this.overlay = null;
	this.curStar = this.config.rateObj.firstChild;
	this.curStar.style.zIndex = zIndex;	
	this.startWidth = parseInt(this.curStar.style.width);	
	this.current = this.config.startValue;
	this.currentWidth = this.startWidth;
	this.curUser = this.config.uid ? this._$(this.config.uid) : null;
        this.config.starWidth = parseInt(config.starWidth) > 10 ? parseInt(config.starWidth) : 17;
        this.config.starCount = parseInt(config.starCount) > 1 ? parseInt(config.starCount) : 5;
	this.starsWidth = this.config.starCount * this.config.starWidth;
	var that = this;
	this.config.rateObj.onmousedown = function() {
		that.update();
	};
};

stars.prototype._$ = function (v, o) {
	return((typeof(o)=='object'? o : document).getElementById(v));
};

stars.prototype.$S = function (o) {
	return((typeof(o)=='object'?o:_$(o)).style);
};

stars.prototype.agent = function (v) {
	return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0));
};

stars.prototype.absPos = function (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);
};

stars.prototype.XY = function (e, v) {
	var o = this.agent('msie') ? {'X': event.clientX+document.documentElement.scrollLeft, 'Y': event.clientY+document.documentElement.scrollTop} : {'X': e.pageX, 'Y': e.pageY};
    return(v ? o[v] : o); 
};

stars.prototype.mouse = function () {
		
    if(this.stop) {
		this.stop = 0;
		var that = this;
		var remainder, whole = 0;
        document.onmousemove = function(e) {
           
            var n = that.num;    
            var p = that.absPos(that.config.rateObj),
            x = that.XY(e),
            oX = x.X - p.X,
            oY = x.Y - p.Y;
            if(oX < 1 || oX > that.starsWidth + 4 || oY<0 || oY>19) {
                that.stop = 1;
                that.revert();
            } else {
				oX = oX > that.starsWidth - 1 ? that.starsWidth - 1 : oX;				
                if (that.config.showPercentage) {
                    that.current = Math.round(oX / (that.starsWidth - 1) * 100);
					if (that.curUser) {
						that.curUser.innerHTML = that.current + '%';
					}
                } else {
					var cur = oX / (that.starsWidth - 1) * that.config.starCount;
					whole = Math.floor(cur);
					remainder = (cur * 100) % 100;
					if (remainder) {
						if (remainder > 0 && remainder < 25) {
							cur = whole;
						} else if (remainder >= 25 && remainder < 75) {
							cur = parseFloat(whole + 0.5);
						} else {
							cur = parseInt(whole + 1);
						}
					}
					cur = cur > 5 ? 5 : cur;
 					that.current = cur;
					if (that.curUser) {
						that.curUser.innerHTML = that.current;
					}
					oX = cur * (that.starsWidth - 1) / that.config.starCount;
                }
                that.currentWidth = oX;
				that.curStar.style.width = oX + 'px';
                if (that.curUser) {
					that.curUser.style.color = '#111';
				}
            }
        };
    }
};

stars.prototype.update = function () {
	//document.onmousemove = function () {return false;}
	this.stop = 1;
	this.startWidth = this.currentWidth;
    
    this.config.startValue = this.current;
	if (typeof(this.config.callback) == 'function') {
		if (typeof(this.config.callbackParams) == 'object') {
			this.config.callbackParams.rating = this.current;
		} else {
			this.config.callbackParams = {rating: this.current, starWidth: this.config.starWidth};
		}
		this.config.callbackParams.stars = this;
		this.config.callbackParams.rateObj = this.config.rateObj;
		this.config.callback(this.config.callbackParams);
		this.disable();
	}
};

stars.prototype.revert = function () {
	this.stop = 1;
	var v = this.config.showPercentage ? this.config.startValue + '%' : this.config.startValue;
    this.curStar.style.width = this.startWidth + 'px';
    if (this.curUser) {
		this.curUser.innerHTML = v;
		this.curUser.style.color = '#888';
	}
    document.onmousemove = function () {return false;};
};

stars.prototype.disable = function () {
	zIndex++;
	var position = this.absPos(this.config.rateObj);
	var overlay = document.createElement('div');
	overlay.className = 'modal-bg';
	overlay.style.top = parseInt(position.Y + 3) + 'px';
	overlay.style.left = position.X + 'px';
	overlay.style.width = this.starsWidth + 'px';
	overlay.style.height = CreatoorSN.common.starHeight + 'px';
	overlay.style.zIndex = zIndex;
	this.overlay = overlay;
	document.body.appendChild(overlay);
	document.onmousemove = function () {return false;};
};

stars.prototype.enable = function() {
	document.body.removeChild(this.overlay);
	zIndex--;
	this.overlay = null;
};

CreatoorSN.namespace('ratings');
CreatoorSN.ratings = {
	
	updateCallback : null,
	updateParams : null,
	rateObject : null,
	starsObject : null,
	updateCallback : null,
	
	rate: function (e, rateObj, callback, usrId, startValue, showPercentage, starCount) {
            CreatoorSN.ratings.updateCallback = callback;
		if (CreatoorSN.ratings.rateObject != rateObj) {			
				if (CreatoorSN.ratings.starsObject) {
					var so = CreatoorSN.ratings.starsObject;
					if (so) {
						CreatoorSN.ratings.rateObject.onmousemove = function(e)
						{
							CreatoorSN.ratings.rate(e, this, so.callback, so.config.uid, so.config.startValue, so.config.showPercentage, so.config.starCount);
						};
					}
				}
				CreatoorSN.ratings.rateObject = rateObj;
                                var config = {
					rateObj: rateObj,
					uid: usrId,
					startValue: startValue ? startValue : 0,
					showPercentage: showPercentage ? true : false,
					starCount: starCount,
					callback: CreatoorSN.ratings.saveRating,
					starWidth: CreatoorSN.common.starWidth,
					starHeight: CreatoorSN.starHeight
				};				
				CreatoorSN.ratings.starsObject = new stars(config);			
		}
		CreatoorSN.ratings.starsObject.mouse();
	},
	
	saveRating : function(params) {
		if (CreatoorSN.ratings.updateCallback && typeof(CreatoorSN.ratings.updateCallback.fn) == 'function') {
			if (typeof(CreatoorSN.ratings.updateCallback.params) != 'object') {
				CreatoorSN.ratings.updateCallback.params = {};				
			}
			for (x in params) {
				CreatoorSN.ratings.updateCallback.params[x] = params[x];
			}
			CreatoorSN.ratings.updateCallback.fn(CreatoorSN.ratings.updateCallback.params);
		}
	},
	
	removeRating : function() {
		
	},
	
	setUsers : function (avgRating, id, section, type) {
		eval('CreatoorSN.' + section + '.showRatingUsers')(avgRating, id, type);
	},
	
	showUsers : function (ratingUsersDivId, avgRatingDiv, url, get) {
		
		var ratingUsersDiv = _$(ratingUsersDivId);
		var target = avgRatingDiv.parentNode.parentNode;
		var avgParent = avgRatingDiv.parentNode;
		if (ratingUsersDiv) {
			CreatoorSN.ratings.hideUsers(ratingUsersDiv);
			return false;
		}
		
		
		var avgParentHtml = avgParent.innerHTML;
		avgParent.innerHTML = '<img src="/images/ajax-loader.gif" alt="please wait..." />';		
		var oCallback = {                
            success : function (o) {
				avgParent.innerHTML = avgParentHtml;				
				avgRatingDiv = avgParent.firstChild;
				while (!avgRatingDiv.tagName) {
					avgRatingDiv = avgRatingDiv.nextSibling;
				}
				var response = YAHOO.lang.JSON.parse(o.responseText);
                if (response.success) {
					var userCount = parseInt(response.count);
					var rating = response.rating;
					var width = Math.round(parseFloat(response.rating * CreatoorSN.common.starWidth));
					avgRatingDiv.firstChild.style.width = width + 'px';
					if (avgRatingDiv.nextSibling) {
                        avgRatingDiv.nextSibling.innerHTML = response.rating + ' (<span>' + response.count + '</span>)';                           
                    }
					avgRatingDiv.onclick = function() {
                        return doNothing();
                    };
					if (userCount) {
						avgRatingDiv.onclick = function() {
							CreatoorSN.ratings.showUsers(ratingUsersDivId, avgRatingDiv, url, get);
						};
						var ratingUsersDiv = new creaDomObject({
							tag: 'div',
							id: ratingUsersDivId,
							className: 'opinion-users clear-left',
							html: response.html
						});
						if (target.nextSibling && target.nextSibling.className != 'clear') {
							target.parentNode.removeChild(target.nextSibling);
						}
						var hideUsersLink = new creaDomObject(
                        {
                            tag: 'span',
                            html: CreatoorSN.common.translate('skrij'),
                            className: 'fake-link'
                        }
	                    );
	                    hideUsersLink.domElement.onclick = function() {
	                        CreatoorSN.ratings.hideUsers(ratingUsersDiv.domElement);
	                    };
	                    var hideUsers = new creaDomObject(
	                        {
	                            tag: 'div',
	                            className: 'hide-opinion-users',
	                            elements: [hideUsersLink]
	                        }
	                    );
						hideUsers.addTo(ratingUsersDiv);
						addAfter(ratingUsersDiv, target);
						
					} else {
						avgRatingDiv.onclick = function() {return false;};
					}
                    
                } else {
					if (response.noAuth) {
                        var login = new noAuth(function(noAuthObj){
                            CreatoorSN.ratings.showUsers(ratingUsersDivId, avgRatingDiv, url, get);
                        }, response.message);
                        return;
                    }
                    CreatoorSN.common.showErrorAlert(response.message);
                }
            },
            
            failure : function (o) {
				avgRatingDiv.innerHTML = avgRatingDivHtml;
                CreatoorSN.common.showErrorAlert(o.statusText);
            },
            timeout: CreatoorSN.common.iAjaxTimeout
            
        };
        YAHOO.util.Connect.asyncRequest(
            "GET",
            url + '?' + get,
            oCallback
        );
	},
	
	hideUsers : function(ratingUsersDiv) {
		ratingUsersDiv.parentNode.removeChild(ratingUsersDiv);
	} 
};

