﻿var currentPageComments;
var PageId;
var PageSize;
var FeatureId;
var Paged;

/* search comments and page */
$(document).ready(function () {
    //    var validator = $('#form1').validate({
    //        //errorClass: "ui-state-highlight",
    //        success: "success",
    //        ignore: ".ignore",
    //        onsubmit: true
    //    });

    //alert(featurescommentsns.CommentParseDate("\/Date(1300710897413)\/"));

    $('[id^=commentsPager] li').live('hover', function () {

        FeatureId = $(this).parent().parent().attr('id').replace('commentsPager_', '');

        PageSize = $("#pageSize_" + FeatureId).val();

    });


    featurescommentsns.SetupCommentDetails();

    featurescommentsns.SetupSaveButton();


});
var featurescommentsns = new function () {
    this.SetupSaveButton = function () {


        $('p.commentbuttons').children().each(function () {

            if ($(this).attr('id').indexOf('sendb') != -1) {


                var Id = $(this).parent().attr('id').replace('buttons_', '');

                $(this).unbind();
                $(this).bind('click', function (e) {
                    e.preventDefault();


                    var CaptchaCriteria = new Object();

                    CaptchaCriteria.ChallengeVal = $("#recaptcha_challenge_field").attr("value");
                    CaptchaCriteria.ResponseVal = $("#recaptcha_response_field").attr("value");
                    CaptchaCriteria.FeatureId = Id;
                    CaptchaCriteria.PageId = $("#pageId_" + Id).val();


                    var DTO = { 'criteria': CaptchaCriteria };

                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "/ajax/commentswebservice.asmx/ValidateCaptcha",
                        data: JSON.stringify(DTO),
                        dataType: "json",
                        success: function (data) {

                            if (data.d == "true") {

                                AddComment(Id);

                            }
                            else {

                                var featureDiv = $('#featureId_' + Id);
                                var updatemessage = $(featureDiv).find('[id*=statuslb]');
                                $(updatemessage).text("Please ensure all fields are entered correctly");

                            }
                            if ($("#recaptcha_challenge_field").length > 0) {

                                if (Recaptcha != undefined) {
                                    Recaptcha.reload();
                                }
                            }




                        }
                    });




                });






            }

        });



    }

    var AddComment = function (id) {

        var featureDiv = $('#featureId_' + id);

        var anonymous = $(featureDiv).find('[id*=anonymousChk]').attr('checked');
        var name = $(featureDiv).find('[id*=nameBx]').val();
        var email = $(featureDiv).find('[id*=emailBx]').val();
        var message = $(featureDiv).find('[id*=messageBx]').val();
        var updatemessage = $(featureDiv).find('[id*=statuslb]');
        var CommentFormCriteria = new Object();

        CommentFormCriteria.PageId = $("#pageId_" + id).val();
        CommentFormCriteria.FeatureId = id;
        CommentFormCriteria.Name = name;
        CommentFormCriteria.Email = email;
        CommentFormCriteria.Message = message;
        CommentFormCriteria.Anonymous = anonymous;


        var DTO = { 'comments': CommentFormCriteria };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ajax/commentswebservice.asmx/AddComment",
            data: JSON.stringify(DTO),
            dataType: "json",
            global: false,
            success: function (data) {
                if (data) {

                    $(updatemessage).text(data.d);
                    GetComments(1, id, $("#pageSize_" + id).val());

                    $(featureDiv).find('[id*=messageBx]').hide();
                    $(featureDiv).find('[id*=emailBx]').hide();
                    $(featureDiv).find('[id*=nameBx]').hide();
                    $(featureDiv).find('[id*=anonymousChk]').hide();
                    $(featureDiv).find('[id*=sendb]').hide();
                    $(featureDiv).find('[id*=cancelb]').hide();
                    $(featureDiv).find('[id*=messageLb]').hide();

                    $(featureDiv).find('[id*=messageBx]').val('');
                    $(featureDiv).find('[id*=emailBx]').val('');
                    $(featureDiv).find('[id*=nameBx]').val('');
                    $(featureDiv).find('[id*=anonymousChk]').attr('checked', false);
                }
            }
        });






    }




    this.CommentParseDate = function (data) {
        var date = eval(data.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
        var formattedDate = dateFormat(date, "m/dd/yyyy H:MM:ss");
        var today = new Date();

        var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds

        var diffDays = Math.round(Math.abs((today.getTime() - Date.parse(formattedDate).getTime()) / (oneDay)));

        if (diffDays == 0) {

            var currenthour = dateFormat(today, "HH");
            var commenthour = dateFormat(formattedDate, "HH");

            var hourdifference = currenthour - commenthour;
            var currentminute = dateFormat(today, "MM");
            var commentminute = dateFormat(formattedDate, "MM");

            switch (hourdifference) {

                case 0:
                    var currentsecond = dateFormat(today, "ss");
                    var commentsecond = dateFormat(formattedDate, "ss");
                    switch (currentminute - commentminute) {

                        case 0:


                            return (currentsecond - commentsecond) == 1 ? (currentsecond - commentsecond) + " second ago" : (currentsecond - commentsecond) + " seconds ago";

                            break;
                        case 1:

                            var seconds = 60 - commentsecond;
                            seconds = parseInt(seconds) + parseInt(currentsecond);


                            if (seconds < 60) {

                                return seconds == 1 ? seconds + " second ago" : seconds + " seconds ago";

                            }


                            break;

                    }


                    return (currentminute - commentminute) == 1 ? (currentminute - commentminute) + " minute ago" : (currentminute - commentminute) + " minutes ago";

                case 1:

                    var minutes = 60 - commentminute;
                    minutes = parseInt(minutes) + parseInt(currentminute);




                    if (minutes < 60) {

                        return minutes == 1 ? minutes + " minute ago" : minutes + " minutes ago";

                    }
                    break;
            }

            return hourdifference == 1 ? hourdifference + " hour ago" : hourdifference + " hours ago";

        }
        else if (diffDays < 30) {

            return diffDays == 1 ? diffDays + " day ago" : diffDays + " days ago";

        }



        //return dateFormat(date, "dd/m/yyyy h:MM:ss TT");
        return dateFormat(date, "dd mmmm yyyy");

    }

    this.SetupCommentDetails = function () {


        $(".jsComments").each(function () {

            FeatureId = null;
            PageId = null;
            Paged = null;
            PageSize = null;



            FeatureId = $(this).attr('id').toString().replace("featureId_", "");
            PageId = $("#pageId_" + FeatureId).val();
            Paged = $("#paged_" + FeatureId).val();
            PageSize = $("#pageSize_" + FeatureId).val();



            GetComments(1, FeatureId, PageSize);




        });


    }


    var GetComments = function (index, featureId, pageSize) {


        PageId = $("#pageId_" + featureId).val();
        Paged = $("#paged_" + featureId).val();
        var q = "";
        // commentsPagedURL = url;
        currentPageComments = null;
        if (currentPageComments != undefined) {
            currentPageComments.abort();
        }
        var PageSearchCriteria = new Object();
        PageSearchCriteria.PageSize = pageSize;
        PageSearchCriteria.Start = (index - 1) * pageSize;
        PageSearchCriteria.Query = q;
        PageSearchCriteria.Term = "";
        PageSearchCriteria.featureId = featureId;
        PageSearchCriteria.Id = PageId;


        var DTO = { 'criteria': PageSearchCriteria };

        currentPageComments = $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ajax/commentswebservice.asmx/SearchComments",
            data: JSON.stringify(DTO),
            dataType: "json",
            global: false,
            success: function (data) {
                if (data) {
                    bindCommentsList(data.d, featureId, pageSize, Paged);
                }
                else {
                    $("#commentsTableBody_" + featureId).children().remove();
                }
            }
        });

        commentsPageIndex = index;

    }



    var Search = function (commentsPageIndex) {
        GetComments(commentsPageIndex, FeatureId, PageSize);
    }

    var bindCommentsList = function (data, featureId, pageSize) {
        var resultCount = data.Count;
        pageCount = Math.ceil(resultCount / pageSize);
        $("#commentsPager_" + featureId).hide();
        if (pageCount > 0) {

            if (Paged == "True") {

                if (resultCount > pageSize) {
                    $("#commentsPager_" + featureId).show();
                    $("#commentsPager_" + featureId).pager({ pagenumber: commentsPageIndex, pagecount: pageCount, buttonClickCallback: Search });

                }

            }


            var r = data.Results;
            $("#commentsTableBody_" + featureId).children().remove();
            $("#commentsTemplate_" + featureId)
		    .tmpl(r)
		    .appendTo("#commentsTableBody_" + featureId);

            initButtons();
        }
        else {
            $("#commentsTableBody_" + featureId).children().remove();
        }
    }
}
