﻿//Initialize help menu.
$(document).ready(function() {
    HelpMenu.InitalizeHelpMenu();
});

// BUG in IE calling resize multiple times

//$(window).wresize(function() {
//    var keepMenuOpen = false;

//    if (HelpMenu.HelpMenuItemSelected && HelpMenu.HelpMenuItemSelected.indexOf("tr_HelpMenuItem_") == 0)
//        HelpSection.DisplayHelp(HelpMenu.HelpMenuItemSelected);

//    if ($("#divHelpMenu").is(":visible")) keepMenuOpen = true;

//    HelpMenu.LayoutSet = false;
//    HelpMenu.SetLayout(keepMenuOpen);
//});

var HelpMenu = {
    //HELP CENTER SETTINGS
    HelpMenuItems: new Array(),

    HelpMenuItemSelected: null,
    KeepOpen: false,
    KeepPermanentOpen: false,
    HelpItemBelowWindow: false,
    TutorialFolder: null,
    TutorialFile: null,

    LayoutSet: false,
    ResizeTimer: null,
    SetLayout: function(keepOpen) {
        if (!HelpMenu.LayoutSet) {
            $("#divHelpMenu").show();
            $("#divHelpMenu").css("left",
                $("#tblHelpCenter").offset().left -
                    ($("#divHelpMenu").width() - $("#tblHelpCenter").width()));

            if (!keepOpen) $("#divHelpMenu").hide();

            $("#divHelpMenu").css("top", $("#tblHelpCenter").offset().top + $("#tblHelpCenter").height() + 4);
        }
        HelpMenu.LayoutSet = true;
    },

    MenuOpen: function() {
        $("#tblHelpCenter").addClass("HelpMenu-HelpButtonHover");
        $(".HelpMenu-HelpArrow").addClass("HelpMenu-HelpArrowHover");
        clearTimeout(HelpMenu.TimeoutID);
        $("#divHelpMenu").slideDown("fast");
    },
    MenuClose: function(force) {
        if (!HelpMenu.KeepPermanentOpen || force) {
            if (force) HelpMenu.KeepPermanentOpen = false;
            $("#tblHelpCenter").removeClass("HelpMenu-HelpButtonHover");
            $(".HelpMenu-HelpArrow").removeClass("HelpMenu-HelpArrowHover");
            clearTimeout(HelpMenu.TimeoutID);
            $("#divHelpMenu").slideUp("fast");
        }
    },

    //Stop the animation on all help menu items.
    StopWalkthrough: function() {
        clearTimeout(HelpMenu.WalkthroughTimerID);
        $(".HelpMenu-MenuItem").find("table").hide().removeClass("HelpMenu-HoverOver").show();
        $(".HelpMenu-MenuItemImage").removeClass("HelpMenu-MenuItemImageHover");

        HelpSection.ClearHelp();
    },

    WalkthroughTimerID: null,
    //this should loop through the help menu items and select each one - one-by-one.
    ShowMeWalkthrough: function() {
        $(".HelpMenu-MenuItemImage").addClass("HelpMenu-MenuItemImageHover");
        HelpMenu.MenuClose(true);
        var next = function(index) {
            if (index != 0) {
                $($(".HelpMenu-MenuItem")[index - 1]).find("table").fadeOut("slow", function() {
                    $(this).removeClass("HelpMenu-HoverOver");
                    $(this).show();
                    runnext(index);
                });
            } else
                runnext(index);
        }
        var runnext = function(index) {
            if (index < $(".HelpMenu-MenuItem").length) {
                var currentItem = $($(".HelpMenu-MenuItem")[index]);
                currentItem.find("table").fadeOut("fast",
                        function() {
                            $(this).addClass("HelpMenu-HoverOver");
                            HelpSection.DisplayHelp(currentItem[0].id, true);
                            $(this).fadeIn("slow", function() {
                                HelpMenu.WalkthroughTimerID = setTimeout(function() {
                                    next(index + 1);
                                }, HelpMenu.HelpMenuItems[currentItem[0].id].Duration * 1000);
                            });
                        }
                    );
            } else {
                HelpMenu.MenuOpen();
                HelpMenu.StopWalkthrough();
                $('html, body').animate({ scrollTop: 0 }, 1000);
            }
        }
        next(0);
    },

    IsWalkThrough: function() {
        return $(".HelpMenu-MenuItemImageHover").length > 0;
    },

    ResetHelp: function() {
        HelpMenu.StopWalkthrough();
        HelpMenu.KeepPermanentOpen = false;
        HelpMenu.MenuClose();
        HelpMenu.HelpMenuItemSelected = null;
        $("#tblHelpMenuItems tr").removeClass("HelpMenu-HoverOver");
    },

    InitalizeHelpMenu: function() {
        // Re-order Help Items
        var items = $("tr[id^=tr_HelpMenuItem_]");

        $.each(items, function(i, v) {
            var controls = HelpSection.FormatControlList(HelpMenu.HelpMenuItems[this.id].TargetControlID.split(','));
            if (!controls || controls.length == 0) {
                $(this).remove();
            } else {
                var top = HelpSection.GetOuterCoordinates(controls)[1];

                $(this).attr("topCoord", top);

                var curlist = $("tr[id^=tr_HelpMenuItem_]");
                for (var t = 0; t < i; t++) {
                    if (top < $(curlist[t]).attr("topCoord")) {
                        $(curlist[t]).before(this);
                        break;
                    }
                }
            }
        });
        if ($("tr[id^=tr_HelpMenuItem_]").length == 0)
            $("tr[id$=tr_ShowMeWalkthrough]").hide();

        // Help Button
        $("#tblHelpCenter").hover(
            function(e) {
                HelpMenu.SetLayout();
                if (!HelpMenu.KeepOpen) HelpMenu.MenuOpen();
                HelpMenu.KeepOpen = true;
            },
            function(e) {
                HelpMenu.KeepOpen = false;
                setTimeout(function() { if (!HelpMenu.KeepOpen) HelpMenu.MenuClose(); }, 500);
            });

        $("#tblHelpCenter").bind("click", function(e) {
            if (HelpMenu.KeepPermanentOpen) {
                HelpMenu.KeepPermanentOpen = false;
                HelpMenu.MenuClose();
            }
            else {
                HelpMenu.KeepPermanentOpen = true;
                if ($(".HelpMenu-HelpButtonHover").length == 0)
                    HelpMenu.MenuOpen();
            }
            e.stopPropagation();
        });
        $(document).bind("click", function(e) {
            HelpMenu.ResetHelp();
        });

        // Help Menu
        $("#divHelpMenu").hover(
            function(e) {
                HelpMenu.KeepOpen = true;
            },
            function(e) {
                HelpMenu.KeepOpen = false;
                setTimeout(function() { if (!HelpMenu.KeepOpen) HelpMenu.MenuClose(); }, 500);
            });

        // Help Menu Items
        $("#tblHelpMenuItems tr[id]").hover(
            function() {
                if (HelpMenu.HelpMenuItemSelected != this.id) {
                    $(this).addClass("HelpMenu-HoverOver");

                    if (this.id.indexOf("tr_HelpMenuItem_") == 0) {
                        HelpMenu.StopWalkthrough();
                        if (HelpMenu.HelpMenuItemSelected != this.id)
                            HelpSection.DisplayHelp(this.id);
                    }

                    //                    var s1 = new SWFObject("/global/components/desktop/libraries/SiteStudio.HelpCenter/components/desktop/help_center_menu/resources/player.swf",
                    //                            "ply", "1", "1", "9", "#FFFFFF");
                    //                    s1.addParam("wmode", "transparent");
                    //                    s1.addParam("allowfullscreen", "true");
                    //                    s1.addParam("allowscriptaccess", "always");
                    //                    s1.addParam("flashvars", "type=sound&autostart=true&file=/global/components/desktop/libraries/SiteStudio.HelpCenter/components/desktop/help_center_menu/resources/SFXBible_08484.mp3");

                    //                    s1.write("soundClip");
                }
            },
            function() {
                if (HelpMenu.HelpMenuItemSelected != this.id) {
                    $(this).removeClass("HelpMenu-HoverOver");
                    if (this.id.indexOf("tr_HelpMenuItem_") == 0) {
                        HelpSection.ClearHelp();
                        if (HelpMenu.HelpMenuItemSelected && HelpMenu.HelpMenuItemSelected.indexOf("tr_HelpMenuItem_") == 0)
                            HelpSection.DisplayHelp(HelpMenu.HelpMenuItemSelected);
                    }
                }
            }
        );

        $("#tblHelpMenuItems tr[id]").bind("click", function(e) {
            $("#tblHelpMenuItems tr[id]").removeClass("HelpMenu-HoverOver");
            $(this).addClass("HelpMenu-HoverOver");

            if (this.id.indexOf("tr_HelpMenuItem_") == 0) {
                if (HelpMenu.HelpItemBelowWindow)
                    HelpSection.DisplayHelp(this.id, true);
            } else
                HelpSection.ClearHelp();

            HelpMenu.HelpMenuItemSelected = this.id;

            HelpMenu.KeepPermanentOpen = true;
            e.stopPropagation();
        });

        // Walkthrough
        $("tr[id$=_tr_ShowMeWalkthrough]").bind("click", function(e) {
            if (HelpMenu.IsWalkThrough())
                HelpMenu.StopWalkthrough();
            else
                HelpMenu.ShowMeWalkthrough();
        });

        // Video Tutorial
        $(".HelpMenu-CloseButton").click(function(e) {
            HelpMenu.HideTutorial();
            e.stopPropagation();
        });

        $(".HelpMenu-CloseButton").hover(
            function() { $(this).addClass("HelpMenu-CloseButtonHover"); },
            function() { $(this).removeClass("HelpMenu-CloseButtonHover"); });
    },

    ShowTutorial: function() {
        $.video.show("/global/components/desktop/libraries/SiteStudio.HelpCenter/components/desktop/help_center_menu/resources/TutorialVideoPlayer.swf",
            { height: 542, width: 855 },
            [{ Key: "contentFolder", Value: HelpMenu.TutorialFolder },
                { Key: "contentFile", Value: HelpMenu.TutorialFile}]);
    },
    HideTutorial: function() {
        $.video.hide();
    },

    CurrentRotation: 0,
    RotateDegrees: 0,
    TimeoutID: 0,
    AnimateRotate: function(obj) {
        if (HelpMenu.RotateDegrees < 0) {
            HelpMenu.CurrentRotation -= 40;
            if (HelpMenu.CurrentRotation <= HelpMenu.RotateDegrees) HelpMenu.CurrentRotation = HelpMenu.RotateDegrees;
        } else {
            HelpMenu.CurrentRotation += 40;
            if (HelpMenu.CurrentRotation >= HelpMenu.RotateDegrees) HelpMenu.CurrentRotation = HelpMenu.RotateDegrees;
        }
        HelpMenu.PerformRotate(obj, HelpMenu.CurrentRotation);
        if (HelpMenu.CurrentRotation != HelpMenu.RotateDegrees) HelpMenu.TimeoutID = setTimeout(function() { HelpMenu.AnimateRotate(obj) }, 1);
    },

    PerformRotate: function(obj, deg) {
        if ($.browser.msie) {
            HelpMenu.IERotate(obj, deg);
        } else {
            obj.css("-webkit-transform", "rotate(" + deg + "deg)");
            obj.css("-moz-transform", "rotate(" + deg + "deg)");
        }
    },
    IERotate: function(obj, deg) {
        var rad = deg * (Math.PI * 2 / 360);
        costheta = Math.cos(rad);
        sintheta = Math.sin(rad);

        obj[0].filters.item(0).M11 = costheta;
        obj[0].filters.item(0).M12 = -sintheta;
        obj[0].filters.item(0).M21 = sintheta;
        obj[0].filters.item(0).M22 = costheta;
    }
}

// Displaying Help
var HelpSection = {

    HelpDialogWidth: 250,
    HelpDialogHeight: 180,
    HelpDialogSeparation: 10,

    ClearHelp: function() {
        //Remove help DOM elements if they have been previously rendered.
        $('#spanHelpableSelection').remove();
        $('#spanHelpText').remove();        
    },

    GetOuterCoordinates: function(controls) {
        var left = PositionHelper.getMinLeft(controls);
        var minTop = PositionHelper.getMinTop(controls);
        var width = PositionHelper.getMaxWidth(controls);
        var maxHeight = PositionHelper.getMaxHeight(controls);
        return [left, minTop, width, (maxHeight - minTop)];
    },

    FormatControlList: function(controls) {
        for (var i = controls.length - 1; i > -1; i--) {
            var id = HelpSection.FindControl(controls[i]);
            if (id)
                controls[i] = id;
            else
                controls.splice(i, 1);
        }
        return controls;
    },

    FindControl: function(id) {
        var marker = id.substring(0, 1);
        if (marker == "#") {
            if ($(id).length > 0) return id;
            var split = id.substr(1).split("_");
            var control = "";
            for (var i = split.length - 1; i >= 0; i--) {
                control = "_" + split[i] + control;
                if ($("[id$=" + control + "]").length == 1) return "#" + $("[id$=" + control + "]")[0].id;
            }
        }
        else {
            // Find by class
            if ($(id).length == 1) return id;
        }

        return null;
    },

    setPosition: function(elem, left, top, width, height) {
        if (left != null) $(elem).css('left', left + 'px');
        if (top != null) $(elem).css('top', top + 'px');
        if (width != null) $(elem).css('width', width + 'px');
        if (height != null) $(elem).css('height', height + 'px');
    },

    //Highlight an area based on coordinates.
    HighlightArea: function() {

        //No need to add the span if it's already been added.
        if ($('#spanHelpableSelection').length > 0) return;

        //Create and display the span.
        var newSpan = document.createElement('span');
        newSpan.setAttribute('id', 'spanHelpableSelection');
        $(newSpan).addClass('HelpMenu-HelpControl');
        HelpSection.setPosition(newSpan, HelpSection.ControlCoordinates[0], HelpSection.ControlCoordinates[1], HelpSection.ControlCoordinates[2], HelpSection.ControlCoordinates[3]);
        document.forms[0].appendChild(newSpan);
    },

    ControlCoordinates: null,
    //Render a span around the helpable controls.
    HighlightControls: function(controls) {
        //Format the control list
        controls = HelpSection.FormatControlList(controls);

        //Get the outer coordinates.
        HelpSection.ControlCoordinates = HelpSection.GetOuterCoordinates(controls);
        HelpSection.ControlCoordinates[0] -= 4; // top 
        HelpSection.ControlCoordinates[1] -= 4; // left
        HelpSection.ControlCoordinates[2] += 6; // width
        HelpSection.ControlCoordinates[3] += 6; // height

        //Highlight the helpable controls.
        HelpSection.HighlightArea();
    },

    DisplayHelpSection: function(helpTitle, helpText, coordinates, scrollToItem) {
        //No need to add the span if it's already been added.
        if ($('#spanHelpText').length > 0) return;
        
        //Create the container for help text.
        var newSpan = document.createElement("span");
        newSpan.className = "HelpMenu-HelpContainer";
        $(newSpan).html($("#spanTemplate").html());
        $(newSpan).attr('id', 'spanHelpText');        

        var top = HelpSection.ControlCoordinates[1];
        var height = HelpSection.ControlCoordinates[3];

        var center = top + (height / 2);        

        $($(newSpan).find("span")).text(helpTitle);
        $($(newSpan).find("div")).text(helpText);

        document.forms[0].appendChild(newSpan);

        var width = HelpSection.HelpDialogWidth;
        if ($(newSpan).width() < width)
            width = $(newSpan).width();
        $(newSpan).css("width", width);

        //Caclulate the left pos.
        var left =
        //not enough room to display help on left
            (HelpSection.ControlCoordinates[0] - width < HelpSection.HelpDialogSeparation) ?
        //display to right = leftpos + width + separation
            HelpSection.ControlCoordinates[0] + HelpSection.ControlCoordinates[2] + HelpSection.HelpDialogSeparation :
        //display to left - need to increase the separator space
            HelpSection.ControlCoordinates[0] - width - HelpSection.HelpDialogSeparation + 4;

        var newtop;
        var bottompadding = 50;
        var scrollpadding = 50;
        var padding = 0;
        var helpheight = $(newSpan).height() + padding > HelpSection.HelpDialogHeight ? HelpSection.HelpDialogHeight : $(newSpan).height();

        // show bottom arrow
        if ((left + 250) > $(window).width()) {
            $($(newSpan).find(".Arrow-Left")).hide();
            $($(newSpan).find(".Arrow-Right")).hide();
            $($(newSpan).find(".Arrow-Bottom")).show();

            newtop = top - helpheight - $($(newSpan).find(".Arrow-Bottom")).height() - HelpSection.HelpDialogSeparation + 4;

            left = HelpSection.ControlCoordinates[0] + (HelpSection.ControlCoordinates[2] / 2) - (width / 2);
        } else {
            // show right arrow
            if (left < HelpSection.ControlCoordinates[0]) {
                $($(newSpan).find(".Arrow-Left")).hide();
                $($(newSpan).find(".Arrow-Right")).show();
            }
            if ((left + $(newSpan).width()) > $(window).width()) {
                $(newSpan).width($(window).width() - left - 5);
                helpheight = $(newSpan).height() + padding > HelpSection.HelpDialogHeight ? HelpSection.HelpDialogHeight : $(newSpan).height();
            }
        }

        $(newSpan).hide();
        if (!newtop) newtop = center - ((helpheight + padding) / 2) + 3; // 3 padding for drop shadow

        var scrollTo = (newtop - $(window).height() + bottompadding + helpheight);
        if (HelpMenu.HelpItemBelowWindow && scrollToItem) {
            $('html, body').animate(
                { scrollTop: scrollTo }, 1000);
            HelpMenu.HelpItemBelowWindow = false;
        }
        else {
            HelpMenu.HelpItemBelowWindow = false;
            var bottomLimit = ($(window).height() + $(document).scrollTop() - bottompadding - helpheight);
            var topLimit = ($(document).scrollTop() + bottompadding + helpheight);
            if ((newtop > bottomLimit) || (newtop < topLimit)) {
                if (scrollToItem && HelpMenu.IsWalkThrough()) {
                    $('html, body').animate(
                        { scrollTop: scrollTo }, 1000);
                } else {
                    HelpMenu.HelpItemBelowWindow = true;

                    newtop = ($(window).height() + $(document).scrollTop() - bottompadding) - helpheight;
                    $($(newSpan).find(".Arrow-Left")).hide();
                    $($(newSpan).find(".Arrow-Right")).hide();
                    $($(newSpan).find(".Arrow-Bottom")).show();

                    left = HelpSection.ControlCoordinates[0] + (HelpSection.ControlCoordinates[2] / 2) - (width / 2);
                }
            }
        }

        HelpSection.setPosition($(newSpan), left, newtop, null, helpheight);

        $(newSpan).find(".HelpMenu-HelpText").hide();        
        $(newSpan).show();        
        $(newSpan).find(".HelpMenu-HelpText").fadeIn("slow");
    },

    DisplayHelp: function(helpMenuItemId, scrollToItem) {
        HelpSection.ClearHelp();

        //Get controls associated to the helpMenuItemId.
        var controls = HelpMenu.HelpMenuItems[helpMenuItemId].TargetControlID.split(',');

        HelpSection.HighlightControls(controls);

        //Display the help section.
        HelpSection.DisplayHelpSection(
            HelpMenu.HelpMenuItems[helpMenuItemId].Title,
            HelpMenu.HelpMenuItems[helpMenuItemId].Description,
            [null, HelpSection.ControlCoordinates[1], HelpSection.HelpDialogWidth, HelpSection.HelpDialogHeight],
            scrollToItem);
    }
};