/**
 * Title: BBCWORLDWIDE_CPLAT.SaveComment
 * Copyright: Copyright (c) 2008
 * Company: BBC Worldwide Ltd
 * Description: Handles Javascript submit for Save Ugc flow
 * @author: SaxenNW1
 * @version: $Revision: $
 * @date: 21 July 2008 16:05:29
 */


/**
 * This define the BBCWORLDWIDE_CPLAT.Ugc Class - overrrides the singleton common BaseObject
 * @param base {@link BBCWORLDWIDE_CPLAT.BaseObject}
 * @return  BBCWORLDWIDE_CPLAT.Ugc {@link  BBCWORLDWIDE_CPLAT.Ugc}
 */
BBCWORLDWIDE_CPLAT.Comment = function(base, p_oParams) {

    /**
     * p_oParams - comment configuration params :
     *    cplatContainer:   the container DIV id
     *    truncateLength:   the length comment text will be truncated too
     *    voteUrl:          the client application URL for posting a vote
     */
    base.setclientConfigParams(p_oParams);

    // when doc has loaded add click handlers to voting links and add trunctae plugin to commentText
    $(document).ready(function() {
        // add truncate functionality to comment text
        $(".cplatTruncatedMoreLess").truncate( base.getClientConfigParams().truncateLength, {
            chars: /\s/,
            trail: [ " ( <a href='#' class='truncate_show'>more</a> . . . )", " ( . . . <a href='#' class='truncate_hide'>less</a> )" ]
        });
        // add click event handlers onto the voting buttons/text
        $("a.voteYes").click(voteYes);
        $("a.voteNo").click(voteNo);
        //$("#cplat-moderateCommentSubmit").click(moderate);
         expandModerationBox();




    });

    // add the form validation messages + rules
    base.addValidation = function (oForm) {
        $(oForm).validate({rules:base.getValidationRules(),messages:base.getValidationMessages()});
    };


    /**
     * Expands the moderation box to show the moderation form
     *
     */
    function expandModerationBox() {
        $('p.cplat-commentModerate, input.cplat-cancel-button').click(function() {

            var answer = $(this).next('div.cplat-commentModeration');
            if (answer.is(':visible')) {
                answer.slideUp('slow');
            } else {

                $('div.cplat-commentModeration:visible').slideUp('slow');
                answer.slideDown('slow');
            }

            return false;
        });

    }
    

    /**
     * Event handler for the onclick event of the Vote YES button/link
     */
    function voteYes() {
        return vote(this, true);
    };

    /**
     * Event handler for the onclick event of the Vote NO button/link
     */
    function voteNo() {
        return vote(this, false);
    };

    /**
     * Do and AJAX POST of the vote to CPLAT (via the client)
     * @param useful - boolean true if voting useful
     */
    function vote(element, useful){
        var clickedurl = $(element).attr("href");
        var commentIdParam = clickedurl.match(/cplat_commentId=.+/)[0];
        var commentId = commentIdParam.substring(commentIdParam.indexOf("=")+1);
        var url = p_oParams.voteUrl + "?ajaxRequestURL=/comment-vote/" + commentId + "&useful=" + (useful ? "true" : "false");
        eval("var voteSuccessCallbackProxy = function(data) {voteSuccessCallback('" + commentId + "', data);};");
        eval("var voteErrorCallbackProxy = function(data) {voteErrorCallback('" + commentId + "', data);};");
        base.ajaxGet(url, "POST", "ajaxRequest=true", voteSuccessCallbackProxy, voteErrorCallbackProxy, null, votingCompleteCallback);
        return false;
    };

    /**
     * removes the error status message
     */
    function removeStatusMessage(commentId){
        $("#cplat-commentVoting"+commentId).find(".commSaveStatus").remove();
    };

    /**
     * Success callback from Ajax Vote POST
     */
    var voteSuccessCallback = function(commentId, data){
        $("#cplat-commentVoting"+commentId).html(data);
    };

    /**
     * Error callback from Ajax Vote POST
     */
    var voteErrorCallback = function(commentId, xhr){
        removeStatusMessage(commentId);
        $("#cplat-isThisUseful"+commentId).after("<label class='commSaveStatus'>There was an error and your vote was not registered</label>");
        setTimeout(new function(){removeStatusMessage(commentId);},10000);
    };

    /**
     * Called when voting ajax call has completed
     */
    var votingCompleteCallback = function(xhr, status){
        if (status=="success"){
            // write out the anonymous commentvote user cookie
            // using the value from the response header - expires after 1 year
            var anonId = xhr.getResponseHeader("CPLAT_COMMENT_VOTE_ANON_USER_ID");
            $.cookie('CPLAT_COMMENT_VOTE_ANON_USER_ID', anonId, { expires: 365, path: '/' });
        }
    };


    /**
     * Do and AJAX POST of the vote to CPLAT (via the client)
     * @param useful - boolean true if voting useful
     */
//    function moderate(){
//       // if (moderateValidation()) {
////        var moderateDiv = $("#mplat-contentModeration");
////        var requestParameters = base.retrieveRequestParametersFromContainer(moderateDiv);
////        var commentId =  $("#mplat-contentModeration").find("input[name='mplat_resource_uuid']").val();
////        var url = p_oParams.moderationUrl + "?ajaxRequestURL=/createWorkRequest.do";
////        eval("var moderateSuccessCallbackProxy = function(data) {moderateSuccessCallback('" + commentId + "', data);};");
////        eval("var moderateErrorCallbackProxy = function(data) {moderateErrorCallback('" + commentId + "', data);};");
////        base.ajaxSubmit(self, url, "POST", requestParameters, moderateSuccessCallbackProxy, moderateErrorCallbackProxy);
//      //  }
//        return false;
//    };


//    /**
//     * Success callback from Ajax moderation POST
//     */
//    var moderateSuccessCallback = function(commentId, data){
//        $("#cplat-commentModeration"+commentId).html(data);
//        $("#cplat-commentModeration"+commentId).after("<label>Successfully saved</label>");
//    };
//
//    /**
//     * Error callback from Ajax moderation POST
//     */
//    var moderateErrorCallback = function(commentId, XMLHttpRequest, data){
//
//         var queryString = XMLHttpRequest.getResponseHeader("queryString");
//
//        if (queryString !=  null) {
//            if (queryString.indexOf("mplat-error_checkbox") != -1 && $("#mplat-reason"+commentId).get(0) !== undefined) {
//                $("#mplat-reason"+commentId).before("<label>" + base.getValidationMessages().mplat-reason + "</label>");
//           }
//
//            if (queryString.indexOf("mplat-error_note") != -1 && $("#mplat-note"+commentId).get(0) !== undefined) {
//                $("#mplat-note"+commentId).before("<label>" + base.getValidationMessages().mplat-notes + "</label>");
//            }
//        }
//
//    };
//
//
//    function moderateValidation() {
//
//            var commentId = $('form').find("input[name='mplat_resource_uuid']").val();
//            var valid = true;
//            if ($('form').find("input#mplat_remReasonOTH").attr("checked") != 'true' || $('form').find("input#mplat_remReasonABU").attr("checked") != 'true' || $('form').find("input#mplat_remReasonCOM").attr("checked") != 'true' || $('form').find("input#mplat_remReasonCOP").attr("checked") != 'true') {
//
//                alert("yo 1");
//                //$('form').find("#mplat-reason"+commentId).before("<label>" + base.getValidationMessages().mplat-reason + "</label>");
//                valid = false;
//            }
//            if ($('form').find("textarea#mplat_notes").val().length == 0 && $('form').find("input#mplat_remReasonOTH" + commentId).attr("checked")) {
//                alert("yo 2");
//                // $('form').find("#mplat-note"+commentId).before("<label>" + base.getValidationMessages().mplat-notes + "</label>");
//                valid = false;
//            }
//            return valid;
//
//    }


    
    return base;
};