
// action when hover over mouse on stars.
function displayHover(tagId, score) {
    for (var i = 1; i <= score; i++) {
        var star = dojo.byId('star_'+tagId+'_'+i);
        star.setAttribute('src', '/images/stars/rating_over.gif');
    }
}

// action when hover off mouse from stars.
function displayNormal(tagId, score) {
    for (var i = 1; i <= score; i++) {
        var star = dojo.byId('star_'+tagId+'_'+i);
        var status = star.className;
        star.setAttribute('src', '/images/stars/rating_'+status+'.gif');
    }
}

var NUMBER_OF_STARS = 5;

// Initialize rating(voting) system for the user.
function raterInit(tagId, toolId, hideIfVoted, token) {
    
    var div = dojo.byId(tagId);
    if(!div) { return; }
    
    var rating = getRating(toolId, token);
    if(!rating) { return; }
    
    var voted = rating.voted;
    var score = rating.score;
    var comment = rating.comment;
    token = token || '';

    while(div.hasChildNodes()) {
        div.removeChild(div.firstChild);
    }
    
    if(voted && hideIfVoted) {
    	return;
    }
    
    // 
    var prefix = document.createElement("span");
    prefix.style.cssText = "font-size:1.0em; font-weight:bold; color:#333399; margin-left:15px;";
    if(voted) {
    	prefix.appendChild(document.createTextNode("Your rating is: "));
    } else {
    	prefix.appendChild(document.createTextNode("Please rate this tool: "));
    }
    div.appendChild(prefix);
    
    // star images
    for (var i = 1; i <= NUMBER_OF_STARS; i++) {
        var star = document.createElement('img');
        if (score >= 1) {
            star.setAttribute('src', '/images/stars/rating_on.gif');
            star.className = 'on';
            score--;
        } else if(score >= 0.5 && score < 1) {
            star.setAttribute('src', '/images/stars/rating_half.gif');
            star.className = 'half';
            score = 0;
        } else {
            star.setAttribute('src', '/images/stars/rating_off.gif');
            star.className = 'off';
        }
        star.setAttribute('id', 'star_'+tagId+'_'+i);
        star.onmouseover = new Function("event", "displayHover('"+tagId+"', "+i+");");
        star.onmouseout = new Function("event", "displayNormal('"+tagId+"', "+i+");");
        star.onclick = new Function("event", "submitRating('"+tagId+"', "+toolId+", "+i+", '"
        		+comment.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/'/g, "\\'")
        		+"', "+hideIfVoted+",'"+token+"');");

        div.appendChild(star);
    }
    
    // comment.
    if(voted && !token) {
        var span = document.createElement("span");
        span.appendChild(document.createTextNode(" " + comment));
        div.appendChild(span);
        
        // edit link for comment.
        var a = document.createElement("a");
        a.href = "javascript:void(0);";
        score = rating.score;
        a.onclick = new Function("event", "submitRating('"+tagId+"', "+toolId+", "+score+", '"
        	+comment.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/'/g, "\\'")
        	+"', "+hideIfVoted+",'"+token+"');");
        a.appendChild(document.createTextNode(" edit"));
        div.appendChild(a);
    }
    
}

// Get user's Rating from DB. 
function getRating(toolId, token) {

    var result = null;
	dojo.io.bind({
        url: '/rater/getRating.php',
        handler: function(type, data, event) {
            if (type == 'error') {
                alert('Error getting the rating!');
            } else {
                //alert(data.comment);
                result = data;
            }
        },
        mimetype: 'text/json',
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: { 'toolid': toolId, 'token': token }
    });
	
	return result;
}

// Submit and save user's vote to DB.
// After saving, update the ratings.
function submitRating(tagId, toolId, score, comment, hideAfterVote, token) {
    
	if(!token) {
    	comment = prompt("Please comment on the tool.", comment);
    	if(comment == null) {
       		return;
   		}
   	}

    //var score = parseInt(starNumber) + 1;
    dojo.io.bind({
        url: '/rater/submitRating.php',
        handler: function(type, data, event) {
            if (type == 'error') {
                alert('Error submitting the rating!');
            } else {
                //alert(data);
                
                // Update all of the user's rating of the tool.
                var divList = document.getElementsByTagName("div");
                for(var i = 0; i < divList.length; i++) {
                	if(divList[i].className == "rating" &&
                			divList[i].id.match("_"+toolId+"$")) {
                		
                		raterInit(divList[i].id, toolId, hideAfterVote, token);
                		
                		// add "Thanks for voting!" to the place where user did a vote.
                		if(tagId == divList[i].id) {
                			if(!token) {
		                		var thanks = document.createElement("span");
						        thanks.appendChild(document.createTextNode(" Thanks for voting!"));
						        thanks.className = "thanks";
						        dojo.byId(divList[i].id).appendChild(thanks);
								dojo.lfx.html.fadeShow(thanks, 1000).play();
							}
					    }
                	}
                }
                
                // Update total ratings.
                totalRatingInit("total_"+tagId, toolId, true, token);
                
                // Update comment input field.(voting via email only)
                commenterInit("comment_"+tagId, toolId, token);
            }
        },
        mimetype: 'text/plain',
        method: 'post',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: {'toolid': toolId, 'score': score, 'comment': comment, 'token': token}
    });
}

// Get average rating of the tool from DB.
function getAvgRating(toolId, token) {

    var result = null;
    dojo.io.bind({
        url: '/rater/getAvgRating.php',
        handler: function(type, data, event) {
            if (type == 'error') {
                alert('Error getting the rating!');
            } else {
                //alert(data);
                result = data;
            }
        },
        mimetype: 'text/json',
        method: 'get',
        sync: true,
        error: function(type, error){ dojo.debug(error.message); },
        timeoutSeconds: 60,
        content: { 'toolid': toolId, 'token': token }
    });
    
    return result;
}

// Initialize total rating.
// argument: isUpdate - when 'true', get data from DB.
//                      when 'false', use data inside the div tag. (for better performance)
function totalRatingInit(tagId, toolId, isUpdate, token) {

    var div = dojo.byId(tagId);
	if(!div) { return; }
    var score = null;
    var votes = null;
    token = token || '';
    if(isUpdate) {
	    var rating = getAvgRating(toolId, token);
	    if(!rating) { return; }
	    score = rating.avg;
	    votes = rating.votes;
	} else {
		var data = null;
		try {
			data = dojo.byId("total_rating_scores_"+toolId).firstChild.nodeValue.split("/");
		} catch(e) {
			//alert(e);
			return;
		}
		score = parseFloat(data[0]);
		if(isNaN(score)) { return; }
		
		votes = parseInt(data[1], 10);
		if(isNaN(votes)) { return; }
	}
	
    while(div.hasChildNodes()) {
        div.removeChild(div.firstChild);
    }
    
    // star images
    for (var i = 1; i <= NUMBER_OF_STARS; i++) {
        var star = document.createElement('img');
        if (score >= 1) {
            star.setAttribute('src', '/images/stars/rating_on.gif');
            star.className = 'on';
            score--;
        } else if(score >= 0.5 && score < 1) {
            star.setAttribute('src', '/images/stars/rating_half.gif');
            star.className = 'half';
            score = 0;
        } else {
            star.setAttribute('src', '/images/stars/rating_off.gif');
            star.className = 'off';
        }
        star.setAttribute('id', 'star_'+toolId+'_'+i);
        div.appendChild(star);
    }
    
    var span = document.createElement("span");
    if(token) {
    	span.appendChild(document.createTextNode(" ("+votes+" "+(votes>1 ? "votes" : "vote")+")"));
    } else {
	    if(votes > 0) {
		    var a = document.createElement("a");
		    a.href = "javascript:void(0)";
		    //a.onclick = new Function("event", "mySequenceManager.loadContent('/leftcontent/viewComments.php?toolid="+toolId+"');");
		    a.onclick = function() {
		    	mySequenceManager.loadContent('/leftcontent/viewComments.php?toolid='+toolId);
		    }
		    if(votes > 1) {
		    	a.appendChild(document.createTextNode(" ("+votes+" votes) view ratings"));
		    } else {
		    	a.appendChild(document.createTextNode(" (1 vote) view ratings"));
		    }
		    span.appendChild(a);
		} else {
			span.appendChild(document.createTextNode(" (0 vote)"));
		}
	}

    div.appendChild(span);
}

// Initialize a comment field which is used in voting via email(/rater/thankyou.php).
function commenterInit(tagId, toolId, token) {
    var div = dojo.byId(tagId);
    if(!div) { return; }
    
    var rating = getRating(toolId, token);
    if(!rating) { return; }
    
    var voted = rating.voted;
    var score = rating.score;
    var comment = rating.comment;
    token = token || '';

    while(div.hasChildNodes()) {
        div.removeChild(div.firstChild);
    }
    
    // 
    var prefix = document.createElement("span");
    prefix.style.cssText = "font-size:1.0em; font-weight:bold; color:#333399;";
    if(comment) {
    	prefix.appendChild(document.createTextNode("Your comment is: "));
    } else {
    	var message = '';
    	switch (score)
    	{
    	case '1':
    		message = 'What didn\'t you like about this tool? ';
    		break;
    	case '2':
    		message = 'What kind of improvements would you like to see in this tool? ';
    		break;
    	case '3':
    		message = 'Please comment this tool: ';
    		break;    
    	case '4':
    		message = 'What do you like about this tool and/or what could we have done to earn a perfect score? ';
    		break;
    	case '5':
    		message = 'What do you like about this tool? ';
    		break;		
    	}
    	prefix.appendChild(document.createTextNode(message));
    }
    div.appendChild(prefix);
    div.appendChild(document.createElement("br"));
    
    // input field.
    var input = document.createElement("textarea");
    //input.setAttribute("type", "textarea");
    //input.setAttribute("size", "50");
    input.setAttribute("rows", "3");
    input.setAttribute("cols", "50");
    //input.setAttribute("value", comment);
    input.appendChild(document.createTextNode(comment));
    input.setAttribute("id", "comment_" + toolId);
    div.appendChild(input);
    div.appendChild(document.createElement("br"));
    
    // submit button.
    var button = document.createElement("input");
    button.setAttribute("type", "button");
    button.setAttribute("value", "Submit");
    button.className = "fancyButton";
    raterTagId = tagId.replace(/^comment_/g, '');
    button.onclick = new Function("event", "var comment=dojo.byId('comment_"+toolId+"').value;"
    		+"submitRating('"+raterTagId+"', "+toolId+", "+score+", "
        	//+"comment.replace(/\\n/g, '\\n').replace(/\\r/g, '\\r').replace(/'/g, '\\'')"
        	+"comment"
        	+", false,'"+token+"');");
    div.appendChild(button);
}
