/**
 * Comments
 *
 * @author Boz
 * @classDescription UI functionality needed by comments.
 * @css
 *   .comment_preview
 *   .comment_teaser
 *   .comment_full
 *   .comment_seemore
 *   #commentform
 *   #commentscountdisplay
 *
 **/

mdp.app.Comments = function(settings){
    /* ---[ CLASS VARIABLES ]--- */
    var self = this;
    var options = $.extend({
        locked:false,
        pages:null,
        totalResults:null,
        startIndex:null,
        startPage:null,
        endPage:null,
        page:1,
        pagesPerPage:4,
        paginate:true,
        onInit:function(){},
        onPost:function(){},
        onSuccess:function(){},
        onError:function(msg){alert(msg);}
    },settings || {});

    /* public */

    /* private */

    /* ---[ CONSTRUCTOR ]--- */
    function init(){

        /* load coniguration */
        options = $.extend(options,{args:getParams()});

        var commentscountdisplay = $(".commentscountdisplay:first");
        if(commentscountdisplay != null){
            var text = commentscountdisplay.text();
            options.totalResults = parseInt(text,10);
            updatePagination();
            $(".commentscountdisplay").html(options.totalResults);
        }

        /* initialization code */
        setupEventListeners();

        /* setup facebook */
        var fbenabled = $("#fbenabled");
        if(fbenabled != null){
             if(fbenabled.attr("fb-init") == null){
            if(fbenabled.attr("data-apikey") == null){ alert("You Forget To Pass FBApiKey to the Comments Form Frag!"); }
            else{
                var apikey = fbenabled.attr("data-apikey");
                FB.init(apikey,"/common/common/facebook/xd_receiver.jsp");
            }
        }
        }

        /* character counter */
        var commenttext = $("#commenttext");
        var charcountdisplay = $("#charcountdisplay");
        if(commenttext != null && charcountdisplay != null){
            if(typeof(mdp.charCount) == "function"){
                new mdp.charCount(commenttext,parseInt(options.args.charCount,10),charcountdisplay,false);
            }
        }

        /* fire init event */
        options.onInit();
    }

    /* ---[ PUBLIC METHODS ]--- */
    this.nextPage = function(){
        this.getPage(options.page + 1);
    };

    this.prevPage = function(){
        this.getPage(options.page - 1);
    };

    this.getPage = function(page){
        options.page= options.args.page = page;
        getComments();
        updatePagination();
    };

    this.postToFacebook = function(comment){
        if(comment!= null){
            var template_data = $("#fbenabled").attr("data-templatedata");
            if(template_data != null){
                template_data = $.parseJSON(template_data);
                template_data["comment-body"] = comment;
                var action_links = [{'text':template_data["site-name"], 'href':template_data["content-url"]}];
//                FB.Connect.streamPublish(comment, template_data, action_links);
                FB.ui(
                   {
                     method: 'stream.publish',
                     message: comment,
                     attachment: template_data,
                     action_links: action_links,
                     user_message_prompt: ''
                   },
                   function(response) {}
                );
            }
        }
    };

    this.updateCommentDisplay = function(pageSize,pagesPerPage,page){
        options.args.pageSize = pageSize;
        options.pagesPerPage = pagesPerPage;
        this.getPage(page);
    };

    this.setOption = function(key,value){
        options[key]=value;    
    };

    /* ---[ PRIVATE METHODS ]--- */
    function previewComment(){
        var link = this;

        /* get comment preview divs */
        var comment_preview = findParent(link,"comment_preview");
        var comment_teaser = $(".comment_teaser:first",comment_preview);
        var comment_full = $(".comment_full:first",comment_preview);

        /* animate and show full text */
        comment_teaser.html(comment_full.text());
        link.remove();
    }

    function findParent(el,_class){
        if(el.hasClass(_class)){
            return el;
        }
        else{
            return findParent(el.parent(),_class);
        }
    }

    function updatePagination(){
        /* calculate pages */
        if(options.totalResults > 0 && options.paginate){
            options.pages = Math.ceil(options.totalResults/options.args.pageSize);
            options.startIndex = options.page * options.args.pageSize;
            options.startPage = Math.ceil(options.page/options.pagesPerPage);
            if(options.page == options.pages){
                options.endPage = options.page;
            }else{
                options.endPage = options.pages<options.pagesPerPage?options.startPage+options.pages-1:options.startPage+options.pagesPerPage-1;
            }
            var pagination;
            var div;
            var pagesdiv;

            /* build pagination */
            div = $("<div>").attr({"class":"commentpagination"});

            if(options.page == 1){
                $("<a>").attr({"class":"pre disable"}).html("Prev").appendTo(div);
            }
            else{
                $("<a>").attr({"class":"pre"}).html("Prev").appendTo(div);
            }

            pagesdiv = $("<span>").attr({"class":"pages"}).appendTo(div);
            for(var j=options.startPage; j<=options.endPage; j++){
                if(j == options.page){
                    $("<a>").attr({"class":"unlink"}).html(j).appendTo(pagesdiv);
                }
                else{
                    $("<a>").html(j).appendTo(pagesdiv);
                }
                if(j<options.endPage){
                    pagesdiv.appendText(" | ");
                }
            }

            $("<span>").html(" of " + options.pages + " ").appendTo(pagesdiv);

            if(options.page==options.pages){
                $("<a>").attr({"class":"nxt disable"}).html("Next").appendTo(div);
            }else{
                $("<a>").attr({"class":"nxt"}).html("Next").appendTo(div);
            }

            /* replace old pagination */
            pagination = $(".commentpagination");
            for(var i=0; i<pagination.length; i++){
                pagination[i].replaceWith(div.clone());
            }

            if(options.page > 1){
                $(".pre").click(function(){
                    mdp.comments.prevPage();
                });
            }

            if(options.page < options.pages){
                $(".nxt").click(function(){
                    mdp.comments.nextPage();
                });
            }

            $(".pages a").click(function(){
                mdp.comments.getPage(parseInt($(this).text(),10));
            });
        }
        if(options.paginate===false){
            var commentpagination =  $(".commentpagination")[0];
            if(commentpagination){
                commentpagination.empty();
            }
        }
    }

    function getComments(updatePreview){
        $.ajax({
            url:"/common/socialmedia/commentsListFrag.jsp",
            data:options.args,
            success:function(html){
                $("#comments").html(html);
                updatePagination();
                if(updatePreview){
                    /* update the comment preview */
                    updateCommentPreview();
                }

                updateReportAbuseLinks();
        }});
    }

    function getParams(){
            var commenttext = $("#commenttext");
            var commentsitebrand = $("#commentsitebrand");
            var commentcontenttype = $("#commentcontenttype");
            var commentcontentid = $("#commentcontentid");
            var commentchildid = $("#commentchildid");
            var commentchannel = $("#commentchannel");
            var commentsubchannel = $("#commentsubchannel");
            var commentuserid = $("#commentuserid");
            var charcount = $("#charcount");
            var comments = $("#comments");
            var nocache = $("#nocache");
        return {
            commenttext:commenttext==null?"":commenttext.val(),
            sitebrand:commentsitebrand==null?"":commentsitebrand.val(),
            contentType:commentcontenttype==null?"":commentcontenttype.val(),
            contentId :commentcontentid==null?"":commentcontentid.val(),
            childId :commentchildid==null?"":commentchildid.val(),
            channel :commentchannel==null?"":commentchannel.val(),
            subchannel :commentsubchannel==null?"":commentsubchannel.val(),
            userId : commentuserid==null?"":commentuserid.val(),
            charCount : charcount==null?"":charcount.val(),
            pageSize:comments==null?"":comments.attr("data-pagesize"),
            dateFormat:comments==null?"":comments.attr("data-dateformat"),
            page:options.page,
            "no-cache":nocache==null?"":nocache.innerHTML
        };
    }

    function updateCommentPreview(){
        /* Get the first comment
        var comment = $(".commentdetail p:first").text();
        $(".comment_teaser").html(comment.length > 100?comment.substr(0,100) + "...":comment);
        $(".comment_full").html(comment);
        $(".comment_teaser").removeAttr("height");
        */
    }

    function updateReportAbuseLinks(){
        /* detect reportAbuse instance */
        if(typeof(mdp.reportAbuse) == 'object'){
            mdp.reportAbuse.reAttachEvents($("#comments"));
        }
    }

    /* ---[ EVENT LISTENERS ]--- */
    function setupEventListeners(){

        /* enable submit button */
        var commentsubmit = $("#commentsubmit");
        if(commentsubmit != null){
            commentsubmit.removeAttr("disabled");
        }

        /* Comment preview event handler */
        $(".comment_seemore").click(previewComment);

        /* Comment Form */
        var commentform = $("#commentform");
        if(commentform != null){
            $("#commentform").submit(function(e){
                e.preventDefault();
                    /* get form values */
                    options.args.commenttext = $("#commenttext").val();

                    /* send to facebook */
                    var fbenabled = $("#fbenabled");
                    if(fbenabled != null && fbenabled.val() == "on"){
                        self.postToFacebook(options.args.commenttext);
                    }

                    /* submit comment */
                    if(!options.locked){
                        /* fire post event */
                        options.onPost();

                        options.locked = true;
                        SocialMediaService.submitNewComment(options.args.sitebrand,
                                options.args.contentType,
                                options.args.contentId,
                                options.args.childId,
                                options.args.channel,
                                options.args.subchannel,
                                options.args.userId,
                                options.args.commenttext,
                                function(remoteResult){
                            options.locked = false;
                            if(remoteResult.statusCode == 0){
                                /* Update total results */
                                options.totalResults = remoteResult.result.count;

                                /* reset pagination */
                                options.page = 1;

                                /* refresh comments and rebuild pagination */
                                getComments(true);

                                /* clear comment form */
                                $("#commenttext").value = "";

                                /* update comment count displays */
                                $(".commentscountdisplay").html(options.totalResults);

                                /* fire post event */
                                options.onSuccess();
                            }
                            else{
                                /* fire error handling event */
                                alert(remoteResult.statusMessage);
                                options.onError(remoteResult.statusMessage);
                            }
                        });
                    }
            });
        }

    }

    /* ---[ RUN ]--- */
    init();
};

$(document).ready( function(){
    mdp.comments = new mdp.app.Comments(mdp.commentOptions || {});
});

