﻿var MSvillage = {};

$(function () {
    MSvillage.content.init();
    MSvillage.navigation.init();
    MSvillage.fontSizing.init();
    MSvillage.feeds.init();
    MSvillage.login.init();
    MSvillage.blogs.init();
    MSvillage.forumAudit.init();
    MSvillage.SocialModal.init();
    $(".defaultvalue").focus(MSvillage.utilities.onInputFocus).blur(MSvillage.utilities.onInputBlur);
});

MSvillage.content = {

    init: function () {
        $("#bd-content .swapme").mouseover(this.onSwapMeMouseOver).mouseout(this.onSwapMeMouseOut);
        $("#bd-content .faq-q").click(this.onFaqClick);
        this.moveDotNetForm();
    },
    // moves a .net form into an html container
    moveDotNetForm: function () {
        var $container = $("#form-container");
        if ($container.length) {
            $("#aspnetForm").appendTo($container);
        }
    },
    onSwapMeMouseOver: function () {
        var $img = $(this);
        $img.attr("src", $img.attr("src").replace(".", "_over."));
    },
    onSwapMeMouseOut: function () {
        var $img = $(this);
        $img.attr("src", $img.attr("src").replace("_over.", "."));
    },
    onFaqClick: function () {
        $(this).next(".faq-a").slideToggle("fast");
    }
};

MSvillage.navigation = {
    init: function () {
        $("#nav > li").mouseover(this.onMouseOver).mouseout(this.onMouseOut);
    },
    onMouseOver: function () {
        var $img = $(this).find("img"),
            $childUL = $(this).find("ul");

        $img.attr("src", $img.attr("src").replace(".gif", "_d.gif"));
        // ul width should be at least as wide as the parent li image
        if ($childUL.length) {
            var imgWidth = $img.width();
            if (imgWidth > $childUL.outerWidth()) {
                $childUL.attr("style", "width:" + imgWidth + "px");
            }
            $childUL.show();
        }

    },
    onMouseOut: function () {
        var $img = $(this).find("img");
        $img.attr("src", $img.attr("src").replace("_d.gif", ".gif"));
        $(this).find("ul").hide();
    }
};

MSvillage.fontSizing = {

    init: function () {

        // normal font size
        $("#font-size-small").click(function (event) {
            $("#bd").removeClass("bigger").removeClass("biggest");
        });

        // larger font
        $("#font-size-medium").click(function (event) {
            $("#bd").addClass("bigger").removeClass("biggest");
        });

        // largest font
        $("#font-size-large").click(function (event) {
            $("#bd").addClass("biggest").removeClass("bigger");
        });

    }

};

MSvillage.feeds = {
    init: function () {
        $("#feeds").css("opacity", "0.8");
        $("#feed-tabs img").click(this.onTabClick);
    },
    onTabClick: function () {

        var $img = $(this);
        if (!$img.hasClass("current")) {
            // change tabs
            $img.attr("src", $img.attr("src").replace(".gif", "_d.gif")).addClass("current").siblings().each(function () {
                $(this).removeClass("current").attr("src", $(this).attr("src").replace("_d.gif", ".gif"));
            });
            // swap content            
            $("#feed-content div").eq($(this).index()).removeClass("hide").siblings().addClass("hide");
        }

    }
};

MSvillage.login = {

    init: function () {
        $("#login-password").keyup(this.onPasswordKeyUp);
        $("#login-button").click(this.onLogIn);
        $("#modalClose").click(this.onModalCancel);
        if ($("#np").val() === 'True') {
            this.showModalLogin();
        }
    },
    showModalLogin: function () {

        var $container = $("#modal"),
            maskHeight = $(document).height(),
            maskWidth = $(window).width(),
            containerHeight = $container.height(),
            containerWidth = $container.width();

        // fill screen with mask
        $("#mask").css({ width: maskWidth, height: maskHeight }).fadeTo(0, 0.6);

        // change position and add resized map
        $("#modal")
            .css({ top: $(window).height() / 2 + $(window).scrollTop() - containerHeight / 2, left: maskWidth / 2 - containerWidth / 2 })
            .show();

        $("#login-form").appendTo($("#modal-login"));

    },
    onPasswordKeyUp: function (e) {
        if (e.keyCode === 13) {
            MSvillage.login.onLogIn();
        }

    },
    onLogIn: function (e) {
        if (e) {
            e.preventDefault();
        }

        var loginEmail = $("#login-email").val(),
                loginPassword = $("#login-password").val();

        // validate
        if (loginEmail === '') {
            alert(MSvillage.localization.get().emailRequired);
            return;
        }

        if (loginPassword === '') {
            alert(MSvillage.localization.get().passwordRequired);
            return;
        }

        // try login
        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/Authenticate",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{email:"' + loginEmail + '", password: "' + loginPassword + '"}',
            error: function () { alert(MSvillage.localization.get().loginFailed); },
            success: function (data) {
                $("#login-errForgot span").remove();
                if (data.d) {

                    // success - redirect to current page to set cookie

                    window.location = window.location.href;
                    // turn on welcome message
                    //$("#login-form *").remove();
                    //$("#login-form").append("" + MSvillage.localization.get().loginSucceeded + "");
                } else {
                    $("#login-errForgot").prepend("<span>" + MSvillage.localization.get().invalidCredentials + "</span>");
                }
            }
        });

    },
    onModalCancel: function () {
        if ($("#lcid").val() === '3084') {
            window.location = '/fr-ca';
        } else {
            window.location = '/';
        }
    }

};

MSvillage.blogs = {
    init: function () {
        var $blogsContainer = $("#blog-listings");
        if ($blogsContainer.length) {
            $(".listing-title", $blogsContainer).toggle(this.onTitleAnchorClick, this.onTitleAnchorToggleClick);

            $('p.blog-intro').each(function () {
                MSvillage.Comments.blogPostHasComments($(this));
            });

            $blogsContainer.delegate('.title-view-comments', 'click', function (e) {
                $('div.hide').css('display', 'none');
                $('p.blog-intro').css('display', 'block');
                $(this).parent().hide().next().show();

                var parentElement = $(this).parent().parent();
                var postingLineage = $(this).parent().parent().attr('id');

                MSvillage.Comments.loadBlogComments(postingLineage, parentElement);

                window.location.hash = $(this).parent().siblings('.endLocation').attr('id');

                return false;
            });
        }
    },
    onTitleAnchorClick: function () {
        
  
            $('div.hide').css('display', 'none');
            $('p.blog-intro').css('display', 'block');
            $(this).next().hide().next().show();

            $('.single-story-comments-section').remove();
          
            var parentElement = $(this).parent();
            var postingLineage = $(this).attr('lineage');
            
            MSvillage.Comments.loadBlogComments(postingLineage, parentElement);

            // set focus when expanding
            window.location.hash = $(this).parent().attr('id');
           
            return false;
      
    },
    onTitleAnchorToggleClick: function () {
        $(this).next().show().next().hide();
        $('.single-story-comments-section').remove();
        return false;
    }
};

MSvillage.localization = {
    get: function () {
        // helper so the language doesn't have to be set all the time.
        return MSvillage.localization[$("#lcid").val()];
    },
    "4105": {
        emailRequired: "Email address is required.",
        passwordRequired: "Password is required.",
        invalidCredentials: "Your email address and/or password is invalid, or your account is no longer active.",
        loginSucceeded: "Welcome!",
        loginFailed: "There was a problem logging in. Please try again.",
        optionSelectionRequired: "Please choose an option.",
        vote: "Vote &gt;",
        results: "Results &gt;",
        votingError: "There was a problem adding your vote."
    },
    "3084": {
        emailRequired: "Adresse courriel requise.",
        passwordRequired: "Mot de passe requis.",
        invalidCredentials: "Votre adresse courriel et (ou) votre mot de passe est invalide, ou votre compte n'est plus actif.",
        loginSucceeded: "Bienvenue!",
        loginFailed: "Il y a eu un problème à l'ouverture de la session. Veuillez réessayer.",
        optionSelectionRequired: "Veuillez choisir une option.",
        vote: "Votez &gt;",
        results: "Résultats &gt;",
        votingError: "Il y a eu un problème pour ajouter votre vote."
    }
};

MSvillage.utilities = {
    onInputFocus: function () {
        if (this.defaultValue === $(this).val()) {
            $(this).val("");
        }
    },
    onInputBlur: function () {
        if ($(this).val() === "") {
            $(this).val(this.defaultValue);
        }
    }
};

MSvillage.forumAudit = {
    init: function () {
        $("#modalForumAuditClose").click(MSvillage.forumAudit.onModalCancel);
    },
    Audit: function () {

        var subject = $(".subject_field").val();
        var description = $(".description_field").val();

        var bool = true

        // Audit Post
        $.ajax({ async: false,
            type: "POST",
            url: "/services/msvillage.asmx/AuditPost",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{subject:"' + subject + '", description: "' + description + '"}',
            error: function () { alert("Audit Failed"); return false; },
            success: function (data) {

                if (data.d) {
                    bool = true;
                } else {
                    bool = false;
                    MSvillage.forumAudit.showModal();
                }
            }
        });


        return bool;
    },
    AuditComment: function () {

        var comment = MSvillage.Comments.jsonEncode($("#singleStoryCommentBox").val());
      

        var bool = true

        // Audit Post
        $.ajax({ async: false,
            type: "POST",
            url: "/services/msvillage.asmx/AuditComment",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{comment:"' + comment + '"}',
            error: function (xmlRequest) {
                var msg = 'ajaxFailure: FAIL: \n\r xmlRequest.status=' + xmlRequest.status + ' \n\r xmlRequest.statusText=' + xmlRequest.statusText + '\n\r xmlRequest.responseText=' + xmlRequest.responseText;
                alert(msg);
            },
            success: function (data) {

                if (data.d) {
                    bool = true;
                } else {
                    bool = false;
                    MSvillage.forumAudit.showModal();
                }
            }
        });


        return bool;
    },
    showModal: function () {

        var $container = $("#modalForumAudit"),
            maskHeight = $(document).height(),
            maskWidth = $(window).width(),
            containerHeight = $container.height(),
            containerWidth = $container.width();

        // fill screen with mask
        $("#mask").css({ width: maskWidth, height: maskHeight }).fadeTo(0, 0.6);

        // change position and add resized map
        $("#modalForumAudit")
            .css({ top: $(window).height() / 2 + $(window).scrollTop() - containerHeight / 2, left: maskWidth / 2 - containerWidth / 2 })
            .show();
    },
    onModalCancel: function () {
        // hide screen mask
        $("#mask").hide();

        // change position and add resized map
        $("#modalForumAudit").hide();
    }
};

MSvillage.SocialModal = {
    init: function () {
        var theme = $("#ctl00_hiddenSocial").val();

        if (theme == "Social") {

            //check for cookie
            if ($.cookie('Msvillage2010') != '1') {
                MSvillage.SocialModal.showModal();
            }

        }

        $("#modalSocialAccept").click(MSvillage.SocialModal.onModalAccept);
        $("#modalSocialDecline").click(MSvillage.SocialModal.onModalDecline);
    },
    showModal: function () {

        var $container = $("#modalSocial"),
            maskHeight = $(document).height(),
            maskWidth = $(window).width(),
            containerHeight = $container.height(),
            containerWidth = $container.width();

        // fill screen with mask
        $("#mask").css({ width: maskWidth, height: maskHeight }).fadeTo(0, 0.6);

        // change position and add resized map
        $("#modalSocial")
            .css({ top: $(window).height() / 2 + $(window).scrollTop() - containerHeight / 2, left: maskWidth / 2 - containerWidth / 2 })
            .show();
    },
    onModalAccept: function (e) {
        if (e) {
            e.preventDefault();
        }

        //set cookie
        $.cookie('Msvillage2010', '1', { expires: 1 });

        if ($("#np").val() === 'True') {
            // change position and add resized map
            $("#modalSocial").hide();
            MSvillage.login.showModalLogin();
        }
        else {
            // hide screen mask
            $("#mask").hide();

            // change position and add resized map
            $("#modalSocial").hide();
        }
    },
    onModalDecline: function (e) {

        if (e) {
            e.preventDefault();
        }

        if ($("#lcid").val() === '3084') {
            window.location = '/fr-ca';
        } else {
            window.location = '/';
        }
    }
};

MSvillage.Comments = {
    init: function () {

        $('#commentButton').live('click', function (e) {
            e.preventDefault();

            MSvillage.Comments.isAunthenticated(MSvillage.Comments.handleAuth, "create", "");

        });


        $('#bd-content').delegate('a.toggle-comment', 'click', function (e) {
            e.preventDefault();

            var commentLineage = $(this).attr('lineage');
            var description = $(this).parent().parent().parent().parent().siblings(".comment-description");  //$(this).parent().siblings(".comment-description");


            $(this).toggle(function () {
                MSvillage.Comments.getComment(commentLineage, description, true);
            },
            function () {
                MSvillage.Comments.getComment(commentLineage, description, false);
            });

            $(this).trigger('click');
        });

        $('#bd-content').delegate('a.showAllComments', 'click', function (e) {
            e.preventDefault();

            $(this).toggle(function () {
                $('div.hideComment').removeClass('hideComment').addClass('showComment');
            },
            function () {
                $('div.showComment').removeClass('showComment').addClass('hideComment');
            });

            $(this).trigger('click');
        });
        $('#bd-content').delegate('a.delete-button', 'click', function (e) {
            e.preventDefault();

            var cultureID = $("#lcid").val();
            var lineage = $(this).attr('lineage');

            var confirmMessage;

            if (cultureID == 4105) {
                confirmMessage = "Are you sure you want to delete this comment?";
            }
            else {
                confirmMessage = "Êtes-vous sûr de vouloir supprimer ce commentaire?";
            }

            if (confirm(confirmMessage)) {
                MSvillage.Comments.isAunthenticated(MSvillage.Comments.handleAuth, "delete", lineage);
            }

        });

        $('#bd-content').delegate('a.report-button', 'click', function (e) {
            e.preventDefault();
            var comment = $(this).parent().parent().parent().parent().parent().children("div.comment-description").text();
            var url = window.location.href;

            MSvillage.Comments.reportComment(comment, url);
        });
    },
    storiesInit: function () {
        $('.infoSec td.mmColumn').each(function () {
            MSvillage.Comments.guestEditorialHasComments($(this));
        });

        $('#story_listings .listings-dark').each(function () {
            //MSvillage.Comments.guestEditorialHasComments($(this));
            var $link = $(this).children(".listing-title");
            MSvillage.Comments.lifeStorylHasComments($link);
        });
    },
    deleteComment: function (commentLineage, $comment) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/DeleteComment",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{commentLineage:"' + commentLineage + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Deleting Comment'); },
            success: function (data) {

                if (data.d) {

                    $('.posted-comments').replaceWith(data.d);

                } else {

                    $('#posted-comments').prepend('Error Deleting Comment');
                }
            }
        });
    },
    reportComment: function (comment, url) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/ReportComment",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{url:"' + url + '", comment: "' + comment + '"}',
            error: function () { alert('Error Reporting Comment'); },
            success: function (data) {

                if (data.d) {
                    if (cultureID == 4105) {
                        alert('Comment has been reported');
                    }
                    else {
                        alert('Ce commentaire a été signalé.');
                    }
                } else {

                    $('#posted-comments').prepend('Error Reporting Comment');
                }
            }
        });
    },
    createComment: function (parentLineage, comment) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/CreatComment",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{parentLineage:"' + parentLineage + '", comment: "' + MSvillage.Comments.jsonEncode(comment) + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Creating Comment'); },
            success: function (data) {

                if (data.d) {
                    $('#singleStoryCommentBox').val('');
                    $('.posted-comments').replaceWith(data.d);

                } else {

                    $('#posted-comments').prepend('Error Creating Comment');
                }
            }
        });
    },
    getComment: function (lineage, description, fullComment) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/GetComment",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{lineage:"' + lineage + '", fullComment: "' + fullComment + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Retrieving Comment'); },
            success: function (data) {

                if (data.d) {

                    description.text(data.d);
                } else {

                    $('#posted-comments').prepend('Error Retrieving Comment');
                }
            }
        });
    },
    loadBlogComments: function (lineage, parentElement) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/LoadBlogComments",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{lineage:"' + lineage + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Retrieving Comments'); },
            success: function (data) {

                if (data.d) {
                    parentElement.append(data.d);
                } else {

                    parentElement.prepend('Error Retrieving Comments');
                }
            }
        });
    },
    blogPostHasComments: function (parentElement) {
        var cultureID = $("#lcid").val();
        var lineage = parentElement.parent().attr("id");
        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/BlogPostHasComments",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{lineage:"' + lineage + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Retrieving Comments'); },
            success: function (data) {

                if (data.d) {
                    parentElement.append(data.d);
                } else {

                    // no comments exist
                }
            }
        });
    },
    guestEditorialHasComments: function (parentElement) {
        var cultureID = $("#lcid").val();
        var lineage = ""

       
        var folderIDArray = null;

        if (cultureID == "4105") {
            folderIDArray = parentElement.children().attr("href").split("/", 2);
            lineage = folderIDArray[1];

        }
        else {
            folderIDArray = parentElement.children().attr("href").split("/", 3);
            lineage = folderIDArray[2];
        }

        var url = parentElement.children().attr("href");

      
        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/StoriesHasPostByFolderID",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{folderID:"' + lineage + '", cultureID: "' + cultureID + '", url: "' + url + '"}',
            error: function () { },
            success: function (data) {

                if (data.d) {
                    parentElement.append(data.d);
                } else {

                    // no comments exist
                }
            }
        });
    },

    lifeStorylHasComments: function (parentElement) {
        var cultureID = $("#lcid").val();
        var lineage = ""

        
        var folderIDArray = null;

        if (cultureID == "4105") {
            folderIDArray = parentElement.attr("href").split("/", 2);
            lineage = folderIDArray[1];

        }
        else {
            folderIDArray = parentElement.attr("href").split("/", 3);
            lineage = folderIDArray[2];
        }

        var url = parentElement.attr("href");

      
        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/StoriesHasPostByFolderID",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{folderID:"' + lineage + '", cultureID: "' + cultureID + '", url: "' + url + '"}',
            error: function () { },
            success: function (data) {

                if (data.d) {
                    parentElement.parent().append(data.d);
                } else {

                    // no comments exist
                }
            }
        });
    },

    loadVideoComments: function (lineage) {
        var cultureID = $("#lcid").val();

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/LoadBlogComments",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: '{lineage:"' + lineage + '", cultureID: "' + cultureID + '"}',
            error: function () { alert('Error Retrieving Comments'); },
            success: function (data) {

                if (data.d) {

                    $('.single-story-comments-section').replaceWith(data.d);
                } else {

                    parentElement.prepend('Error Retrieving Comments');
                }
            }
        });
    },
    isAunthenticated: function (callback, callType, lineage) {

        $.ajax({
            type: "POST",
            url: "/services/msvillage.asmx/IsLoggedIn",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function () { alert('Error checking authentication'); },
            success: function (data) {

                callback(data.d, callType, lineage);

            }
        });
    },
    handleAuth: function (isAuth, callType, lineage) {
        if (isAuth && callType == "create") {
            var parentLineage = $('#parentLineage').val();
            var comment = $('#singleStoryCommentBox').val();

            if (comment != "" && MSvillage.forumAudit.AuditComment()) {
                MSvillage.Comments.createComment(parentLineage, comment);

            }
        }
        else if (isAuth && callType == "delete") {
            var $comment = $(this).parent().parent().parent();
            MSvillage.Comments.deleteComment(lineage, $comment);
        }
        else {
            MSvillage.login.showModalLogin();
        }
    },
    jsonEncode: function (val) {
        if (val) {
            return val.replace(new RegExp('\"', 'g'), '\\"');
        } else {
            return ''
        }
    }


};
