Array.prototype.contains = function (element) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}


var Comment = Class.create({
        initialize: function(issueId, threadId, isReply, commentId, commentRate, issueRate) {
            this.issueId = issueId;
            this.threadId = threadId;
            this.isReply = isReply;
            this.commentId = commentId;
            this.commentRate = commentRate;
            this.issueRate = issueRate;
        },
        createForm: function(){
            createCommentForm(this.issueId, this.threadId, this.isReply, this.commentId);
        },
        updateUI: function(){
            updateUserInterface(this.commentId, this.commentRate);
        },
        sendCommentRate: function(){
            sendCommentRates(this.commentId, this.commentRate);
        },
        getColorCode: function(color){
            color = parseInt(color);
            switch(color){
                case 0:
                    return "red";
                case 1:
                    return "orange";
                case 2:
                    return "yellow";
                case 3:
                    return "chartreuse";
                case 4:
                    return "darkgreen"
                default:
                    return "transparent"
            }
        }
    });

var newComment = new Comment();
Comment.numOfObjects = 0;


function addComment(issueId, threadId, isReply, commentId){
    if (commentId != null){
        var parentDiv = Element.extend($(issueId + "_" + threadId + commentId));
    }else
        var parentDiv = Element.extend($(issueId + "_" + threadId));
    if (parentDiv.innerHTML != ""){
        Effect.BlindUp(parentDiv, {afterFinish: function(effect){
                                                    parentDiv.innerHTML = "";
                                                    parentDiv.style.display = 'none';} ,hduration: 0.8 });        
        return false;
	}
    if (Comment.numOfObjects > 0){
        return false;
    }
    Comment.numOfObjects++;
    newComment = new Comment(issueId, threadId, isReply, commentId, null, null);
    newComment.onSuccessfulLogin = function(){
        newComment.createForm();
        newComment.updateUI();
    };
    new Ajax.Request(pageContext + '/login/isLoggedIn?' + (new Date()).getTime(), {
      method: 'get',
        onSuccess: function(response) {
            var resp = response.responseText;
            if (resp.toLocaleLowerCase() == "true"){
                newComment.createForm();
            }else{
                openLoginDialog(newComment.onSuccessfulLogin);
            }
            Comment.numOfObjects=0;
        },
        onException: function(req, exception) {
            Comment.numOfObjects=0;
        },
        onFailure: function(response){
            Comment.numOfObjects=0;
        }
    });
}

function modifyCommentRate(commentId, rate){
    if (Comment.numOfObjects > 0){
        return false;
    }
    Comment.numOfObjects++;
    var newComment = new Comment(null, null, null, commentId, rate, null);
    newComment.onSuccessfulLogin = function(){
        newComment.sendCommentRate();
    };
    new Ajax.Request(pageContext + '/login/isLoggedIn?' + (new Date()).getTime(), {
      method: 'get',
        onSuccess: function(response) {
            var resp = response.responseText;
            if (resp.toLocaleLowerCase() == "true"){
                newComment.onSuccessfulLogin();
            }else{
                openLoginDialog(newComment.onSuccessfulLogin);
                Comment.numOfObjects = 0;
            }
        },
        onException: function(req, exception) {
            Comment.numOfObjects=0;
        },
        onFailure: function(response){
            Comment.numOfObjects=0;
        }
    });
}


function sendCommentRates(commentId, commentRate){
    var params = "comment_id=" + commentId + "&rate=" + commentRate;
    new Ajax.Request(pageContext + '/publication/commentVote', {
        method: 'POST',
        postBody: params,
        onSuccess: function(response) {
            updateUserInterface(commentId, commentRate);
        },
        onException: function(req, exception) {
            Comment.numOfObjects=0;
        },
        onFailure: function(response){
            Comment.numOfObjects=0;
        }
    });
}

function createCommentForm(issueId, threadId, isReply, commentId){
	var url = pageContext + "/publication/checkCaptcha";
    //get parent div
    if (commentId != null)
        var parentDiv = document.getElementById(issueId + "_" + threadId + commentId);
    else
        var parentDiv = document.getElementById(issueId + "_" + threadId);
	if (parentDiv.innerHTML != ""){
		parentDiv.innerHTML = "";
		return false;
	}
	//create container div
	var newdiv = document.createElement("div");
	newdiv.style.margin = "10px";
	// create form
	var myForm = document.createElement("form");
    myForm.setAttribute("name", "comment");
    myForm.setAttribute("action", pageContext + "/publication/addNewComment");
    //Create textarea title
    var titleContainer = document.createElement("span");
    var title;
    if (isReply)
        title = document.createTextNode(strCommentFormTitle1 + ":");
    else
        title = document.createTextNode(strCommentFormTitle2 + ":");
    titleContainer.className = "commentTitle";
    titleContainer.appendChild(title);
    myForm.appendChild(titleContainer);
    // create textarea
	var rTextbox = document.createElement("textarea");
    rTextbox.setAttribute("name", "text");
    rTextbox.rows = "6";
	rTextbox.cols = "10";
	rTextbox.style.border = "1px solid gray";
	rTextbox.style.width = "98%";
	//rTextbox.style.height = "12em";
	// create button
    var buttonContainer = document.createElement("div");
    buttonContainer.setAttribute("align", "right");
    buttonContainer.style.marginTop = "-2em";
    var submitButton = document.createElement("button");
    buttonContainer.appendChild(submitButton);
    var theText=document.createTextNode(strSubmitButton);
	submitButton.appendChild(theText);
    //button onclick event
    submitButton.onclick=function() {
        issueRate.value = newComment.issueRate;
        new Ajax.Request(url, {
          method: 'get',
          parameters:{captcha: myForm.captcha.value},
            onSuccess: function(tr) {
            var notice = $('notice');
            if (tr.responseText.match(/success/)){
                if (rTextbox.value == ""){
                    notice.update("<br>" + strEmptyFormError).setStyle({ color: 'red' });
                }else{
                    myForm.submit();
                }
            }else{
                notice.update("<br>" + strCaptchaError).setStyle({ color: 'red' });
            }
          }
        });
        return false;
    };
    //ranking div container
    var ratingDiv = document.createElement("div");
    ratingDiv.style.cssFloat = "right";
    ratingDiv.style.styleFloat = "right";
    ratingDiv.setAttribute("align","right");
    ratingDiv.innerHTML = "<b>" + rateQuestion + "</b>" +
                          "<table class=\"votingText\"><tr>" +
                          "<td align=\"right\" valign=\"middle\">" +
                          rateWeak + "</td><td align=\"center\" valign=\"middle\">" +
                          "<table onmouseout=\"voteMouseOutTable()\" cellspacing=\"1px\" class=\"voting\"><tr>" +
                          "<td onmouseout=\"voteMouseOutTd(this)\" onmouseover=\"voteMouseOver(this)\" onclick=\"voteClicked(this);\" id=\"vote0\"></td>" +
                          "<td onmouseout=\"voteMouseOutTd(this)\" onmouseover=\"voteMouseOver(this)\" onclick=\"voteClicked(this);\" id=\"vote1\"></td>" +
                          "<td onmouseout=\"voteMouseOutTd(this)\" onmouseover=\"voteMouseOver(this)\" onclick=\"voteClicked(this);\" id=\"vote2\"></td>" +
                          "<td onmouseout=\"voteMouseOutTd(this)\" onmouseover=\"voteMouseOver(this)\" onclick=\"voteClicked(this);\" id=\"vote3\"></td>" +
                          "<td onmouseout=\"voteMouseOutTd(this)\" onmouseover=\"voteMouseOver(this)\" onclick=\"voteClicked(this);\" id=\"vote4\"></td>" +
                          "</tr></table></td>" +
                          "<td align=\"left\" valign=\"middle\">" +
                          rateExc + "</td></tr></table>"
    //captcha div container
    var captchaDiv = document.createElement("div");
	captchaDiv.innerHTML = strCaptchaHelper + "<span id='notice'></span>" +
                           "<br/><input type='text' name='captcha'/><br/>" +
                           "<img id='captcha' name=\"catcha\" align='absmiddle' src='" + pageContext + "/captcha?" + (new Date()).getTime() + "'/>" +
                           "<a href='' onclick='reloadCaptcha();return false;'>" +
                           "<img name=\"reload\" alt='reload image' style=\"padding-left:0.5em\" align='absmiddle' src='" + pageContext + "/imgs/icon16-reload.gif'/>" +
                           "</a>";
	//create hidden fields
	var issueIdField = document.createElement("input");
    issueIdField.setAttribute("name", "issue_id");
    issueIdField.setAttribute("type", "hidden");
	issueIdField.value = issueId;
    myForm.appendChild(issueIdField);
    if (isReply){
        var threadIdField = document.createElement("input");
        threadIdField.setAttribute("name", "thread_id");
        threadIdField.setAttribute("type", "hidden");
        threadIdField.value = threadId;
        myForm.appendChild(threadIdField);
    }
    //for proper reload
    var qsField = document.createElement("input");
    qsField.setAttribute("name", "qs");
    qsField.setAttribute("type", "hidden");
	qsField.value = qs;
    myForm.appendChild(qsField);
    var actNameField = document.createElement("input");
    actNameField.setAttribute("name", "action_name");
    actNameField.setAttribute("type", "hidden");
	actNameField.value = action_name;
    myForm.appendChild(actNameField);
    var issueRate = document.createElement("input");
    issueRate.setAttribute("name", "issue_rate");
    issueRate.setAttribute("type", "hidden");
    myForm.appendChild(issueRate);

    //build comment form DOM
	myForm.appendChild(rTextbox);
    myForm.appendChild(ratingDiv);
    myForm.appendChild(captchaDiv);
    myForm.appendChild(buttonContainer);
	newdiv.appendChild(myForm);
	parentDiv.appendChild(newdiv);
    Effect.BlindDown(parentDiv, {duration: 0.8 });
}

function reloadCaptcha(){
    document["captcha"].src = document["captcha"].src + '?' + (new Date()).getTime()
}

function updateUserInterface(id, rate){
    var commentedIds;
    new Ajax.Request(pageContext + '/publication/getUserRatedComment?' + (new Date()).getTime(), {
        method: 'get',
        onSuccess: function(response) {
            commentedIds = eval(response.responseText);
            var buttons = document.getElementsByClassName("commentRate");
            for (var j=0; j < buttons.length; j++) {
                if (commentedIds.contains(buttons[j].id)){
                    var children = $A($(buttons[j].id).descendants());
                    children.each(function(child) {
                        if(child.tagName && child.tagName.toUpperCase() == "A"){
                            if (child.className.indexOf("rateup") >= 0){
                                Element.replace(child, "<img src=" + pageContext + "/imgs/arrow_up_disabled.gif />");
                            }else if (child.className.indexOf("ratedown") >= 0){
                                Element.replace(child, "<img src=" + pageContext + "/imgs/arrow_down_disabled.gif />");
                            }
                            /*
                            if (child.firstDescendant().src.indexOf("down")<0){
                                child.firstDescendant().src = pageContext + "/imgs/arrow_up_disabled.png";
                                Element.replace(child, child.firstDescendant());
                            }else{
                                child.firstDescendant().src = pageContext + "/imgs/arrow_down_disabled.png";
                                Element.replace(child, child.firstDescendant());
                            }
                            */
                        }
                        if (id && id == buttons[j].id && rate && child.tagName && child.tagName.toUpperCase() == "SPAN"){
                            var newValue = parseInt(child.innerHTML) + rate;
                            child.update(newValue);
                        }
                    });
                }
            }
            Comment.numOfObjects=0;
        },
        onException: function(req, exception) {
            Comment.numOfObjects=0;
            /*
            alert("The request had a fatal exception thrown.\n\n" +
            exception);
            return true;
            */
        },
        onFailure: function(response){
            Comment.numOfObjects=0;
        }
    });
}

function expandAll(button){
    Element.extend(button);
    var exp = false;
    if (button.innerHTML.indexOf("+") == -1){
        button.update("Expand All [ + ]");
    }else{
        button.update("Collapse All [ &#8211; ]");
        exp = true;
    }
    var hiddenComments = document.getElementsByClassName("threadReply");
    for (var j=0; j < hiddenComments.length; j++) {
        if (exp)
            hiddenComments[j].hide();
        else
            hiddenComments[j].show(); 
        hiddenComments[j].next().firstDescendant().onclick.call();//update("&#171;&#32;less");
    }
}

function closeReply(id, button, size) {
    if(!$(id).visible()){
        $(id).show();
        //Effect.BlindDown(id, {duration: 1.0 });
        $(button).update("&#171;&#32;less");
    }else{
        //Effect.BlindUp(id, {duration: 1.0 });
        $(id).hide();
        if (size > 1)
            $(button).update(size + " Replies &#32;&#187;");
        else
            $(button).update(size + " Relpy &#32;&#187;");
    }
}

function voteMouseOver(cell){
    Element.extend(cell);
    var color = cell.previousSiblings().length;
    var colorCode = newComment.getColorCode(color);
    cell.setStyle({backgroundColor: colorCode});
    cell.previousSiblings().each(function(sibling) {
        sibling.setStyle({backgroundColor: colorCode});
    });
    cell.nextSiblings().each(function(sibling) {
            sibling.setStyle({backgroundColor:"transparent"});
        });
}

function voteMouseOutTable(){
    if (newComment.issueRate != null){
        var color = newComment.getColorCode(newComment.issueRate);
        var cell = document.getElementById("vote" + newComment.issueRate);
        cell.setStyle({backgroundColor:color});
        cell.previousSiblings().each(function(sibling) {
            sibling.setStyle({backgroundColor:color});
        });
        cell.nextSiblings().each(function(sibling) {
            sibling.setStyle({backgroundColor:"transparent"});
        });    
    }
}

function voteMouseOutTd(cell){
    Element.extend(cell);
    cell.setStyle({backgroundColor:'transparent'});
    cell.siblings().each(function(sibling) {
        sibling.setStyle({backgroundColor:'transparent'});
    });
}

function voteClicked(cell){
    Element.extend(cell);
    var vote = cell.id.charAt(cell.id.length-1);
    if (newComment.issueRate == vote){
        newComment.issueRate = null
    }else{
        newComment.issueRate = vote;
    }
}

function toggleRateButton(id){
    if ($(id).visible())
        Effect.SlideUp(id, {duration: 0.2 });
    else{
        Effect.SlideDown(id, {duration: 0.2 });
    }
}

function enlargeAvatar(image){
    new Effect.Scale(image, 200, {scaleMode: { originalHeight: 32, originalWidth: 32 }})
}

function reduceAvatar(image){
    new Effect.Scale(image, 50, {scaleMode: { originalHeight: 64, originalWidth: 64 }})
}
