                        /*
 * Javascript for submission view page.
 */

/*
 * Rico interface
 */

function doOnLoad() {
    registerAjaxStuff();
    loadPrivateFontSize();
    onLoadEditComment();
    applyAnchors();
}

Event.observe(window, 'load', doOnLoad);

function applyAnchors() {
    var doLater = null;
    try {
        if (window.location.hash && window.location.hash.length > 0) {
            var hash = window.location.hash;
            if (hash == "#comments") {
                // not sure this call is needed...
                getCommentsTab();
                return;
            }
            if (hash.indexOf("#comment") == 0) {
                var hashCommentId = hash.substring(8);
                getCommentById(cid);
                return;
            }
            if (hash.indexOf("#page") == 0) {
                var pageNum = hash.substring(5);
                changeFullPage(pageNum);
                return;
            }
            if (hash.indexOf("#editcomment") == 0) {
                doLater = function() {window.setTimeout(scrollToEditComment, 200);};
                // don't return
            }
        }
    } catch (e) {
        // if there's an error, show the full tab and re-throw
        getFullTab();
        throw e;
    }
    if (doLater != null) {
        doLater();
    }
}

// these are the state variables for all tabs
// submissionId needs to be set by users of these scripts
var fullPagenum = 1;          // current page number for text
var commentsPagenum = 1;      // current page number for comments
var commentsSort = "";        // current sort option for comments

var myFontSize = 100;         // default font size in percent

function registerAjaxStuff() {
    ajaxEngine.registerRequest( 'getFullTab',
        '/submission/view/ajaxFullSnippet.dos' );
    ajaxEngine.registerRequest( 'getCommentsTab',
        '/submission/view/commentsSnippet.dos' );
    ajaxEngine.registerRequest("comment", 
        "/comment/create.dos");
    ajaxEngine.registerRequest( 'setScore', 
        '/submission/score.dos' );
    ajaxEngine.registerRequest( 'removeScore', 
        '/submission/removeScore.dos' );
    ajaxEngine.registerRequest( 'addFavorite', 
        '/submission/view/addFavorite.dos' );
    ajaxEngine.registerRequest( 'deleteFavorite', 
        '/submission/view/deleteFavorite.dos' );
    ajaxEngine.registerRequest( 'setCommentScore', 
        '/comment/score.dos' );

    ajaxEngine.registerAjaxElement("editCommentContainer");

    ajaxEngine.registerAjaxObject("toolBarControl", new ToolBarControl());
    ajaxEngine.registerAjaxObject("ajaxScoreHandler", new AjaxScoreHandler());
    ajaxEngine.registerAjaxObject("updateScoreControl", new UpdateScoreControl());
    ajaxEngine.registerAjaxObject("ajaxUpdateCommentTotal", new AjaxUpdateCommentTotal());
    ajaxEngine.registerAjaxObject("ajaxScrollToComment", new AjaxScrollToComment());
    ajaxEngine.registerAjaxObject("ajaxSetCommentPageNumber", new AjaxSetCommentPageNumber());
    ajaxEngine.registerAjaxObject("ajaxScrollToTop", new AjaxScrollToTop());
    ajaxEngine.registerAjaxObject("ajaxResetEditComment", new AjaxResetEditComment());
}

function AjaxResetEditComment() {
    this.ajaxUpdate = function(ajaxResponse) {
        onLoadEditComment();
    }
}

function AjaxScrollToTop() {
    this.ajaxUpdate = function(ajaxResponse) {
        scrollToTop();
    }
}

// object to update fields upon ajax calls - for now just the page#
function ToolBarControl() {
    this.ajaxUpdate = function(ajaxResponse) {
        var pn = ajaxResponse.childNodes[0].nodeValue;
        fullPagenum = parseInt(pn);
        // record the page in the URL so a user can bookmark this page
        // only do this for pages past 1, since 1 is obviously the first
        // one that they see, and only do it if the page has actually
        // changed
        if (window.location.hash && window.location.hash.length > 0) {
            var hash = window.location.hash;
            if (hash.indexOf("#page") == 0) {
                var pageNum = parseInt(hash.substring(5));
                if (pageNum != fullPagenum) {
                    window.location.hash = 'page' + fullPagenum;
                }
            }
        }
        else if (fullPagenum > 1) {
            window.location.hash = 'page' + fullPagenum;
        }
    }
}

// object to scroll to the selected comment
function AjaxScrollToComment() {
    this.ajaxUpdate = function(ajaxResponse) {
        var cid = ajaxResponse.firstChild.nodeValue;
        if (cid != null) {
            // oddly, you don't write the '#' into this field, even though it's there when you read it back
            cid = "comment" + cid;
            window.location.hash = cid;
        }
    }
}

function AjaxSetCommentPageNumber() {
    this.ajaxUpdate = function(ajaxResponse) {
        var pn = ajaxResponse.firstChild.nodeValue;
        if (pn != null) {
            commentsPagenum = pn;
        }
    }
}

function getFullTab() {
    ajaxEngine.sendRequest('getFullTab',
        "submissionId=" + submissionId,
        "page=" + fullPagenum,
        ((typeof(submissionInWorkspace) != "undefined" && submissionInWorkspace) ? "submissionInWorkspace=1" : "") );
}

function getCommentsTab() {
    
    ajaxEngine.sendRequest('getCommentsTab',
        "submissionId=" + submissionId,
        "page=" + commentsPagenum,
        (commentsSort != null && commentsSort.length > 0 ? "sort=" + commentsSort : ""));
}

function nextFullPage() {
    // user pressed next page when full tab open
    fullPagenum++;
    getFullTab();
    return false;
}

function backFullPage() {
    // user pressed next page when full tab open
    if (fullPagenum > 1) {
        fullPagenum--;
        getFullTab();
    }
    return false;
}

function changeFullPage(page) {
    // user selected a new page
    fullPagenum = parseInt(page);
    getFullTab();
    return false;
}

// change to first page of given chapter
function changeChapter(page) {
    // user selected a new chapter
    var chapter = parseInt(page);
    ajaxEngine.sendRequest('getFullTab',
        "submissionId=" + submissionId,
        "chapter=" + chapter,
        ((typeof(submissionInWorkspace) != "undefined" && submissionInWorkspace) ? "submissionInWorkspace=1" : "") );
    return false;
}


function nextCommentsPage() {
    commentsPagenum++;
    getCommentsTab();
    return false;
}

function backCommentsPage() {
    if (commentsPagenum > 1) {
        commentsPagenum--;
        getCommentsTab();
    }
    return false;
}

function updateCommentsSort(option) {
    // user selected new sort in drop down
    commentsSort = option.value;
    commentsPagenum = 1;        // reset page
    getCommentsTab();
    return false;
}

function AjaxUpdateCommentTotal() {
    this.ajaxUpdate = function(ajaxResponse) {
        var count = ajaxResponse.firstChild.nodeValue;
        els = document.getElementsByClassName("commentTabCount");
        els.each(function (el) {
            el.innerHTML = count;
        })
    }
}

function markAsFavorite() {
    ajaxEngine.sendRequest('addFavorite', {
        method: 'post',
        parameters: { 'submissionId': submissionId }
    });
}

function unmarkAsFavorite() {
    ajaxEngine.sendRequest('deleteFavorite', {
        method: 'post',
        parameters: { 'submissionId': submissionId }
    });
}

var currentScore = 0;       // current user score

// object to set current score upon ajax calls
function UpdateScoreControl() {
    this.ajaxUpdate = function(ajaxResponse) {
        var cs = ajaxResponse.childNodes[0].nodeValue;
        currentScore = parseInt(cs);
        // this looks odd, but we need to reset any caching of 
        // elements because we get this callback when we are switching
        // to a new submission with a new set of score stars
        scoreDivs = null;

        // TODO: This is too page specific to be here
        // always move the screen to the display area after updating
        var el = $('previewAnchor');
        if (el != null) {
            el.scrollTo(500);
        }

    }
}

function AjaxScoreHandler() {
    this.ajaxUpdate = function(ajaxResponse) {
        var selection = ajaxResponse.firstChild.nodeValue;
        currentScore = selection;
        // until we have diff icons then just use highlighter
        highlightUserScore(currentScore);
        // show the thank you msg
        var div = $('editscoreMessage');
        if (div != null) {
            div.show();
        }
    }
}

/**
    * Highlight on rollover the score where we are.
    * For this to work you need imageGreen and imageWhite to be defined.
    *
    * This looks a little weird because it's optimized to not use 
    * document.getElementsByClassName, which is slow on safari.  (see bug 324)
    */
var scoreDivs = null;
function highlightUserScore(score) {
    if (scoreDivs == null) {
        scoreDivs = [];
        var divs = $('movieOptionStatistic').getElementsByTagName("DIV");
        for (var i = 0; i < divs.length; i++) {
            var n = Element.extend(divs[i]);
            if (n.hasClassName("editscore")) {
                scoreDivs[scoreDivs.length] = n;
            }
        }
    }
                                                                                  for (var i = 0; i < scoreDivs.length; i++) {
        var scoreDiv = scoreDivs[i];
        for (var j = 1; j <= 5; j++) {
            var el = scoreDiv.down("img.score" + j);
            if (j <= score) {
                el.setAttribute("src", "/cms/r/denim/img/stars_episodes_on.gif");
            } else {
                el.setAttribute("src", "/cms/r/denim/img/stars_episodes_off.gif");
            }
        }
    }
}


/**
    * Set the score to the value of the 'selection' parameter.  On success, 
    * a callback updates the score display (this is the backend of the 
    * fan:edit-score tag).
    * 
    * @author justin
    */
function setScore(selection) {
    ajaxEngine.sendRequest('setScore', {
        method : 'post',
        parameters : { 
            submissionId : submissionId, 
            score : selection
        }
    });
}

/**
    * Set "like" to the submission (value = 9).  On success, 
    * a callback updates the like display (this is the backend of the 
    * fanview:like-box tag).
    * 
    * @author barney
    */
function setLike() {
    ajaxEngine.sendRequest('setScore', {
        method : 'post',
        parameters : { 
            submissionId : submissionId, 
            score : 9
        }
    });
}

/**
    * Remove "like" from the submission (value = 0).  On success, 
    * a callback updates the like display (this is the backend of the 
    * fanview:like-box tag).
    * 
    * @author barney
    */
function removeLike() {
    ajaxEngine.sendRequest('removeScore', {
        method : 'post',
        parameters : { 
            submissionId : submissionId
        }
    });
}

/*
    * It is extremely non-obvious, but if you try this call without setting 
    * options.parameters (even to an empty hash {}), the request will fail 
    * with the Javascript exception 
    * 'uncaught exception: Permission denied to get property Object.constructor'.
    * 
    * This is a Rico bug.
    * 
    * -jwh
    */
function editComment() {
    ajaxEngine.sendRequestWithData('comment', 
        Form.serialize($('writecommentform')), {parameters : {}});
}


/*
    * Private font size selection in read box.
    */
function loadPrivateFontSize() {
    if (parseInt(getCookie('fontsize')) > 0) {
        myFontSize = parseInt(getCookie('fontsize'));
        if (myFontSize < 40 || myFontSize > 300) {
            myFontSize = 100;     // failsafe if cookie gets trashed
        }
        setFontSize();
    }
}

function reduceFontSize() {
    if (myFontSize >= 60) {
        myFontSize = myFontSize - 20;
    }
    setFontSize();
    return false;
}
function increaseFontSize() {
    if (myFontSize <= 280) {
        myFontSize = myFontSize + 20;
    }
    setFontSize();
    return false;
}

function setFontSize() {
    if (myFontSize < 40 || myFontSize > 300) {
        alert("font size wigged out: " + myFontSize);
        return;
    }
    setCookie('fontsize', myFontSize, 3600);      // 1 hour???
    var rbe = $("readBox");
    if (rbe != undefined) {
        rbe.style.fontSize=myFontSize+'%';
        /* may not need to force redraw - check out safari first
        rbe.display='none';
        rbe..display='block';
        */
    }
}


function getCommentById(cid) {
    ajaxEngine.sendRequest('getCommentsTab', {
        parameters : {
            submissionId : submissionId, 
            commentId : cid, 
            page : 1
        }
    });
}

/**
    * Set the comment score to the value of the 'score' parameter.  On 
    * success, a callback that updates the count on the page.
    * 
    * @author justin
    */
function setCommentScore(commentId, score, oldScore) {
    ajaxEngine.sendRequest('setCommentScore', {
        method : 'post',
        parameters : { 
            commentId : commentId, 
            score : (score == 0 ? 0 : 1),
            oldScore : oldScore
        }
    });
}

function scrollToTop() {
    // we could do this with anchors, but this keeps from changing the URL
    var pos = Position.page($('topAnchor'));
    if (pos[1] < 0) {
        // this scrolls to the location of topAnchor  -jwh
        //var xy = Position.cumulativeOffset($('topAnchor'));
        //window.scrollTo(0, xy[1]);
        
        // this scrolls to the top instead
        window.scrollTo(0, 0);
    }
}

function scrollToEditComment() {
    // we do this with script because the position of the control changes after 
    // the tabs get loaded
    var pos = Position.page($('editCommentAnchor'));
    if (pos[1] > 0) {
        // this scrolls to the location of topAnchor  -jwh
        var xy = Position.cumulativeOffset($('editCommentAnchor'));
        window.scrollTo(0, xy[1]);
    }
}

function onLoadEditComment() {
    if ($("commentEditBody")) {
        Event.observe($("commentEditBody"), "focus", function() {
            var el = $("commentEditBody");
            if (el.hasClassName("empty")) {
                el.value = "";
                el.removeClassName("empty");
            }
        });
        Event.observe($("commentEditBody"), "blur", blurEditCommentBody);
        // you need this in case the browser "remembers" the old values of the form
        if ($("commentEditBody").value == commentBodyMsg) {
            $("commentEditBody").value = "";
        }
        blurEditCommentBody();
    }
}

function blurEditCommentBody() {
    var el = $("commentEditBody");
    if (el.value.length < 1) {
        el.value = commentBodyMsg;
        el.addClassName("empty");
    }
}

function clearEmpties() {
    var els = [$("commentEditBody")];
    for (var i = 0; i < els.length; i++) {
        if (els[i].hasClassName("empty")) {
            els[i].value = "";
        }
    }
}

function replyToComment(e) {
    var el = Element.extend(Event.element(e));
    var elf = el.up("div.commentControls").down("form.replyForm");
    el.hide();
    elf.show();
}

function replyToComment(e) {
    var el = Element.extend(Event.element(e));
    var elf = el.up("div.commentControls").down("form.replyForm");
    el.hide();
    elf.show();
}

function unreplyToComment(e) {
    var el = Element.extend(Event.element(e));
    var elf = el.up("div.commentControls").down("form.replyForm");
    var elb = el.up("div.commentControls").down("a.commentReplyButton");
    elf.hide();
    elb.show();
}

function editCommentReply(e) {
    var el = Element.extend(Event.element(e));
    el = (el.tagName.toLowerCase() == "form") ? el : el.up("form");
    ajaxEngine.sendRequestWithData('comment', 
        Form.serialize(el), {parameters : {}});
}

function highlightThumbs(el, state) {
    switch (state) {
        case 'up':
                                                   el.setAttribute("src", "/cms/r/denim/img/icon_thumbs_up.gif");
            break;
        case 'ups':                                        el.setAttribute("src", "/cms/r/denim/img/icon_thumbs_up_green.gif");
            break;
        case 'down':                                        el.setAttribute("src", "/cms/r/denim/img/icon_thumbs_down.gif");
            break;
        case 'downs':                                        el.setAttribute("src", "/cms/r/denim/img/icon_thumbs_down_red.gif");
            break;
    }
}