﻿//verify to see if we have defined the global namespace.
if (typeof digidam === 'undefined') {
    digidam = {};
}

jQuery(document).ready(function () {

    jQuery("span.rateplus").click(function () {
        //alert("span.ratePlus");
        try {
            digidam.Comment.storeCommentRate(this, "plus");
        } catch (e) {
        } // TODO:print to console
        return false;
    });

    jQuery("span.rateminus").click(function () {
        //alert("span.rateMinus");
        try {
            digidam.Comment.storeCommentRate(this, "minus");
        } catch (e) {
        } // TODO:print to console
        return false;
    });



    /** Open comment to view its details */
    jQuery("a.commentTitle").click(function () {
        var commentId = digidam.Comment.getCommentId(this);
        digidam.Comment.toggleComment(commentId, this);
        return false; // Avoid the browser following the link
    });

    jQuery("#openCloseComments").click(function () {
        digidam.Comment.toggleAllComments();
    });



});

digidam.Comment = function () {

    var STATISTICS_SERVER_URL = "updateconmments.aspx";
    var errorMsgs = {
        addCommentError: [
				"serverError",
				"There has been a problem delivering your talkback to the system. Please try again later."],
        commentAuthorEmpty: ["authorError", "Please enter your name"],
        commentTitleEmpty: ["titleError", "Please fill in the 'subject' box"]
    };

    /** contentId of comments element, initialized on page load */
    var _serviceInstanceId;
    /** content ids path of current article, initialized on page load */
    var _articlePath;
    /**
    * if true the comments views and rating counts will be updated on
    * statistics server (defined by article 'age' in
    * PrepareCommentListCommand.java)
    */
    var _continueToUpdateStatisticsServer = true;

    return {
        initialize: function (id, articlePath) {
            _serviceInstanceId = id;
            _articlePath = articlePath;
            _continueToUpdateStatisticsServer = true;
        },

        /**
        * retrive comment id concatenated at the end of the tag id attribute
        * (assumes id is always of the following format ...-contentId)
        */
        getCommentId: function (tagObj) {
            var id = jQuery(tagObj).parent().parent().get(0).id; //.split("-");
            var commentId = id; // [id.length - 1]; // commentid is the last value
            // of the tag id
            return commentId;
        },

        getParentId: function (tagObj) {
            var parentid = "";
            var id = jQuery(tagObj).get(0).id.split("-");
            for (var i = 0; i < id.length; i++) {
                if (id[i] == "parentid") {
                    parentid = id[i + 1];
                }
            }
            return parentid;
        },
        saveComment: function (form) {
            // disable the send button to avoid multiple form submissions
            digidam.Comment.toggleButton(form);
            // display in progress gif
            jQuery("img.inProgress", form).show();
            // in case of server response failure, hide the progress image
            setTimeout(function (form) {
                digidam.Comment.hideInProgressImg(form);
                // verify that the talkback form submit button is enabled
                digidam.Comment.enableTalkbackSubmit();
            }, 2000, form);

            // clean the error messages from the form
            jQuery(".commentError", form).each(function () {
                jQuery(this).html("");
            });
            // TODO:validate the form

            // save the comment
            this.storeCommentOnServer(form);
        },
        /**
        * enable/disable the talkback submit button to avoid multiple sending of talkback form
        */
        toggleButton: function (formObj) {
            var button = jQuery('.btn-send', formObj);
            var disabled = button.attr('disabled');
            if (disabled == true) {
                button.removeAttr('disabled');

            }
            else {
                button.attr('disabled', true);
            }
        },

        enableTalkbackSubmit: function () {
            // goes over all the forms in the page and set their disabled state to false
            $('form').each(function () {
                $(this).find('.btn-send').removeAttr('disabled')
            }
			);
        },
        /**
        * submit the comment.
        */
        storeCommentOnServer: function (formObj) {

            var userStatus = digidam.Facebook.getUserStatus();
            switch (userStatus) {
                case FACEBOOK_LOGGED_IN:
                    // get comment author name, add it to the hidden form data.
                    var username = jQuery("h4 a", formObj).html();
                    var facebookid = digidam.Facebook.getFacebookId();
                    jQuery("#comment_author", formObj).val(username);
                    // get facebook id of the currently logged in user, add it to the hidden form data
                    jQuery("#facebookUID", formObj).val(facebookid);
                    digidam.Facebook.submitComment(formObj);
                    break;
                case FACEBOOK_LOGGED_0UT:
                    // get comment author name, add it to the hidden form data.
                    jQuery("#comment_author", formObj).val(
						jQuery(".loggedOut", formObj).val());
                    break;
                case ANONYMOUS:
                    // get comment author name, add it to the hidden form data.
                    jQuery("#comment_author", formObj).val(
						jQuery(".anonymous", formObj).val());
                    break;
                default:
                    alert("user status not found");
            }

            // get all input form data in current form
            var inputs = formObj.serialize();

            // submit the comment
            try {
                jQuery.ajax({
                    cache: false,
                    url: "/cmlink/" + _serviceInstanceId,
                    data: inputs,
                    type: "POST",
                    success: function (data, status) {
                        storeCommentCallback(data, status);
                    },
                    timeout: 3000,
                    dataType: 'json'
                });
            } catch (e) {
                // TODO: do something
            }
        },

        /**
        * update view count of given comment on statistic server TODO: remove
        * view count servlet
        */
        updateCommentViewStatus: function (commentId) {
            if (_continueToUpdateStatisticsServer) {
                jQuery.ajax({
                    data: {
                        type: "COMMENTS_VIEWS", // comment views analyzer
                        // message type (see
                        // ConfigInstances.properties)
                        a: _articlePath,
                        comment: commentId
                    },
                    error: function () { },
                    success: function (data, status) { /*
														 * alert(data + " | " +
														 * status);
														 */
                    },
                    timeout: 3000,
                    type: "GET",
                    // url : "/comments/viewcounter"
                    url: STATISTICS_SERVER_URL
                });
            }
        },

        /** updates given comment rating, liked/not liked */
        storeCommentRate: function (comment, ratingType) {
            var commentId = this.getCommentId(comment);
            // update rating only if the article is new (currently two week old)
            //if (_continueToUpdateStatisticsServer){
             jQuery.get(STATISTICS_SERVER_URL+"?artimovieid="+commentId+"&"+ratingType+"=1&plus=0&minus=0");
            //} else {
                // if the article is old, update the client display only without
                // really sending the data.
                storeCommentRateCallback("", "success", commentId, ratingType)
            //}
        },

        /** display a reply form near the clicked comment */
        showTalkbackForm: function (commentId, parentId, talkback) {

            // Get the parent tag that will host the reply form
            var parent = jQuery(talkback).parents('div.slide');
            jQuery("p.thankYou", parent).hide(); // hide thank you message

            var form = jQuery('#innerTalkbackFormTemplate');
            // Clear the form
            jQuery('input[type=reset]', form).click();
            // Close currently open form, by removing it from dom
            form.remove();
            // Append it to the new position.
            parent.append(form);
            // re-bind a submit event (lost when form is removed from the DOM)!!!
            form.submit(function () {
                digidam.Comment.saveComment(form);
                return false;
            });
            // re-bind all click events (lost while form is removed from the DOM)!!!
            jQuery("a.displayAnonymous", form).click(function () {
                digidam.Comment.displayAnonymous(jQuery(this));
                return false; // Avoid the browser following the link
            });
            jQuery("a.displayFacebookData", form).click(function () {
                digidam.Comment.displayFacebookData(jQuery(this));
                return false; // Avoid the browser following the link
            });

            // set comment parent id
            var parentCommentId = jQuery('[id=parentCommentId]', form);
            if (parentCommentId) {
                parentCommentId.val(parentId);
            }
            var callbackMsgId = jQuery('[id=callbackMsgId]', form);
            if (callbackMsgId) {
                callbackMsgId.val(commentId);
            }
            form.show();
        },

        /** show/hide comment details (like comment text) */
        toggleComment: function (commentId, talkback) {
            // Get the parent - div: post-holder
            var parent = jQuery(talkback).parent().parent().parent();
            if (jQuery(parent).hasClass("active")) {
                jQuery(parent).removeClass("active");
                jQuery(parent).find("#" + banner468x60id).hide();
            } else {
                // display comment details
                jQuery(parent).addClass("active");
                // update comment view status
                this.updateCommentViewStatus(commentId);
                // show comment banner
                if (jQuery(parent).attr('class').indexOf('post-holder') != -1) {
                    if (jQuery(parent).find("#" + banner468x60id).length == 0) {
                        jQuery("#" + banner468x60id).insertAfter(
								jQuery(parent).children().last());
                    }
                    jQuery("#" + banner468x60id).show();
                }
            }
        },

        /** open/close all comments details on the page */
        toggleAllComments: function () {
            if (jQuery("#openCloseComments").html() == "Open all") {

                jQuery(".talkback .post .commentItem").each(function () {
                    jQuery(this).addClass("active");
                });
                if (jQuery(".talkback .post .commentItem").first().find(
						"#" + banner468x60id).length == 0) {
                    jQuery("#" + banner468x60id).insertAfter(
							jQuery(
									jQuery(".talkback .post .commentItem")
											.first()).children().last());
                }
                jQuery("#" + banner468x60id).show();
                jQuery("#openCloseComments").html("Close all");

            } else {

                jQuery(".talkback .post .commentItem").each(function () {
                    jQuery(this).removeClass("active");
                });
                jQuery("#" + banner468x60id).hide();
                jQuery("#openCloseComments").html("Open all");
            }
        },
        /**
        * init the name field of the talkback form. If user facebook logged in,
        * display his/her picture and name, otherwise display facebook connect
        * button.
        */
        initCommentFormName: function () {
            digidam.Facebook.initFaceBook();
        },

        /** show comment anonymous name field (other than his/her facebook name) */
        displayAnonymous: function (displayAnonymousBtn) {
            var form = displayAnonymousBtn.parents("form");
            jQuery(".facebookUserLoggedIn", form).hide();
            jQuery(".facebookAnonymousUser", form).show();
            digidam.Facebook.setUserStatus(ANONYMOUS);
        },

        /** show client facebook name and picture hidden on the page */
        displayFacebookData: function (displayFacebookDataBtn) {
            var form = displayFacebookDataBtn.parents("form");
            jQuery(".facebookAnonymousUser", form).hide();
            jQuery(".facebookUserLoggedIn", form).show();
            digidam.Facebook.setUserStatus(FACEBOOK_LOGGED_IN);
        },
        hideInProgressImg: function (form) {
            jQuery("img.inProgress", form).hide();
        },
        sortComments: function () {
            var sortedTab = arguments[0];
            if (sortedTab) {
                var sortKey = sortedTab.attr('id');
                var myList = jQuery('#commentsTab ul.post>li');
                jQuery.tinysort.defaults.order = "desc";
                myList.tsort({
                    attr: sortKey
                });
            }
        }
    }; // return

    function storeCommentCallback(data, status) {
        var formId = data.formId;

        if (formId) {
            var form = jQuery("#" + formId);
            digidam.Comment.toggleButton(form); // enable the submit button
            digidam.Comment.hideInProgressImg(form);
            if (data.hasCommentError) {
                // display the error messages
                var errorList = eval(data.errorList);
                for (var i in errorList) {
                    var error = errorMsgs[errorList[i]];
                    var errorLabelName = error[0];
                    var errorMsg = error[1];
                    var errorLabel = jQuery("." + errorLabelName, form);
                    errorLabel.html(errorMsg);
                    errorLabel.show();
                }
            } else {
                var responseMsg = "Your talkback has been submitted successfully. <br/>If selected for publication, it will appear as soon as possible on digidam.com.";
                // find where to show the response
                if (formId.indexOf('innerTalkback') != -1) {
                    // its an inner form (comment on comment)
                    form.hide();
                    var callbackMsgBox = "callbackMsg" + data.callbackMsgId;
                    jQuery("[class*='" + callbackMsgBox + "']").each(
							function () {
							    jQuery(this).html(responseMsg);
							    jQuery(this).show();
							}); // show thank you message
                } else {
                    // its a main form
                    jQuery('input[type=reset]', form).click(); // Clear the form
                    jQuery("#" + mainTalkbackFormBoxId).hide(); // hide the form
                    var thankYouObj = jQuery("." + mainCommentsReplyAgainId);
                    jQuery("p", thankYouObj).html(responseMsg);
                    thankYouObj.show(); // show thank you message
                }
            }
        }
    }


    function storeCommentRateCallback(data, status, commentId, ratingType) {
        // alert(status + " | " + commentId + " | " + ratingType);
        if (status != "success") {

            var errorMsg = "Your rating has not been registered due to a technical glitch. Please try again later.";
            var callbackMsgBox = "callbackMsg" + commentId;
            jQuery("[class*='" + callbackMsgBox + "']").each(function () {
                jQuery(this).html(errorMsg);
                jQuery(this).show();
            });

        } else {

            var thankYou = "<h3>Thank you for rating</h3>";
            // update the rating value
            var ratingCountId = "#" + ratingType + commentId;
            jQuery(ratingCountId).each(function () {
                var ratingValue = jQuery(this).html();
                ratingValue++;
                jQuery(this).html(ratingValue);
            });
            // disable the click event on the used rating button
            // to prevent repeated rating of the same talkback
            var ratingBtn = "div#" + commentId +" span.rate" + ratingType;
            var Typer = "." + ratingType;
            var messageAttached = false;
            jQuery(ratingBtn).each(function () {
                jQuery(this).unbind('click');
                jQuery(this).addClass("disabled");

                if (messageAttached == false) {
                    var parent = jQuery(this).parents('div.slide');
                    // parent.append(thankYou);
                    jQuery("p.thankYou", parent).html(thankYou);
                    jQuery("p.thankYou", parent).show(); // show thank you
                    // message
                    messageAttached = true;
                }
            });
        }
    }
} ();
