﻿/// <reference path="./Cineplex.js" />

Agility.RegisterNamespace("Cineplex.Blog");

(function(Blog) {

    var _commentsSortDirection = "DESC";

    $(function() {

        //bind the skinned dropdowns
        $("#lstCommentSort").CineplexCombo({
            onchange: function(elem) {
                var sortDir = $("#lstCommentSort a.selected").attr("sortDir");
                if (sortDir != undefined && sortDir != null) {
                    _commentsSortDirection = sortDir;
                    _populateComments();
                    return false;
                }
            }
        });


        //see if comments are enabled...
        if ($("#pnlCommentCaptcha").size() > 0) {


            //populate the comments
            _populateComments();

            //create the recaptcha	
            Recaptcha.create(
				Recaptcha_Public_Key,
				"pnlCommentCaptcha", {
				    theme: "clean",
				    lang: Recaptcha_Lang
				    //callback: Recaptcha.focus_response_field
				});
        }

        //scroll links...
        $("#lnkViewCommentsOnBlog").click(function() {
            $(document).scrollTo($("#sectionBlogComments"), {
                duration: 300,
                easing: "swing"
            });
            return false;
        });

        $("#lnkAddCommentToBlog").click(function() {
            $(document).scrollTo($("#sectionAddBlogComment"), {
                duration: 300,
                easing: "swing",
                onAfter: function() {
                    $("#txtCommentName").focus();
                }
            });
            return false;
        });

        $("#btnSubmitBlogComment").click(function() {
            _submitComment();
            return false;
        });

        //ensure 400 length limit on comments
        $("#txtCommentsText").keydown(function() {
            if ($(this).val().length > 399) return false;
        });

        if ($("#pnlBlogListing").size() > 0) {
            //get the blog comment counts for the listing...
            _populateBlogCommentCounts();
        }

    });

    function _populateBlogCommentCounts() {
        //get the list of blog ids...
        var ids = new Array();

        $("#pnlBlogListing .BlogListItem").each(function() {
            ids[ids.length] = $(this).attr("blogStoryID");
        });

        //build the jsonp url..        
        //http://cineplexugc.x2.edentity.ca/ExecCustomProcedure.ashx?proc=GetCommentCount&@blogStoryIDs=63698,63579,63570,63581,63520,63416,63391,63322&@languageCode=en-us&format=jsonp
        
        var url = Agility.UGC.API.APIUrl;
        url = url.toLowerCase().replace("agility-ugc-api-jsonp.svc", "ExecCustomProcedure.ashx");
        url += "?proc=GetCommentCount&@blogStoryIDs=" + ids.join(",") + "&@languageCode=" + Cineplex.GetCurrentLanguage();
        url += "&format=json";

        url += "&accessKey=" + escape(Agility.UGC.API.APIAccessKey);
        url += "&seconds=" + escape(Agility.UGC.API.APISeconds);
        url += "&randomNumber=" + escape(Agility.UGC.API.APIRandomNumber);
        url += "&hash=" + escape(Agility.UGC.API.APIHash);
        url += "&profileRecordID=" + escape(Agility.UGC.API.APIProfileRecordID);
        url += "&method=?";

        //({"ResponseType":0, "ResonseData":{[{"BlogStoryID":"60154""Count":"172"}{"BlogStoryID":"63322""Count":"1"}]});

        $.getJSON(url, function(data) {
        if (data == undefined || !$.isArray(data.ResonseData)) return;

            $("#pnlBlogListing .CommentCount").html(0);

            $.each(data.ResonseData, function(index, elem) {
            $("#pnlBlogListing .BlogListItem[blogStoryID='" + elem.BlogStoryID + "'] .CommentCount").html(elem.Count);
            });
        });

    }

    var _isFirstLoad = true;




    function _populateComments(pageIndex) {

        var pageSize = Cineplex_CommentPageSize;
        if (pageIndex == undefined) pageIndex = 0;
        var recordOffset = pageIndex * pageSize;

        //build the search arg
        var searchArg = new Agility.UGC.API.SearchArg();
        searchArg.RecordTypeName = "Comments";
        searchArg.PageSize = pageSize;
        searchArg.RecordOffset = recordOffset;
        searchArg.SortedField = "CreatedOn";
        searchArg.SortDirection = _commentsSortDirection;
        searchArg.Search = "BlogStoryID = " + Cineplex_CurrentBlogID + " && LanguageCode = '" + Cineplex.GetCurrentLanguage() + "'";

        //ensure things don't "jump"		
        $("#pnlBlogComments").css("minHeight", $("#pnlBlogComments").height());

        //show progress		
        $("#pnlBlogComments").html(Cineplex.AjaxSpinner());

        //do the search
        Agility.UGC.API.SearchRecords(searchArg, function(data) {
            if (data.ResponseType != Agility.UGC.API.ResponseType.OK) {
                //show the error...
                $("#pnlBlogComments").html("The comments could not be retrieved.");
            } else {

                //show the actual comments...
                var totalComments = data.ResponseData.TotalRecords;

                //fill in the comment count...
                $("#BlogListing .CommentCount").html(totalComments);


                //template them...
                $("#pnlBlogComments").setTemplateElement('txtCommentTemplate');
                $("#pnlBlogComments").setParam("GetAuthorLink", function(name, url) {
                    if (url == null || url == "") {
                        return name;
                    } else {
                        return "<a class=\"AuthorLink\" href=\"" + url + "\" target=\"_blank\">" + name + "</a>";
                    }
                });

                $("#pnlBlogComments").setParam("GetCommentText", function(comment) {
                    //replace newlines with <br/>

                    var div = $("<div></div>");
                    div.html(comment);
                    return div.text().replace(/(\r\n|[\r\n])/g, "<br />");

                });

                $("#pnlBlogComments").setParam("GetCommentDate", function(dateStr) {

                    var d = Date.parse(dateStr);
                    return d.toString("MMMM d, yyyy @ h:mmtt");

                });

                $("#pnlBlogComments").processTemplate(data.ResponseData.Records);

                //scroll to the top of the comments...
                if (_isFirstLoad == false) {


                    $(document).scrollTo($("#sectionBlogComments"), {
                        duration: 300,
                        easing: "swing",
                        onAfter: function() {
                            $("#pnlBlogComments").css("minHeight", null);
                        }
                    });

                }
                _isFirstLoad = false;

                //init the pager...
                Cineplex.InitializeLegacyAjaxPager($("#pnlBlogCommentsPager"), pageSize, pageIndex, totalComments, function(newPageIndex) {
                    _populateComments(newPageIndex);
                });

                //hook up the "abuse" link
                $("#pnlBlogComments  .FlagLink").click(function() {

                    var commentID = parseInt($(this).attr("commentID"));
                    if (isNaN(commentID)) return false;

                    //ensure things don't "jump"		
                    $("#pnlBlogComments").css("minHeight", $("#pnlBlogComments").height());

                    //show progress		
                    $("#pnlBlogComments").html(Cineplex.AjaxSpinner());

                    //flag the comment...
                    Agility.UGC.API.SetRecordFlag(commentID, Agility.UGC.API.RecordFlag.Abuse, "Offensive.", function(data) {
                        alert(Cineplex.Constants.lblCommentFlaggedOffensive);
                        _populateComments(pageIndex);
                    });

                    return false;
                });
            }
        });

    }

    _submitComment = function() {

        var challenge = Recaptcha.get_challenge();
        var response = Recaptcha.get_response();
        var name = $.trim($("#txtCommentName").val());
        var lastname = $.trim($("#txtCommentLastName").val());
        var email = $.trim($("#txtCommentEmail").val());
        var website = $.trim($("#txtCommentWebsiteUrl").val());
        var comment = $.trim($("#txtCommentsText").val());
        var blogTitle = $("#blogItemTitle").html();

        //make sure the top of the blog section is visible
        $(document).scrollTo($("#sectionAddBlogComment"), {
            duration: 300,
            easing: "swing"
        });

        //validate the input....
        if (name == "" || email == "" || comment == "" || response == "") {
            $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_RequiredFields).slideDown();
            return;
        }

        //validate email
        if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email) == false) {
            $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_ValidEmail).slideDown();
            return;
        }

        //validate the url
        if (website != "") {
            var vUrl = new RegExp();
            vUrl.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
            if (!vUrl.test(website)) {
                $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_ValidWebsiteURL).slideDown();

                return;
            }
        }

        //hide the response panel...
        $("#pnlAddBlogCommentMessage").slideUp("normal", function() {

            //hide the input panel...
            $("#pnlAddBlogComments").css("visibility", "hidden");
            $("#pnlAddBlogCommentProgress").show();


            var postData = {
                name: name,
                email: email,
                lastname: lastname,
                website: website,
                comment: comment,
                captcharesponse: response,
                captchachallenge: challenge,
                blogTitle: blogTitle,
                blogID: Cineplex_CurrentBlogID,
                languageCode: Cineplex.GetCurrentLanguage()
            };

            //recycle the captcha
            Recaptcha.reload()

            $.ajax({
                cache: false,
                type: 'POST',
                url: Agility.ResolveUrl("~/Services/AddBlogComment.ashx"),
                dataType: "html",
                data: postData,
                success: function(data, textStatus, XMLHttpRequest) {
                    //success
                    $("#pnlAddBlogComments").css("visibility", "visible");
                    $("#pnlAddBlogCommentProgress").hide();

                    if (data == "OK") {
                        //clear out the fields...
                        $("#txtCommentName").val("");
                        $("#txtCommentLastName").val("");
                        $("#txtCommentEmail").val("");
                        $("#txtCommentWebsiteUrl").val("");
                        $("#txtCommentsText").val("");

                        //show the message
                        $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_CommentSuccess).slideDown();

                        //populate the comments (ensureing that we don't do the "scroll" after loading them...
                        _isFirstLoad = true;
                        _populateComments(0);

                        return;
                    } else if (data == "CAPTCHA_NOT_VALID") {
                        //captcha error

                        $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_InvalidCaptcha).slideDown();
                        Recaptcha.focus_response_field();

                    } else if (data == "COMMENT_VALIDATION_ERROR") {

                        //comment validation error										
                        $("#pnlAddBlogCommentMessage").text(Cineplex_Comment_InvalidHTMLInComment).slideDown();

                    } else {
                        //unknown errors										
                        $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_CommentError).slideDown();
                    }

                },
                error: function(req, textStatus, errorThrown) {
                    //error
                    $("#pnlAddBlogComments").css("visibility", "visible");
                    $("#pnlAddBlogCommentProgress").hide();

                    //respond to the error...
                    $("#pnlAddBlogCommentMessage").html(Cineplex_Comment_CommentError).slideDown();
                }
            });

        });


    }


})(Cineplex.Blog);

