/*
General Functions 
=========================
Author:               George Edwards
Date Created:         3/22/2011
*/
function pageIs(sPageName) {
    return (window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1).toLowerCase() == sPageName.toLowerCase());
}

Array.prototype.max = function () { return Math.max.apply(Math, this); };

// http://www.quirksmode.org/js/cookies.html
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

// http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// http://www.quirksmode.org/js/cookies.html
function eraseCookie(name) {
    createCookie(name, "", -1);
}

// http://clintoncherry.wordpress.com/2008/04/24/javascript-search-and-replace-query-string-values/
function replaceQueryString(url, param, value) {
    var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
    if (url.match(re))
        return url.replace(re, '$1' + param + "=" + value + '$2');
    else if (url.indexOf("?") == -1)
        return url + '?' + param + "=" + value;
    else
        return url + '&' + param + "=" + value;
}

/*
Resize Widgets Dynamically
==========================
Author:                George Edwards
Date:                  4/26/2011
*/

(function ($) {
    $.fn.alignHeights = function () {
        this.css("height", "auto");
        var aHeights = this.map(function () { return $(this).height(); }).get();
        this.css("height", aHeights.max() + 6);
    };
})(jQuery);

function adjustRowsOnResize() {
    $(window).resize(function () {
        $(".ahn-widget").attr("style", "margin-left: 0px; ").data("init", false);
        adjustRows();
    });
}

function adjustRowsOnResizeDisable() {
    $(window).unbind("resize");
}

$(adjustRows);
$(adjustRowsOnResize);

function adjustRows() {
    var total_width = $(".ahn-container").innerWidth();
    if (total_width == null) total_width = $("#ahn-container").innerWidth();
    if (total_width == null) return;

    $(".ahn-widget").css("margin-left", "0px");
    $(".ahn-widget").each(function () {
        if (!$(this).data("init")) {
            var spacing_size = 5;

            if ($(this).hasClass("ahn-widget-size-4")) $(this).css({ width: total_width, "float": "left", clear: "left" }).data("init", true);
            if ($(this).hasClass("ahn-widget-size-3")) $(this).css({ width: (total_width - (1 * spacing_size) - 250), "float": "left" }).data("init", true);
            if ($(this).hasClass("ahn-widget-size-2")) $(this).css({ width: Math.floor((total_width - (2 * spacing_size)) * 0.50), "float": "left" }).data("init", true);
            if ($(this).hasClass("ahn-widget-size-1")) $(this).css({ width: 240, "float": "left" }).data("init", true);
        }
    });

    var currentTop = 0;
    var currentRow = 0;
    $(".ahn-widget").each(function () {
        // if this is on the left
        if ($(this).offset().top != currentTop) {
            currentTop = $(this).offset().top;
            currentRow++;
            if ($(this).position().left > 10) {
                $(this).css("margin-left", "5px");
            }
        } else {
            $(this).css("margin-left", "5px");
        }
        $(this).attr("data-row", currentRow);
    });

    var maxRows = currentRow;
    for (var i = 0; i < maxRows; i++) {
        var numWidgets = $(".ahn-widget[data-row=" + (i + 1) + "]").length;
        var $last = $(".ahn-widget[data-row=" + (i + 1) + "]:last");
        var lastLeft = $last.position().left;
        var lastWidth = $last.outerWidth();
        var lastSpacing = $last.css("margin-left").replace("px", "");
        if (lastSpacing == "auto") lastSpacing = 0;
        lastSpacing = Math.floor(lastSpacing);
        var row_width = lastLeft + lastWidth + lastSpacing;
        var row_diff = total_width - row_width;

        if (row_diff > 0 && row_diff < 10)
            $last.css("margin-left", lastSpacing + row_diff);
    }

    $(".wide-featured-items-gallery-wrap li").alignHeights();
}

/* 
Page Tabs 
=========================
Description:          Tabs for the page navigation on the private home page
Base CSS Class:       ahn-page-tabs
Author:               George Edwards
Date Created:         05/04/2011
*/

$(function () {
    $(".ahn-page-tabs").tabs({
        create: function (event) {
            var selectedTabIndex = 0;

            $(this).find("li a").each(function (idx) {
                if (window.location.href.indexOf($(this).attr("data-url")) > 0) {
                    selectedTabIndex = idx;
                }
            });

            $(this).tabs("option", "selected", selectedTabIndex);
        },
        select: function (event, ui) {
            var tabURL = $(ui.tab).attr("data-url");
            if (tabURL) {
                if (window.location.href.indexOf(tabURL) < 0) {
                    window.location.href = tabURL;
                    return false;
                }
            }
        }
    }).show();
});

/* 
Hover Click on Widget Items 
=========================
Description:          Allows for Widgets with links to activate the link from anywhere
Base CSS Class:       ahn-item-link
Author:               George Edwards
Date Created:         3/30/2011
*/

$(function () {
    widgetItem_init();
});

function widgetItem_init($context) {
    if (typeof ($context) == "undefined") $context = $("body");

    $context.find(".wide-featured-items-gallery-wrap li").click(widgetItem_handleClick);
    $context.find(".wide-calendar-upcoming-events-wrap li").click(widgetItem_handleClick);
    $context.find(".ahn-standard-listing").click(widgetItem_handleClick);
    $context.find(".ahn-committee-member").click(widgetItem_handleClick);
    $context.find(".ahn-single-column .ahn-list-items li").click(widgetItem_handleClick);
}

function widgetItem_handleClick(event) {
    event.preventDefault();

    var link = $(this).find("a:not(.ahn-tool-tip-link, .ahn-listing-description-link):first");
    var linkHref = link.attr("href");
    var linkTarget = link.attr("target");

    if (linkHref && linkHref.indexOf("javascript") != 0) {
        if (linkTarget == "_blank") window.open(linkHref);
        else window.location = linkHref;
    }

}

/* 
Favorites 
=========================
Description:          Automatically builds controls for setting the favorite flag for an item
Base CSS Class:       ahn-favorite-icon
Author:               George Edwards
Date Created:         3/22/2011
*/
$(function () {
    favoriteIcon_init();
});

function favoriteIcon_init($context) {
    if (typeof ($context) == "undefined") $context = $("body");

    $context.find(".ahn-favorite-icon").click(favoriteIcon_handleClick);
    $context.find(".ahn-favorite-icon").mouseover(favoriteIcon_handleMouseover);
    $context.find(".ahn-list-items div:has(.ahn-favorite-icon), .ahn-list-items li:has(.ahn-favorite-icon)").hover(
        function () {
            // This causes problems with the general hover over of the list item
            //$(this).stop(true, true).find(".ahn-favorite-icon").delay(1000).mouseover();
        },
        function () {
            $(this).find(".ahn-favorite-icon").clearQueue().ahnTooltip('destroy');
        }
    );
}

function favoriteIcon_disable($context) {
    if (typeof ($context) == "undefined") $context = $("body");

    $context.find(".ahn-favorite-icon").unbind("click");
    $context.find(".ahn-favorite-icon").unbind("mouseover");
    $context.find(".ahn-list-items div:has(.ahn-favorite-icon), .ahn-list-items li:has(.ahn-favorite-icon)").unbind("hover");
}

function favoriteIcon_handleClick(event) {
    var $listingDiv = $(this).parent();
    var featureId = $listingDiv.attr("data-featureid");
    var itemId = $listingDiv.attr("data-itemid");
    var favoriteId = $listingDiv.attr("data-favoriteid");
    var helpLabel = "";
    var removeClass = null;
    var addClass = null;
    var ajaxAction = null;
    var ajaxData = null;

    // Ensure the icon stays visible during a click
    $(this).css("display", "block");

    if ($(this).hasClass("ahn-enabled")) {
        ajaxAction = "remove";
        ajaxData = "favorite_id=" + favoriteId;
        helpLabel = "Add to Favorites";
        removeClass = "ahn-enabled";
    }
    else {
        ajaxAction = "add";
        ajaxData = "feature_id=" + featureId + "&item_id=" + itemId;
        helpLabel = "Remove from Favorites";
        addClass = "ahn-enabled";
    }

    if (ajaxAction) {
        $.ajax({
            //async: false,
            url: "favorites_svc.asp",
            data: "action=" + ajaxAction + "&" + ajaxData,
            dataType: "json",
            type: "GET",
            success: function (data) {
                if (data["favorite_id"]) {
                    if (data["favorite_id"] != "removed")
                        $listingDiv.attr("data-favoriteid", data["favorite_id"]);
                    else
                        $listingDiv.removeAttr("data-favoriteid");
                }
                else {
                    helpLabel = "Error: Unable to complete the request (2345).";
                    removeClass = null;
                    addClass = null;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                helpLabel = "Error: Unable to complete the request (" + xhr.statusText + ").";
                removeClass = null;
                addClass = null;
            }
        });
    }

    if (removeClass) $(this).removeClass(removeClass);
    if (addClass) $(this).addClass(addClass);
    $(this).find(".ahn-tooltip-body a").text(helpLabel);
    $(this).ahnTooltip("resize");

    event.stopPropagation();
}

function favoriteIcon_handleMouseover(event) {
    var message = ($(this).hasClass("ahn-enabled") ? "Remove from Favorites" : "Add to Favorites");
    $(this).ahnTooltip({ contents: "<a href=\"javascript:;\" class=\"ahn-tool-tip-link hover-over\">" + message + "</a>", at: $(this) });
}

/*  IsAllChecked
=========================
Description:          Return true or false to see if all values are checked = true
Parameters:           [none] Selector is on jQuery object
Author:               George Edwards and Chris Harrison
Date Created:         6/14/2011
*/
(function ($) {
    $.fn.isAllChecked = function () {
        var isAllChecked = true;
        $.each(this, function (i, checkBox) {
            isAllChecked = ($(checkBox).attr("checked") && isAllChecked);
        });
        return isAllChecked;
    };
})(jQuery);

/*
Tool Tip 
=========================
Description:          Show a tooltip with a message next to an existing DOM element
Base CSS Class:       ahn-tooltip
Author:               George Edwards
Date Created:         3/23/2011
*/
(function ($) {
    var settings = {
        'location': 'right',
        'backgroundColor': 'white',
        'dropShadow': true,
        'contents': 'hello world',
        'showSpeed': 'fast',
        'at': null
    };

    var methods = {
        // Initilization
        init: function (options) {
            if (options) {
                $.extend(settings, options);
            }
            if (!settings.at) settings.at = document.body;
            else if (settings.at.length > 0) settings.at = settings.at.get(0);

            return this.each(function () {
                var $this = $(this);

                $this.queue(function (next) {
                    var tooltipLeft = $this.offset().left - $(settings.at).offset().left + $this.width();
                    var tooltipTop = $this.offset().top - $(settings.at).offset().top;

                    // TODO:  if location other than 'right', set the position here

                    if (!$this.data('ref')) {
                        $this.data('ref', $ref = $('<div />', {
                            html: "<div class=\"ahn-tooltip-tip\" /><div class=\"ahn-tooltip-body\">" + settings.contents + "</div>",
                            css: { top: tooltipTop, left: tooltipLeft, display: 'none' }
                        }).addClass("ahn-tooltip").appendTo(settings.at));

                        if (settings.dropShadow) {
                            $("<div />", {
                                css: { width: ($this.data('ref').width() - 4) }
                            }).addClass("ahn-tooltip-shadow-bottom").appendTo($this.data('ref'));
                            $("<div />", {
                                css: { height: ($this.data('ref').height() - 4), left: ($this.data('ref').width() + 11) }
                            }).addClass("ahn-tooltip-shadow-right").appendTo($this.data('ref'));
                        }
                    }

                    $this.data('ref').fadeIn(settings.showSpeed);
                    next();
                });
            });
        },
        // Clean-up
        destroy: function () {
            return this.each(function () {
                var $this = $(this);

                if ($this.data('ref')) {
                    $this.data('ref').fadeOut(settings.showSpeed).remove();
                    $this.removeData('ref');
                }
            });
        },
        // Resize based on new html
        resize: function () {
            return this.each(function () {
                var $this = $(this);

                if ($this.data('ref')) {
                    $this.data('ref').find(".ahn-tooltip-shadow-bottom").css({ width: ($this.data('ref').width() - 4) });
                    $this.data('ref').find(".ahn-tooltip-shadow-right").css({ height: ($this.data('ref').height() - 4), left: ($this.data('ref').width() + 11) });
                }
            });
        }
    };

    $.fn.ahnTooltip = function (method) {
        // Method calling logic
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method + ' does not exist on jQuery.ahnTooltip');
        }
    };
})(jQuery);

/* 
Edit Page Button 
=========================
Description:          Allow community administrators to edit the page by clicking on a button
Base CSS Class:       ahn-up-page-edit
Author:               George Edwards
Date Created:         3/28/2011
*/
$(function () {
    $(".ahn-up-page-edit").click(editPageButton_handleClick);
});

function editPageButton_handleClick(event) {
    if ($(this).hasClass("ahn-up-page-edit")) {
        $(this).blur().animate({ opacity: 0, width: "56px" }, 500).queue(function (next) {
            $(this).addClass("ahn-up-page-done").removeClass("ahn-up-page-edit");
            //eraseCookie("hideEditPageTooltip");
            if (!readCookie("hideEditPageTooltip"))
                modal_dialog("Edit Mode", "<div style=\"font-size: 0.8em; text-align: center; \">You are now in Edit Mode.  While in Edit Mode, you may modify the placement and properties of certain page elements within your page.  Click <strong>Done</strong> after you have finished making your changes.<br /><br /><input type=\"checkbox\" /> Do not show this message in the future</div>", 350, 75, "OK", null, false, true, null, null, hideEditPageTooltip);

            $(".ahn-widget").each(function () {
                buildHandle($(this));
            });
            //$(window).bind('beforeunload', windowNavigate_handleBeforeUnload);
            next();
        }).animate({ opacity: 1 }, 500);

        $(".ahn-widget-edit-menu-btn").each(function () {
            editWidgetMenu_createMenu(event, this);
        });

        $("<div />")
            .html("<a class=\"ahn-up-page-add\" href=\"javascript:;\"></a>")
            .css({ "float": "right", "margin-right": "5px", "display": "none" })
            .insertAfter($(this))
            .delay(500)
            .fadeIn(500)
            .queue(function (next) {
                widgetAdd_init();
                next();
            });
    } else {
        $(this).blur().animate({ opacity: 0, width: "26px" }, 500).queue(function (next) { $(this).addClass("ahn-up-page-edit").removeClass("ahn-up-page-done"); next(); }).animate({ opacity: 1, width: "78px" }, 500);
        $(".ahn-widget-handle").removeData("ref").remove();
        $(".ahn-up-page-add").parent().remove();
        //$(window).unbind('beforeunload');
    }
}

function buildHandle($widget) {
    var cssDark = ($(".ahn-wrapper:first").hasClass("ahn-bg-dark") ? "ahn-bg-dark" : "");

    var $handle = $("<div />")
        .css({ width: $widget.width(), top: $widget.offset().top - 16, left: $widget.offset().left, display: "none" })
        .addClass("ahn-widget-handle")
        .addClass(cssDark)
        .attr("data-pageElement", $widget.attr("pgElement"))
        .append(
            $("<div />")
                .addClass("ahn-widget-edit-menu-btn")
                .html("<a href=\"javascript:;\">Edit Widget</a>")
                .click(editWidgetMenu_handleClick)
                .hover(editWidgetMenu_createMenu, editWidgetMenu_removeMenu)
        )
        .data("ref", $widget[0])
        .appendTo("body")
        .queue(function (next) {
            var $menuBtn = $(this).find(".ahn-widget-edit-menu-btn");
            var $menu = null;
            if ($menuBtn.children(".ahn-widget-edit-menu").length > 0) $menu = $menuBtn.children(".ahn-widget-edit-menu");

            if (!$menu) {
                $menu = $("<div />")
                    .css("display", "none")
                    .addClass("ahn-widget-edit-menu")
                    .html("<ul />")
                    .appendTo($menuBtn);

                // Call the database to get the details about this widget
                buildWidgetDropDownMenu($menu);
            }
            next();
        })
        .fadeIn();
}

function hideEditPageTooltip(event) {
    if ($("#modal-dialog input[type=checkbox]").is(':checked')) {
        createCookie("hideEditPageTooltip", true, 1000);
    }
}
function editWidgetMenu_handleClick(event) {
    if (!$(this).hasClass("ahn-active")) {
        editWidgetMenu_createMenu(event, this);
    }
    else {
        editWidgetMenu_removeMenu(event, this);
    }
}
function editWidgetMenu_createMenu(event, context) {
    // Define each of the objects needed for the menu
    var $this = $(this);
    if (typeof context != "undefined") $this = $(context);
    var $menu = null;
    if ($this.children(".ahn-widget-edit-menu").length > 0) $menu = $this.children(".ahn-widget-edit-menu");

    if (!$this.hasClass("ahn-active")) {
        $this.find("a").blur();
        $(".ahn-active").click();
        $this.addClass("ahn-active");
        $this.find("img").attr("src", "images/edit-widget-menu-up.png");
        $this.parent().css("z-index", 2);

        if (!$menu) {
            $menu = $("<div />")
                .css("display", "none")
                .addClass("ahn-widget-edit-menu")
                .html("<ul />")
                .appendTo($this);

            // Call the database to get the details about this widget
            buildWidgetDropDownMenu($menu);
        }
        // the stop will help when a slideUp is already in motion
        $menu.stop(true, true).slideDown(400);
    }
}
function buildWidgetDropDownMenu(context) {
    var $menu = context;
    var $widget = null;
    if ($menu.parent().parent().data("ref")) $widget = $($menu.parent().parent().data("ref"));

    var errorMsg = null;
    var pageElementData = null;

    if ($menu.data("pageElement") || $menu.find("ul li").length > 0) {
        $menu.find("ul li").remove();
        $menu.removeData("pageElement");
    }

    $.ajax({
        //async: false,
        url: "widget_svc.asp",
        data: "action=info&pageElement=" + $widget.attr("pgElement"),
        dataType: "json",
        type: "GET",
        success: function (data) {
            if (data.hasOwnProperty("pageElement") && data.pageElement.id == $widget.attr("pgElement")) {
                pageElementData = data;
                buildWidgetDropDownMenu_handleSuccess(pageElementData, $menu);
            }
            else {
                errorMsg = "Error: Unable to complete the request (7894).";
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
        }
    });

    if (errorMsg) {
        $menu.find("ul").append($("<li />").html(errorMsg));
    }
}

function widgetAdd_init() {
    $(".ahn-up-page-add").click(widgetAdd_handleClick);
}

function buildWidgetDropDownMenu_handleSuccess(pageElementData, $menu) {
    $menu.data("pageElement", pageElementData);

    if (pageElementData.menuOptions.editText) {
        $menu.find("ul").append(
                        $("<li />").append(
                            $("<a />").attr("href", "javascript:;").addClass("ahn-widget-lnk-rte").html("Edit Text").click(editWidgetLinkRTE_handleClick)
                        )
                    );
    }

    if (pageElementData.menuOptions.editProperties) {
        $menu.find("ul").append(
                        $("<li />").append(
                            $("<a />").attr("href", "javascript:;").addClass("ahn-widget-lnk-edit").html("Edit Properties").click(editWidgetLinkEdit_handleClick)
                        )
                    );
    }

    if (pageElementData.menuOptions.customSort.visible) {
        $menu.find("ul").append(
                        $("<li />").append(
                            $("<a />").attr("href", "javascript:;").addClass("ahn-widget-lnk-sort").html("Sort Items").click(editWidgetLinkSort_handleClick)
                        )
                    );
    }

    // Everybody gets move widget
    $menu.find("ul").append(
        $("<li />").append(
            $("<a />").attr("href", "javascript:;").addClass("ahn-widget-lnk-move").html("Move Widget").click(editWidgetLinkMove_handleClick)
        )
    );

    if (!pageElementData.pageElement.isLocked) {
        $menu.find("ul").append(
            $("<li />").append(
                $("<a />").attr("href", "javascript:;").addClass("ahn-widget-lnk-delete").html("Delete Widget").click(editWidgetLinkDelete_handleClick)
            )
        );
    }
}

function editWidgetLinkMove_handleClick(event) {
    var $mainContainer = $(".ahn-container");

    $(".ahn-widget").each(function () { editWidget_disableInteractions($(this), false); });

    $(".ahn-widget-handle").fadeOut(200);
    $(".ahn-up-page-done").animate({ opacity: 0 });
    $(".ahn-up-page-add").animate({ opacity: 0 });

    $("<div />")
            .css({ "position": "absolute", "top": $mainContainer.offset().top - 40, "left": ($mainContainer.offset().left + $mainContainer.width() - 56), "z-index": 1010 })
            .html("<a href=\"javascript:;\" class=\"ahn-up-page-done\"></a>")
            .appendTo("body")
            .click(btnDoneMove_handleClick)
            .fadeIn();

    $(".ahn-container").sortable({
        placeholder: "ahn-droppable",
        forcePlaceholderSize: true,
        tolerance: "pointer",
        scroll: true,
        scrollSpeed: 20,
        scrollSensitivity: 120,
        containment: "parent",
        stop: adjustRows
    });
}

function btnDoneMove_handleClick(event) {
    var btnDone = this;
    var pageFeaturePageName = $(".ahn-wrapper").attr("data-page-name");
    var sortString = "";
    $(".ahn-widget").each(function (idx) {
        if (sortString != "") sortString += ";";
        sortString += $(this).attr("pgElement") + ":" + idx;
    });

    var jsonData = "&pageName=" + pageFeaturePageName;
    jsonData += "&widgetOrder=" + escape(sortString);

    $.ajax({
        url: "widget_svc.asp",
        data: "action=move" + jsonData,
        dataType: "json",
        context: btnDone,
        type: "GET",
        success: function (data) {
            if (data && data.hasOwnProperty("success")) {
                var refreshUrl = replaceQueryString(window.location.href, "j", data.success);
                window.location.href = refreshUrl;
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
            $(this).ahnTooltip({ contents: errorMsg }).delay(2000).queue(function (next) { $(this).ahnTooltip("destroy"); next(); });
        }
    });
}

function editWidgetLinkDelete_handleClick(event) {
    var $menu = $(this).parents(".ahn-widget-edit-menu");
    var pageElementData = $menu.data("pageElement");
    var $handle = $menu.parent().parent();

    var $deleteDialog = $("<div />")
        .addClass("ahn-widget-delete-dialog")
        .html("<div style=\"text-align: center; \">Are you sure you would like to remove this widget from your page?</div><div style=\"font-size: 0.8em; text-align: center; \"><br /><br />Note: Deleting a widget does not affect the data or elements within the widget.  It simply removes the widget from your page.</div>")
        .data("pageElement", pageElementData)
        .data("ref", $handle);

    modal_dialog(
        "Delete Widget",
        $deleteDialog,
        350,
        75,
        "Delete",
        btnDelete_handleClick,
        true,
        true
    );
}

function btnDelete_handleClick(event) {
    var $deleteDialog = $(".ahn-widget-delete-dialog");
    var $handle = $deleteDialog.data("ref");
    var pageElementData = $deleteDialog.data("pageElement");
    var pageFeaturePageName = $(".ahn-wrapper").attr("data-page-name");

    var jsonData = "&pageName=" + pageFeaturePageName;
    jsonData += "&pageElement=" + pageElementData.pageElement.id;

    $.ajax({
        url: "widget_svc.asp",
        data: "action=delete" + jsonData,
        dataType: "json",
        type: "GET",
        success: function (data) {
            if (data && data.hasOwnProperty("success")) {
                $handle.remove();
                $(".ahn-widget[pgElement=" + pageElementData.pageElement.id + "]").remove();
                adjustRows();
                widgetHandle_adjustForNewContent();
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
            alert(errorMsg);
        }
    });
}

function editWidgetMenu_removeMenu(event, context) {
    var $this = $(this);
    if (typeof context != "undefined") $this = $(context);

    $this.find("a").blur();
    $this.find(".ahn-widget-edit-menu").slideUp(200);
    if ($this.parent().css("z-index") < 10) $this.parent().css("z-index", 1);
    $this.removeClass("ahn-active");
    $this.find("img").attr("src", "images/edit-widget-menu-down.png");
}
function editWidgetLinkRTE_handleClick(event) {
    var $menu = $(this).parents(".ahn-widget-edit-menu");
    var $widget = null;
    var $handle = $menu.parent().parent();
    if ($handle.data("ref")) {
        $widget = $($handle.data("ref"));
        widgetTextEditDialog_handleOpen($widget, $widget);
    }
}
function editWidgetLinkEdit_handleClick(event) {
    var $menu = $(this).parents(".ahn-widget-edit-menu");
    var pageElementData = $menu.data("pageElement");
    var customHeight = 60;

    var $propertiesWindow = $("<div />")
        .data("menu", $menu)
        .addClass("ahn-widget-edit-properties-dialog");
    $propertiesWindow.html(
        widgetProperties_html({
            "editTitle": pageElementData.pageElement.editTitle,
            "title": pageElementData.pageElement.title,
            "favoriteFeedId": pageElementData.pageElement.favoriteFeedId,
            "favoriteSelected": pageElementData.pageElement.favoriteSelected,
            "categorySelect": pageElementData.pageElement.categorySelect,
            "categoryOptions": pageElementData.pageElement.categoryOptions,
            "currentCategories": pageElementData.pageElement.currentCategories,
            "editTop": pageElementData.pageElement.editTop,
            "topOptions": pageElementData.topOptions,
            "topValue": pageElementData.pageElement.currentTop,
            "widgetStyles": pageElementData.pageElement.widgetStyles,
            "editUsername": pageElementData.pageElement.editUsername,
            "currentUsername": pageElementData.pageElement.currentUsername,
            "sortOptions": pageElementData.pageElement.sortOptions,
            "sortValue": pageElementData.pageElement.currentSort,
            "IsMsgBoard": pageElementData.pageElement.IsMsgBoard,
            "IsAdhocMsg": pageElementData.pageElement.IsAdhocMsg,
            "AdhocMsgType": pageElementData.pageElement.AdhocMsgType,
            "AdhocMsgText": pageElementData.pageElement.AdhocMsgText,
            "AdhocMsgGroup": pageElementData.pageElement.AdhocMsgGroup,
            "IsPhotoAlbum": pageElementData.pageElement.IsPhotoAlbum,
            "animationSpeed": pageElementData.pageElement.animationSpeed,
            "HotRepliesSelected": pageElementData.pageElement.HotRepliesSelected,
            "IsClassifieds": pageElementData.pageElement.IsClassifieds,
            "premiumSelected": pageElementData.pageElement.premiumSelected
        })
    );

    modal_dialog(
        "Widget Wizard",
        $propertiesWindow,
        600,
        customHeight,
        "Apply",
        widgetPropertiesApply_handleClick,
        true,
        true,
        null,
        null,
        null
    );

    // Set selector divs to the same height of the tallest one
    if (pageElementData.pageElement.widgetStyles.length > 1) {
        var tallestDiv = 0;
        $(".ahn-widget-edit-feed-list .ahn-selector").each(function () {
            if ($(this).height() > tallestDiv) tallestDiv = $(this).height();
        });
        $(".ahn-widget-edit-feed-list .ahn-selector").height(tallestDiv);
    }
}
function favoritesOnly_handleClick(event) {
    var $feedDiv = $($(this).data("ref"));
    $feedDiv.data("favoriteSelected", $(this).is(':checked'));
}
function widgetPropertiesApply_handleClick(event) {
    var $propertiesWindow = $(".ahn-widget-edit-properties-dialog");
    var $menu = $propertiesWindow.data("menu");
    var pageElementData = $menu.data("pageElement");
    var $widget = null;
    if ($menu.parent().parent().data("ref")) $widget = $($menu.parent().parent().data("ref"));
    var widgetHtml = null;

    var pageElementId = pageElementData.pageElement.id;
    var pageElementTitle = ($propertiesWindow.find("#ahn-widget-edit-title").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-title").val() : null);
    var pageElementTop = ($propertiesWindow.find("#ahn-widget-edit-top-edit-option").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-top-edit-option option:selected").attr("value") : null);
    var pageElementSort = ($propertiesWindow.find("#ahn-widget-edit-sort-option").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-sort-option").val() : null);
    var pageElementIsMsgBoard = ($propertiesWindow.find("#ahn-widget-hot-replies-checkbox").length == 1 ? $propertiesWindow.find("#ahn-widget-hot-replies-checkbox").is(":checked") : false);
    var pageElementIsClassifieds = ($propertiesWindow.find("#ahn-widget-premium-checkbox").length == 1 ? $propertiesWindow.find("#ahn-widget-premium-checkbox").is(":checked") : false);
    var pageElementAdhocMsgCnt = ($propertiesWindow.find("#ahn-messages-list li").length);
    var pageElementAdHocMsgType = ($propertiesWindow.find("input:radio[name=grp1]:checked").val());
    var pageElementAdhocMsgGroup = ($propertiesWindow.find("#ahn-messages-list").attr("group"))

//------------- category select -------------------------
    var pageElementCategoryId = "";

    if ($propertiesWindow.find("#ahn-widget-category-multiselect-edit-option").length) {
        //get checked values
        $("#ahn-widget-category-multiselect-edit-option > input").each(function (i) {
            if ($(this).is(':checked')) pageElementCategoryId += $(this).val() + ",";
        });
        if (pageElementCategoryId != "") pageElementCategoryId = pageElementCategoryId.substring(0, pageElementCategoryId.length - 1);  //remove trailing comma
    }
    else if ($propertiesWindow.find("#ahn-widget-category-select-list").length) {
        //get selected value
        pageElementCategoryId = $("#ahn-widget-category-select-list").val();
    }
//------------- end category select ---------------------

    var pageElementFeedId = null;
    pageElementFeedId = pageElementData.pageElement.feedId;
    if ($propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").length > 0) {
        if ($propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").is(":checked")) {
            pageElementFeedId = $propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").val();
        }
    }

    var pageElementWidgetId = null;
    var pageElementWidgetSize = 4;
    if ($propertiesWindow.find(".ahn-widget-edit-style-container .ahn-selected").length == 1) {
        pageElementWidgetId = $propertiesWindow.find(".ahn-widget-edit-style-container .ahn-selected").data("widgetid");
        pageElementWidgetSize = $propertiesWindow.find(".ahn-widget-edit-style-container .ahn-selected").data("size");
    }

    var pageElementUsername = null;
    if ($propertiesWindow.find("#ahn-widget-edit-username").length > 0) {
        pageElementUsername = $propertiesWindow.find("##ahn-widget-edit-username").val();
    }
    var pageElementHotReplies = false;
    if ($propertiesWindow.find("#ahn-widget-hot-replies-checkbox").length > 0) {

        if ($propertiesWindow.find("#ahn-widget-hot-replies-checkbox").is(":checked")) {
            pageElementHotReplies = true;
        }
    }

    //input for adhoc message data
    var pageElementAdhocMsg = null;
    if (pageElementAdhocMsgCnt > 0) {
        var optionTexts = [];
        $("#ahn-messages-list li span").each(function () {
            optionTexts.push($(this).text())
        });

        pageElementAdhocMsg = optionTexts.join("|");
    }

    //animation speed
    var pageElementAnimationSpeed = "";
    if ($propertiesWindow.find("#ahn-widget-animation-speed-select-list").length) {
        //get selected value
        pageElementAnimationSpeed = $("#ahn-widget-animation-speed-select-list").val();
    }

    var jsonData = "&pageElement=" + pageElementId;
    if (pageElementTitle) jsonData += "&title=" + escape(pageElementTitle);
    if (pageElementFeedId) jsonData += "&feedid=" + pageElementFeedId;
    if (pageElementTop) jsonData += "&top=" + pageElementTop;
    if (pageElementSort) jsonData += "&sort=" + pageElementSort;
    if (pageElementCategoryId != "") jsonData += "&categoryId=" + pageElementCategoryId;
    if (pageElementWidgetId) jsonData += "&widgetid=" + pageElementWidgetId;
    if (pageElementUsername) jsonData += "&source=" + pageElementUsername;
    if (pageElementIsMsgBoard) jsonData += "&hot_replies=" + pageElementHotReplies;
    if (pageElementIsClassifieds) jsonData += "&premium=" + pageElementIsClassifieds;
    if (pageElementAdhocMsg) jsonData += "&txtMessages=" + pageElementAdhocMsg;
    if (pageElementAdhocMsg) jsonData += "&adhocMsgType=" + pageElementAdHocMsgType;
    if (pageElementAdhocMsg) jsonData += "&adhocMsgGroup=" + pageElementAdhocMsgGroup;
    if (pageElementAnimationSpeed) jsonData += "&animationSpeed=" + pageElementAnimationSpeed;

    $.ajax({
        //async: false,
        url: "widget_svc.asp",
        data: "action=update" + jsonData,
        dataType: "html",
        type: "GET",
        success: function (data) {
            widgetHtml = data;
            if (widgetHtml) {
                $widget.find(".ahn-widget-content").html(widgetHtml);
                $widget.removeClass("ahn-widget-size-4").removeClass("ahn-widget-size-3").removeClass("ahn-widget-size-1").addClass("ahn-widget-size-" + pageElementWidgetSize);
                $widget.data("init", false);
                buildWidgetDropDownMenu($menu);
                initWidgetInteractions($widget);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
        }
    });
}

function editWidget_disableInteractions($widget, isSort) {
    favoriteIcon_disable($widget);
    $widget.find(".wide-featured-items-gallery-wrap li, .ahn-standard-listing, .wide-calendar-upcoming-events-wrap li").unbind("click");

    $widget.find(".ahn-list-items").disableSelection();
    if (!isSort) $widget.addClass("ahn-moveable");
    $widget.find(".ahn-list-items > div, .ahn-list-items > li, .ahn-list-items a, .ahn-list-items .ahn-favorite-icon").addClass("ahn-moveable");
    $widget.find("a").addClass("ahn-prevent-click").click(function (event) { if ($(this).hasClass("ahn-prevent-click")) event.preventDefault(); });
}


function editWidgetLinkSort_handleClick(event) {
    var $menu = $(this).parents(".ahn-widget-edit-menu");
    var pageElementData = $menu.data("pageElement");
    var $widget = null;
    var $handle = $menu.parent().parent();
    if ($handle.data("ref")) $widget = $($handle.data("ref"));

    if ($widget && pageElementData.menuOptions.customSort.enabled) {
        editWidget_disableInteractions($widget, true);

        // Top Modal
        $("<div />")
            .height($widget.offset().top)
            .css("z-index", 999)
            .addClass("ui-widget-overlay")
            .appendTo("body");

        // Bottom Modal
        var topHeight = $widget.offset().top + $widget.height();
        $("<div />")
            .height($(document).height() - topHeight)
            .css({ "z-index": 999, "top": topHeight })
            .addClass("ui-widget-overlay")
            .appendTo("body");

        // Left Modal
        $("<div />")
            .height($widget.height())
            .width($widget.offset().left)
            .css({ "z-index": 999, "left": 0, "top": $widget.offset().top })
            .addClass("ui-widget-overlay")
            .appendTo("body");

        // Right Modal
        var leftWidth = $widget.offset().left + $widget.width();
        $("<div />")
            .height($widget.height())
            .width($(document).width() - leftWidth)
            .css({ "z-index": 999, "left": leftWidth, "top": $widget.offset().top })
            .addClass("ui-widget-overlay")
            .appendTo("body");

        if ($widget.find(".wide-featured-items-gallery-wrap").length > 0) {
            $widget.find(".ahn-list-items li").each(function () { $(this).width($(this).width() - 1); });
            $widget.find(".ahn-list-items").sortable({ update: listItem_handleSortUpdate });
        }
        else {
            $widget.find(".ahn-list-items").sortable({
                placeholder: "ui-state-highlight",
                forcePlaceholderSize: true,
                update: listItem_handleSortUpdate
            });
        }

        $(".ahn-widget-edit-menu-btn").fadeOut(200);
        $(".ahn-up-page-done").animate({ opacity: 0 });
        $(".ahn-up-page-add").animate({ opacity: 0 });

        $("<div />")
            .css({ "position": "absolute", "top": ($widget.offset().top - 23), "left": ($widget.offset().left + $widget.width() - 60), "z-index": 1010 })
            .html("<a href=\"javascript:;\" class=\"ahn-up-page-done\"></a>")
            .appendTo("body")
            .click(btnDoneSort_handleClick)
            .fadeIn()
            .data("ref", $handle);
        /*
        $("<div />")
        .css({ background: "white", color: "#666666", height: "50px", width: $widget.width(), position: "absolute", top: $widget.offset().top + $widget.height() + 20, left: $widget.offset().left, "z-index": 2000, border: "1px solid #000", display: "none", "overflow-y": "scroll" })
        .addClass("ahn-debug")
        .appendTo("body")
        .fadeIn();
        */
    }
    else {
        modal_dialog("Sort Items", "<div style=\"font-size: 0.8em; text-align: center; \">Custom sort is currently only available when <strong>Favorites Only</strong> is selected.<br /><br />To change this setting, choose Edit Properties on this Widget.  Otherwise, the default sort will be shown.</div>", 350, 75, "OK", null, false);
    }
}
function listItem_handleSortUpdate(event, ui) {
    var $item = ui.item;
    var $list = $item.parents(".ahn-list-items");
    var featureId = $item.attr("data-featureid");
    var itemId = $item.attr("data-itemid");
    var favoriteId = $item.attr("data-favoriteid");
    var newOrder = $list.children().index($item) + 1;
    var ajaxAction = "sort";
    var ajaxData = null;

    ajaxData = "favorite_id=" + favoriteId + "&new_order=" + newOrder;

    if (ajaxAction) {
        $.ajax({
            //async: false,
            url: "favorites_svc.asp",
            data: "action=" + ajaxAction + "&" + ajaxData,
            dataType: "json",
            type: "GET",
            success: function (data) {
                if (data["favorite_id"]) {
                    if (data["favorite_id"] != "sorted")
                        alert("Error: Unable to complete the request (898).  Please try again.");
                }
                else {
                    alert("Error: Unable to complete the request (897).  Please try again.");
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert("Error: Unable to complete the request (" + xhr.statusText + ").");
            }
        });
    }
    //$(".ahn-debug").append("sort complete. new order: " + newOrder + "<br />");
}
function btnDoneSort_handleClick() {
    var $widget = null;
    var $handle = $(this).data("ref");
    if ($handle.data("ref")) $widget = $($handle.data("ref"));

    $widget.find(".ahn-list-items").sortable("destroy");
    $(".ui-widget-overlay").remove();
    $(".ahn-widget-edit-menu-btn").delay(500).fadeIn(500);
    $(this).remove();
    $(".ahn-up-page-done").animate({ opacity: 1 });
    $(".ahn-up-page-add").animate({ opacity: 1 });

    // Reset the Favorites and the click events
    $widget.find(".ahn-list-items").enableSelection();
    $widget.find(".ahn-list-items > div, .ahn-list-items > li, .ahn-list-items a, .ahn-list-items .ahn-favorite-icon").removeClass("ahn-moveable");
    $widget.find("a").removeClass("ahn-prevent-click");
    widgetItem_init($widget);
    favoriteIcon_init($widget);
}

function windowNavigate_handleBeforeUnload(event) {
    return "Your work may not be done yet.  Click Done, then go resume your previous action.";
}

function widgetHandle_adjustForNewContent() {
    $(".ahn-widget-handle").each(function () {
        var $widget = $($(this).data("ref"));
        $(this).css({ width: $widget.width(), top: $widget.offset().top - 16, left: $widget.offset().left });
    });
}

/*
Add WIDGET
=====================================
*/

function widgetAdd_handleClick(event) {
    var pageFeaturePageName = $(".ahn-wrapper").attr("data-page-name");
    //** edit to prevent menu from showing account and user profile info
    var pageType = $("#strPageType").val();
    if (pageType == null) {
        //** if we have no hidden field assume we are in Private mode 
        //** remember you can only edit in private mode logged in anyways.
        pageType = "Private"
    };

    // pass the pageType thru the ajax
    var addBtn = event.target;
    $(addBtn).blur();
    $.ajax({
        url: "widget_svc.asp",
        data: "action=addinfo&pageName=" + pageFeaturePageName + "&pageType=" + pageType,
        dataType: "json",
        type: "GET",
        context: addBtn,
        success: function (data) {
            if (data.hasOwnProperty("feeds")) {
                widgetAdd_displayGallery(data);
            }
            else {
                var errorMsg = "Error: Unable to complete the request (No data available).";
                $(this).ahnTooltip({ contents: errorMsg }).delay(2000).queue(function (next) { $(this).ahnTooltip("destroy"); next(); });
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            var errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
            $(this).ahnTooltip({ contents: errorMsg }).delay(2000).queue(function (next) { $(this).ahnTooltip("destroy"); next(); });
        }
    });
}

function widgetAdd_displayGallery(up) {
    var customHeight = 210;

    var $wizardWindow = $("<div />")
                    .data("upData", up)
                    .addClass("ahn-widget-edit-properties-dialog");

    if (up.feeds.length > 0) {
        var $feedContainer = $("<div />").addClass("ahn-widget-edit-feed-container");
        var $feedList = $("<div />").addClass("ahn-widget-edit-feed-list");

        $.each(up.feeds, function (i, feed) {
            $feedList.append(
                        $("<div />")
                            .addClass("ahn-selector")
                            .addClass((feed.selected ? "ahn-selected" : ""))
                            .data("feedid", feed.key)
                            .data("feedidx", i)
                            .html("<img src=\"" + (feed.icon || "nopic.png") + "\" width=\"40\" height=\"40\" border=\"0\" alt=\"" + feed.value + "\" /><br />" + feed.value)
                            .click(widgetSelection_handleClick)
                    );
        });
        $feedList.append(
                    $("<div />").addClass("clear")
                );

        if (up.feeds.length > 1) {
            $("<div />").addClass("ahn-form-label").html("Choose a Widget:").appendTo($wizardWindow);
            $feedList.appendTo($feedContainer);
            $feedContainer.appendTo($wizardWindow);
            customHeight += 100;
        }
        else {
            $feedList.appendTo($feedContainer);
            $feedContainer.css("display", "none");
            $feedContainer.appendTo($wizardWindow);
        }
    }

    modal_dialog(
                "Widget Wizard",
                $wizardWindow,
                600,
                customHeight,
                "Next",
                widgetAddDialog_handleNext,
                true,
                true,
                null,
                null,
                null,
                "ahn-btn-next"
            );

    // Set selector divs to the same height of the tallest one
    if (up.feeds.length > 1) {
        var tallestDiv = 0;
        $(".ahn-widget-edit-feed-list .ahn-selector").each(function () {
            if ($(this).height() > tallestDiv) tallestDiv = $(this).height();
        });
        $(".ahn-widget-edit-feed-list .ahn-selector").height(tallestDiv);
    }

    $(".ahn-widget-edit-feed-list .ahn-selected").removeClass("ahn-selected").click();
}

function widgetAddDialog_handleNext() {
    var $propertiesWindow = $(".ahn-widget-edit-properties-dialog");
    var up = $propertiesWindow.data("upData");
    var $selectedWidgetFeed = null;
    var IsMsgBoard = false;
    var IsClassifieds = false;

    if ($(".ahn-selected").length == 1) {
        var widgetFeedIdx = $(".ahn-selected").data("feedidx");

        if (up.feeds[widgetFeedIdx].key == 3) {
            IsClassifieds = true
        };

        if (up.feeds[widgetFeedIdx].key == 32) {
            IsMsgBoard = true
        };

        if (up.feeds[widgetFeedIdx].key == $(".ahn-selected").data("feedid")) {
            $propertiesWindow.queue(function (next) {
                $propertiesWindow.height($propertiesWindow.outerHeight() + 20);
                $selectedWidgetFeed = $(".ahn-selected").clone().data("feedidx", widgetFeedIdx).addClass("ahn-widget-feed-selected").css({ position: "absolute", top: $(".ahn-selected").position().top, left: $(".ahn-selected").position().left }).appendTo($propertiesWindow);
                next();
            }).queue(function (next) {
                $propertiesWindow.children(":not(.ahn-selected)").fadeOut().remove();
                next();
            }).queue(function (next) {
                var currentLeft = $selectedWidgetFeed.position().left;
                if (currentLeft < 20) currentLeft = 150;
                $selectedWidgetFeed.animate({ left: 14, top: 7 }, currentLeft * 1.55, next);
            }).queue(function (next) {
                $selectedWidgetFeed.removeClass("ahn-selected").css({ position: "static", "float": "left" });
                next();
            }).queue(function (next) {
                $("<div />")
                            .css({ "border-left": "1px solid #666", "margin-left": "2px", "float": "left", height: $propertiesWindow.height(), display: "none", "padding-left": "25px", width: "465px" })
                            .append(widgetProperties_html({
                                "editTitle": up.feeds[widgetFeedIdx].editTitle,
                                "title": up.feeds[widgetFeedIdx].value,
                                "favoriteFeedId": up.feeds[widgetFeedIdx].favoriteFeedId,
                                "favoriteSelected": false,
                                "IsMsgBoard": up.feeds[widgetFeedIdx].IsMsgBoard,
                                "IsAdhocMsg": up.feeds[widgetFeedIdx].IsAdhocMsg,
                                "AdhocMsgType":up.feeds[widgetFeedIdx].IsAdhocMsgType,
                                "IsPhotoAlbum": up.feeds[widgetFeedIdx].IsPhotoAlbum,
                                "HotRepliesSelected": false,
                                "IsClassifieds": up.feeds[widgetFeedIdx].IsClassifieds,
                                "premiumSelected": false,
                                "categorySelect": up.feeds[widgetFeedIdx].categorySelect,
                                "categoryOptions": up.feeds[widgetFeedIdx].categoryOptions,
                                "editTop": up.feeds[widgetFeedIdx].editTop,
                                "topOptions": up.topOptions,
                                "topValue": 10,
                                "widgetStyles": up.feeds[widgetFeedIdx].widgetStyles,
                                "editUsername": up.feeds[widgetFeedIdx].editUsername,
                                "currentUsername": up.feeds[widgetFeedIdx].currentUsername,
                                "sortOptions": up.feeds[widgetFeedIdx].sortOptions
                            }))
                            .appendTo($propertiesWindow)
                            .fadeIn(200);

                // Set selector divs to the same height of the tallest one
                if (up.feeds[widgetFeedIdx].widgetStyles.length > 0) {
                    var tallestDiv = 0;
                    $(".ahn-widget-edit-feed-list .ahn-selector").each(function () {
                        if ($(this).height() > tallestDiv) tallestDiv = $(this).height();
                    });
                    $(".ahn-widget-edit-feed-list .ahn-selector").height(tallestDiv);
                }
                next();
            });
        }

        $(".ui-dialog-buttonset .ahn-btn-next").blur().removeClass("ahn-btn-next").addClass("positive").text("Apply").unbind("click").click(widgetAddApply_handleClick);
        return false;
    }
    else {
        $propertiesWindow.find(".ahn-dialog-message").remove();
        $propertiesWindow.append("<div class=\"ahn-dialog-message\" style=\"margin-top: 8px; text-align: center; \"><strong>Please choose a widget before continuing.</strong></div>");
        return false;
    }
}

function widgetSelection_handleClick(event) {
    var $propertiesWindow = $(this).parents(".ahn-widget-edit-properties-dialog");

    if (!$(this).hasClass("ahn-selected")) {
        $(this).parent().find(".ahn-selected").removeClass("ahn-selected");
        $(this).addClass("ahn-selected");
        $propertiesWindow.find(".ahn-dialog-message").remove();
    }
}

function setCheckAll() {
    $("#category-checkbox-check-all").attr("checked", $("#ahn-widget-category-multiselect-edit-option input").isAllChecked());
}


function widgetProperties_html(widgetData) {
    /* widgetData
    - editTitle
    - title
    - favoriteFeedId
    - favoriteSelected
    - categorySelect
    - categoryOptions
    - currentCategories
    - editTop
    - topOptions
    - key
    - value
    - topValue
    - widgetStyles
    - key
    - value
    - icon
    - selected
    - editUsername
    - currentUsername
    - sortOptions
    - currentSort -- holds current value
    - IsMsgBoard 
    - HotRepliesSelected
    - IsAdhocMsg
    - AdhocMsgType
    - AdhocMsgText
    */
    var $widgetProperties = $("<div />");

    if (widgetData.editTitle) {
        $("<div />")
                    .append("<div class=\"ahn-form-label\">Widget Title:</div><div class=\"ahn-form-field\"><input type=\"text\" id=\"ahn-widget-edit-title\" name=\"title\" value=\"" + widgetData.title + "\" /></div>")
                    .appendTo($widgetProperties);
    }

    if (widgetData.editUsername) {
        $("<div />")
                    .append("<div class=\"ahn-form-label\">Username:</div><div class=\"ahn-form-field\"><input type=\"text\" id=\"ahn-widget-edit-username\" name=\"title\" value=\"" + widgetData.currentUsername + "\" /></div>")
                    .appendTo($widgetProperties);
    }

    if (widgetData.favoriteFeedId > 0) {
        $("<div />")
                    .append("<div class=\"ahn-form-label\">Favorites Only:</div><div class=\"ahn-form-field\"><input type=\"checkbox\" id=\"ahn-widget-edit-favorite-edit-checkbox\" value=\"" + widgetData.favoriteFeedId + "\" " + (widgetData.favoriteSelected ? "checked" : "") + " /></div>")
                    .appendTo($widgetProperties);
    }

    if (widgetData.IsClassifieds) {
        $("<div />")
                    .append("<div class=\"ahn-form-label\">Premium Only:</div><div class=\"ahn-form-field\"><input type=\"checkbox\" name=\"premium\" id=\"ahn-widget-premium-checkbox\" value=\"" + widgetData.premiumSelected + "\" " + (widgetData.premiumSelected ? "checked" : "") + " /></div>")
                    .appendTo($widgetProperties);
    }

    if (widgetData.editTop) {
        var $editTop = $("<div />");

        $("<div />")
                    .addClass("ahn-form-label")
                    .html("Top # of Items:")
                    .appendTo($editTop);

        var $topList = $("<select />")
                    .attr("id", "ahn-widget-edit-top-edit-option")
                    .css("width", "60px");
        $.each(widgetData.topOptions, function (i, topOption) {
            $topList.append(
                    $("<option />")
                        .attr("value", topOption.key)
                        .text(topOption.value)
                    );
        });

        $topList.find("option[value=" + widgetData.topValue + "]").attr("selected", "true");

        $("<div />")
                    .addClass("ahn-form-field")
                    .append($topList)
                    .appendTo($editTop);

        $editTop.appendTo($widgetProperties);
    }

    if (widgetData.IsAdhocMsg) {
        //*** set the radio buttons for checked ***
        var IsChecked = [0, 1, 2, 3];
        var MsgText = [];
        var MsgTypeSelection = widgetData.AdhocMsgType - 1

        var msggroup = widgetData.AdhocMsgGroup
        IsChecked[0] = "";
        IsChecked[MsgTypeSelection] = "checked=\"checked\"";
        
        var $adHocMsg = $("<div />")
            .append("<div class=\"ahn-form-label\">Messages:</div><br />");

        var $adHocMsgListBox = $("<div class=\"ahn-messages-list-box\"></div>");

        var $adHocMsgList = $("<ul id=\"ahn-messages-list\" group=\""+msggroup+"\"></ul>")
            .sortable();

        if (widgetData.AdhocMsgText != null) {
            MsgText = widgetData.AdhocMsgText.split("|");

            for (var x = 0; x < MsgText.length; x++) {
                $("<li />")
                    .append(
                        $("<a href=\"javascript:void(0);\">delete</a>")
                            .click(function () { $(this).parent().remove(); })
                    )
                    .append("<span>" + MsgText[x] + "</span>")
                    .css({ "cursor": "pointer" })
                    .hover(function () { $(this).css("background", "#ccc"); }, function () { $(this).css("background", "none"); })
                    .appendTo($adHocMsgList);
            };
        };

        $adHocMsgList.appendTo($adHocMsgListBox);

        $adHocMsgListBox.appendTo($adHocMsg);

        var $inputControls = $("<div />")
            .append("<input type=\"text\" name=\"txtAdhocMessage\" id=\"txtAdhocMessage\" maxlength=\"87\" class=\"ahn-message-text-box\" />");
          
          $("<input type=\"button\" name=\"btnAddMessage\" id=\"btnAddMessage\" value=\"Add\" class=\"ahn-message-button\" />")
            .click(function () {
                AddAdHocTextMessage($("#txtAdhocMessage").val());
                $("#txtAdhocMessage").val("");
            })
            .appendTo($inputControls);

            var $adHocMsgRadioBtns = $(
                "<br/><br/><input type=\"radio\" name=\"grp1\" class=\"ahn-radio-ticker\" value=\"1\" " + IsChecked[0] + "/> Slide Up-Down " +
                "&nbsp;<input type=\"radio\" name=\"grp1\" class=\"ahn-radio-ticker\" value=\"2\"  " + IsChecked[1] + " /> Fade In-Out" +
                "&nbsp<input type=\"radio\" name=\"grp1\" class=\"ahn-radio-ticker\" value=\"3\" " + IsChecked[2] + "/> Fade-out" +
                "&nbsp<input type=\"radio\" name=\"grp1\" class=\"ahn-radio-ticker\" value=\"4\" " + IsChecked[3] + " /> Ticker " +
                "<br />"
            ).appendTo($inputControls);



        $inputControls.appendTo($adHocMsg);
        $adHocMsg.appendTo($widgetProperties);
    }

    if (widgetData.IsMsgBoard) {
        $("<div />")
                    .append("<div class=\"ahn-form-label\">Hot Topics:</div><div class=\"ahn-form-field\"><input type=\"checkbox\" name=\"hot_replies\" id=\"ahn-widget-hot-replies-checkbox\" value=\"" + widgetData.HotRepliesSelected + "\" " + (widgetData.HotRepliesSelected ? "checked" : "") + " /></div>")
                    .appendTo($widgetProperties);
    }

    if (widgetData.sortOptions.length > 1) {
        var $editSort = $("<div />");

        $("<div />")
                    .addClass("ahn-form-label")
                    .html("Sort By:")
                    .appendTo($editSort);

        var $sortList = $("<select />")
                    .attr("id", "ahn-widget-edit-sort-option")
                    .css("width", "206px");
        $.each(widgetData.sortOptions, function (i, sortOption) {
            $sortList.append(
                    $("<option />")
                        .attr("value", sortOption.key)
                        .text(sortOption.value)
                    );
        });

        //Get the sort value
        if (widgetData.sortValue != '')
            $sortList.find("option[value=" + widgetData.sortValue + "]").attr("selected", "true");
        else
            $sortList.find("option[value='views DESC']").attr("selected", "true");

        $("<div />")
                    .addClass("ahn-form-field")
                    .append($sortList)
                    .appendTo($editSort);

        $editSort.appendTo($widgetProperties);
    }
//------------- category select -------------------------
    if (widgetData.categoryOptions.length > 0) {

        var $singleCategoryLabel = "Category:";
        if (widgetData.IsPhotoAlbum) {
            $singleCategoryLabel = "Album:";
        }

        var $categorySelect = $("<div />");

        if (widgetData.categorySelect.toLowerCase() == 'multi') {
            var $categoryList = $("<div />")
                        .attr("id", "ahn-widget-category-multiselect-edit-option");

            $.each(widgetData.categoryOptions, function (i, categoryOption) {
                $categoryList.append(
                        $("<input />")
                            .attr("type", "checkbox")
                            .attr("value", categoryOption.id)
                            .attr("id", "category-checkbox-" + categoryOption.id)
                            .attr('checked', function () {
                                if (String("," + widgetData.currentCategories + ",").indexOf("," + categoryOption.id + ",") != -1 || widgetData.currentCategories == '') {
                                    return true
                                }
                                else return false;
                            })
                            .click(setCheckAll)
                            .css({ "border": "none", "padding-bottom": "4px" }),
                        $("<label />")
                            .attr("for", "category-checkbox-" + categoryOption.id)
                            .html(categoryOption.title),
                        $("<br />")
                );
            });

            $("<div />")
                    .css({ "float": "left" })
                    .html("Categories:")
                    .addClass("ahn-form-label")
                    .prependTo($categorySelect);

            var $checkAll = $("<div />")
                    .css({ "display": "inline-block", "width": "200px", "padding": "2px 0 0 4px", "font-weight": "800" }
            );

            $checkAll.append(
                $("<input />")
                    .attr("type", "checkbox")
                    .attr("value", "Select All")
                    .attr("id", "category-checkbox-check-all")
                    .attr("checked", $categoryList.children("input").isAllChecked())
                    .click(function () {
                        $("#ahn-widget-category-multiselect-edit-option input").attr("checked", $(this).is(":checked"));
                    })
                    .css({ "border": "none", "padding-bottom": "4px" }),
                $("<label />")
                    .attr("for", "category-checkbox-check-all")
                    .html("CHECK ALL"),
                $("<br />")
            );

            $("<div />")
                .addClass("ahn-form-field")
                .append($checkAll)
                .append($categoryList)
                .appendTo($categorySelect);

        }
        else if (widgetData.categorySelect.toLowerCase() == 'single') {
            $("<div />")
                        .css({ "float": "left" })
                        .html($singleCategoryLabel)
                        .addClass("ahn-form-label")
                        .prependTo($categorySelect);

            var $categoryList = $("<div />");
            var $selectList = $("<select />")
                    .attr('id', 'ahn-widget-category-select-list')
                    .addClass("ahn-form-field");
            $.each(widgetData.categoryOptions, function (i, categoryOption) {
                $selectList.append("<option value='" + categoryOption.id + "'>" + categoryOption.title + "</option>");
            });
            $selectList.val(widgetData.currentCategories);
            $selectList.prependTo($categorySelect);
        }

        $categorySelect.appendTo($widgetProperties);
    }
//------------- end category select -------------------------

    if (widgetData.IsPhotoAlbum) {
        var $animationSpeed = $("<div />");

        $("<div />")
                        .css({ "float": "left" })
                        .html("Picture Speed:")
                        .addClass("ahn-form-label")
                        .appendTo($animationSpeed);

        var $speedList = $("<div />");
        var $selectList = $("<select />")
                    .attr('id', 'ahn-widget-animation-speed-select-list')
                    .addClass("ahn-form-field");

        $selectList.append("<option value='6000'>Slow</option>");
        $selectList.append("<option value='4000'>Medium</option>");
        $selectList.append("<option value='2000'>Fast</option>");
        $selectList.val(widgetData.animationSpeed);
        $selectList.prependTo($animationSpeed);

        $animationSpeed.appendTo($widgetProperties);
    }



    if (widgetData.widgetStyles && widgetData.widgetStyles.length > 0) {
        var $editStyle = $("<div />").css({ "margin-top": "20px", "clear": "left" });
        var $styleContainer = $("<div />").addClass("ahn-widget-edit-style-container");
        var $styleList = $("<div />").addClass("ahn-widget-edit-feed-list");

        $.each(widgetData.widgetStyles, function (i, widgetStyle) {
            $styleList.append(
                        $("<div />")
                            .addClass("ahn-selector")
                            .addClass((widgetStyle.selected ? "ahn-selected" : ""))
                            .data("widgetid", widgetStyle.key)
                            .data("widgetidx", i)
                            .data("size", widgetStyle.size)
                            .html("<img src=\"" + (widgetStyle.icon || "nopic.png") + "\" width=\"40\" height=\"40\" border=\"0\" alt=\"" + widgetStyle.value + "\" /><br />" + widgetStyle.value)
                            .click(widgetSelection_handleClick)
                    );
        });
        $styleList.append(
                    $("<div />").addClass("clear")
                );

        $("<div />").addClass("ahn-form-label").html("Widget Style:").appendTo($editStyle);
        $styleList.appendTo($styleContainer);
        $styleContainer.appendTo($editStyle);

        if ($styleContainer.find(".ahn-selected").length == 0) $styleContainer.find(".ahn-selector:first").addClass("ahn-selected");

        $editStyle.appendTo($widgetProperties);
    }

    return $widgetProperties;
}

function AddAdHocTextMessage(msgText) {
    if (msgText.length > 0) {
        $("<li />")
                        .append(
                            $("<a href=\"javascript:void(0);\">delete</a>")
                                .click(function () { $(this).parent().remove(); })
                        )
                        //.append(msgText.replace("|", ""))
                        .append("<span>" + msgText.replace("|", "") + "</span>")
                        .css({ "cursor": "pointer" })
                        .hover(function () { $(this).css("background", "#ccc"); }, function () { $(this).css("background", "none"); })
                        .appendTo($("#ahn-messages-list"));
    }
}

function widgetAddApply_handleClick(event) {
    var $propertiesWindow = $(".ahn-widget-edit-properties-dialog");
    var up = $propertiesWindow.data("upData");

    var pageFeaturePageName = $(".ahn-wrapper").attr("data-page-name");
    var pageElementTitle = ($propertiesWindow.find("#ahn-widget-edit-title").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-title").val() : null);
    var pageElementTop = ($propertiesWindow.find("#ahn-widget-edit-top-edit-option").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-top-edit-option").val() : null);
    var pageElementSort = ($propertiesWindow.find("#ahn-widget-edit-sort-option").length == 1 ? $propertiesWindow.find("#ahn-widget-edit-sort-option").val() : null);
    var pageElementAdhocMsgCnt = ($propertiesWindow.find("#ahn-messages-list li").length);
    var pageElementAdHocMsgType = ($propertiesWindow.find("input:radio[name=grp1]:checked").val());


    //------------- category multiselect -------------------------
    var pageElementCategoryId = "";

    if ($propertiesWindow.find("#ahn-widget-category-multiselect-edit-option").length) {
        //get checked values
        $("#ahn-widget-category-multiselect-edit-option > input").each(function (i) {
            if ($(this).is(':checked')) pageElementCategoryId += $(this).val() + ",";
        });
        if (pageElementCategoryId != "") pageElementCategoryId = pageElementCategoryId.substring(0, pageElementCategoryId.length - 1);  //remove trailing comma
    }
    else if ($propertiesWindow.find("#ahn-widget-category-select-list").length) {
        //get selected value
        pageElementCategoryId = $("#ahn-widget-category-select-list").val();
    }
    //------------- end category multiselect ---------------------

    var pageElementFeedId = null;
    if ($propertiesWindow.find(".ahn-widget-feed-selected").data("feedidx") != null) {
        pageElementFeedId = up.feeds[$propertiesWindow.find(".ahn-widget-feed-selected").data("feedidx")].key;
    }
    if ($propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").length > 0) {
        if ($propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").is(":checked")) {
            if ($propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").val()) {
                pageElementFeedId = $propertiesWindow.find("#ahn-widget-edit-favorite-edit-checkbox").val();
            }
        }
    }
    var pageElementWidgetId = null;
    if ($propertiesWindow.find(".ahn-widget-edit-style-container .ahn-selected").length == 1) {
        pageElementWidgetId = $propertiesWindow.find(".ahn-widget-edit-style-container .ahn-selected").data("widgetid");
    }
    var pageElementUsername = null;
    if ($propertiesWindow.find("#ahn-widget-edit-username").length > 0) {
        pageElementUsername = $propertiesWindow.find("##ahn-widget-edit-username").val();
    }
    var pageElementHotReplies = false;
    if ($propertiesWindow.find("#ahn-widget-hot-replies-checkbox").length > 0) {
        if ($propertiesWindow.find("#ahn-widget-hot-replies-checkbox").is(":checked")) {
            pageElementHotReplies = true;
        }
    }
    var pageElementPremium = false;
    if ($propertiesWindow.find("#ahn-widget-premium-checkbox").length > 0) {
        if ($propertiesWindow.find("#ahn-widget-premium-checkbox").is(":checked")) {
            pageElementPremium = true;
        }
    }

    //input for adhoc message data
    var pageElementAdhocMsg = null;
    if (pageElementAdhocMsgCnt > 0) {
        var optionTexts = [];
        $("#ahn-messages-list li span").each(function () {
            optionTexts.push($(this).text())
        });

        pageElementAdhocMsg =   optionTexts.join("|") ;
    }

    //animation speed
    var pageElementAnimationSpeed = "";
    if ($propertiesWindow.find("#ahn-widget-animation-speed-select-list").length) {
        //get selected value
        pageElementAnimationSpeed = $("#ahn-widget-animation-speed-select-list").val();
    }

    var jsonData = "&feedid=" + pageElementFeedId;
    if (pageFeaturePageName) jsonData += "&pageName=" + escape(pageFeaturePageName);
    if (pageElementTitle) jsonData += "&title=" + escape(pageElementTitle);
    if (pageElementTop) jsonData += "&top=" + pageElementTop;
    if (pageElementSort) jsonData += "&sort=" + escape(pageElementSort);
    if (pageElementCategoryId != "") jsonData += "&categoryId=" + pageElementCategoryId;
    if (pageElementWidgetId) jsonData += "&widgetid=" + pageElementWidgetId;
    if (pageElementUsername) jsonData += "&source=" + pageElementUsername;
    if (pageElementHotReplies) jsonData += "&hot_replies=" + pageElementHotReplies;
    if (pageElementPremium) jsonData += "&premium=" + pageElementPremium;
    if (pageElementAdhocMsg) jsonData += "&txtMessages=" + pageElementAdhocMsg;
    if (pageElementAdhocMsg) jsonData += "&adhocMsgType=" + pageElementAdHocMsgType
    if (pageElementAnimationSpeed) jsonData += "&animationSpeed=" + pageElementAnimationSpeed;

    $.ajax({
        url: "widget_svc.asp",
        data: "action=addwidget" + jsonData,
        dataType: "html",
        type: "GET",
        success: function (data) {
            widgetHtml = data;
            if (widgetHtml) {
                var $newWidget = $(widgetHtml).css("float", "left");
                $newWidget.appendTo($(".ahn-container"));
                initWidgetInteractions($newWidget);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
        }
    });

    $("#modal-dialog").dialog("close");
}

function ApplyGalleryView(galleryId, borderColor, animationSpeed) {

    $("#" + galleryId).galleryView({
                panel_width: 525,
                panel_height: 395,
                frame_width: 50,
                frame_height: 50,
                transition_interval: animationSpeed,
                overlay_text_color: '#C0C0C0',
                fade_panels: false,
                background_color: borderColor,
                border: '3px solid ' + borderColor
            });
}

function initWidgetInteractions($widget) {
    adjustRows();
    buildHandle($widget);
    widgetHandle_adjustForNewContent();
    favoriteIcon_init($widget);
    init_freeTextEditor();
    init_change_whatsnew_widget();
    init_user_profile_widget();
}


//***************************************************//
//   Jquery for ahn user-profile 04/13/2011
//**************************************************//
$(function () {
    init_user_profile_widget();
})

function init_user_profile_widget() {
    // Remove current binding
    $(".ahn-user-profile-box A.ahn-user-profile-link").unbind("click");

    $(".ahn-user-profile-box A.ahn-user-profile-link").click(function () {
        var pgElement = $(this).parents(".ahn-widget").attr("pgElement");

        $.ajax({
            url: "widget_svc.asp",
            data: "action=userswap&pageElement=" + pgElement,
            dataType: "html",
            type: "GET",
            context: this,
            success: function (data) {
                widgetHtml = data;
                if (widgetHtml) {
                    $(this).parents(".ahn-widget-content").html(widgetHtml);
                    init_user_profile_widget();
                } // end check for null data
            }, //end success
            error: function (xhr, ajaxOptions, thrownError) {
                var errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
                $(this).parents(".ahn-user-profile-box").find(".ajax-message").html(errorMsg);
            } // end error

        }); //end ajax

    });
}

//***************************************************//
//   Jquery for ahn What's New 04/14/2011
//**************************************************//
$(function () {
    init_change_whatsnew_widget();
})

function init_change_whatsnew_widget() {
    // Remove current binding
    $(".ahn-whats-new-box .ahn-whats-new-button, .ahn-whats-new-box A.ahn-whats-new-last-visit-link").unbind("click");

    $(".ahn-whats-new-box .ahn-whats-new-button, .ahn-whats-new-box A.ahn-whats-new-last-visit-link").click(function () {
        //Init variables
        var pgElement = $(this).parents(".ahn-widget").attr("pgElement");
        var lastdays = 0; // $(this).parent().find("input[type=text]").val();
        var bLastDays = false;

        //Which element was clicked
        bIsButton = $(this).hasClass("ahn-whats-new-button")
        if (bIsButton) {
            lastdays =  $(this).parent().find("input[type=text]").val();
            bLastDays = true;
        }

        // Run Ajax
        $.ajax({
            url: "widget_svc.asp",
            data: "action=whatsnew&pageElement=" + pgElement + "&lastdays=" + lastdays + "&bLastDays=" + bLastDays,
            type: "GET",
            context: this,
            success: function (data) {
                widgetHtml = data;
                if (widgetHtml) {
                    $(this).parents(".ahn-widget-content").html(widgetHtml);
                    init_change_whatsnew_widget();
                } // end check for null data
            }, //end success
            error: function (xhr, ajaxOptions, thrownError) {
                var errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
                $(this).parents(".ahn-whats-new-box").find(".bottom-box").append("<br />" + errorMsg);
            } // end error

        }); //end ajax
    });
}

/* 
Free-Text Widget Editor
=========================
Description:          Allow community administrators to edit free text widgets
Base CSS Class:       ahn-feature-text-edit
Author:               George Edwards
Date Created:         4/14/2011
*/
$(function () {
    init_freeTextEditor();
});

function init_freeTextEditor() {
    $(".WideTextAreaWidget").disableSelection();

    // Remove current binding 
    $(".WideTextAreaWidget A.ahn-feature-text-edit").unbind("click");
    $(".WideTextAreaWidget").unbind("dblclick");

    $(".WideTextAreaWidget A.ahn-feature-text-edit").click(function (event) {
        var $widget = $(this).parents(".ahn-widget");

        // Prevent the link from doing its normal function
        event.preventDefault();

        widgetTextEditDialog_handleOpen($widget, $(this));
    });

    $(".WideTextAreaWidget[click=True]").dblclick(function (event) {

        var $widget = $(this).parents(".ahn-widget");
        widgetTextEditDialog_handleOpen($widget, $(this));
    });
}

function widgetTextEditDialog_handleOpen($widget, $context) {
    adjustRowsOnResizeDisable();

    var pgElementId = $widget.attr("pgElement");
    // Open a dialog box using the an AJAX Text Editor
    $.ajax({
        url: "feature_text_svc.asp",
        data: "pgElementId=" + pgElementId,
        dataType: "html",
        type: "GET",
        context: $context,
        success: function (data) {
            var $textEditor = $("<div />", { css: { "text-align": "left" }, html: data }).addClass("ahn-rte-modal");
            modal_dialog(
                            "Edit Text",
                            $textEditor,
                            600,
                            300,
                            "Apply",
                            widgetTextEditApply_handleClick,
                            true,
                            true,
                            null,
                            null,
                            adjustRowsOnResize,
                            null
                        );

            $(".ui-dialog-buttonset .positive").data("ref", $widget);

            // This is a requirement for Firefox to load the RTE correctly.
            $textEditor.delay(500).queue(function (next) {
                if ($(".ahn-rte-modal IMG[title=Bold]").length < 1) $(".ahn-rte-modal > IMG").load();
                next();
            });


        },
        error: function (xhr, ajaxOptions, thrownError) {
            var errorMsg = "Error: Unable to complete the request (" + xhr.statusText + ").";
            if ($(this).hasClass("ahn-feature-text-edit"))
                $(this).ahnTooltip({ contents: errorMsg }).delay(2000).queue(function (next) { $(this).ahnTooltip("destroy"); next(); });
            else
                $("<div />", { html: errorMsg })
                        .addClass("ahn-error-msg")
                        .prependTo($widget.find(".ahn-widget-content"))
                        .delay(2000).fadeOut("slow").queue(function () { $(this).remove(); });
        }
    });
}

function widgetTextEditApply_handleClick() {
    var $widget = $(".ui-dialog-buttonset .positive").data("ref");
    var pgElementId = $widget.attr("pgElement");
    var richTextEditor = $("#CE_Editor1_ID")[0];
    var contentHTML = richTextEditor.getHTML();

    $.ajax({
        url: "widget_svc.asp",
        data: "action=updatetext&pageElement=" + pgElementId + "&textHTML=" + encodeURIComponent(contentHTML),
        dataType: "html",
        type: "POST",
        context: this,
        success: function (data) {
            // Update the text
            $widget.find(".ahn-widget-content").html(data);

            // Adjust all of the widget handles for this new content
            widgetHandle_adjustForNewContent();

            // Build the click and double-click events again
            init_freeTextEditor();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            $("<div />", { html: "Error: Unable to complete the request (" + xhr.statusText + ")." })
                        .addClass("ahn-error-msg")
                        .prependTo($widget.find(".ahn-widget-content"))
                        .delay(2000).fadeOut("slow").queue(function () { $(this).remove(); });
        }
    });
}

function AdhocMsgTransistions() {
    var $txtMsgWindow = $(".ahn-text-rotator");
}

//*********** Marquee message funtions ********************
//*********************************************************
$(document).ready(function () {
    //StartAnims();
    // Global elements array to hold the li widget animations.
    var nElements = []
});


function StartAnims(msgID) {
    // $(".ahn-ticker li").hide();
    $(".ahn-ticker li").css({ "left": "-35px" });
    nElements = $("#" + msgID + " li:first")
    InOut(nElements, msgID)
}

//***** The main loop engine for the widget marquee animations
function InOut(elem, msgID) {

    var y = $("#" + msgID + "").attr("msgType");
    var NodeList = $("#" + msgID + "").attr("NodeList");

    if (y == 1) {
        elem.slideDown(1500)
            .delay(4000)
            .slideUp(1500, function () {
                if (NodeList > 1) {
                    if (elem.next().length > 0) {
                        InOut(elem.next(), msgID);
                    } else {
                        InOut(elem.siblings(':first'), msgID);
                    };
                } else {
                    InOut(elem, msgID);
                };
            }).delay(2000);

    } else if (y == 2) {

        elem.fadeIn(1000)
            .delay(4000)
            .fadeOut(1500, function () {

                if (NodeList > 1) {
                    if (elem.next().length > 0) {
                        InOut(elem.next(), msgID);
                    } else {
                        InOut(elem.siblings(':first'), msgID);
                    };
                } else {
                    InOut(elem, msgID);
                };
            });
    } else if (y == 3) {

        elem.show()
            .delay(3000)
            .fadeTo(4000, .0, function () {
                elem.hide();
                elem.css({ "filter": "alpha(opacity=100)" });

                elem.css({ 'opacity': 1 });

                if (NodeList > 1) {
                    if (elem.next().length > 0) {
                        InOut(elem.next(), msgID);
                    } else {
                        InOut(elem.siblings(':first'), msgID);
                    };
                } else {
                    InOut(elem, msgID);
                };
            });

    } else if (y == 4) {

        var ul_width = $(".ahn-ticker").width();
        var li_left = ($(".ahn-ticker").position.left)

        var startPos = ul_width + 40 //starting point position add for because it's a ul
        elem.show();
        elem.css({ "left": startPos + "px", "top": "5px" }).animate({ "left": "-35px" }, 3000);
        elem.delay(2000);
        elem.fadeTo(1000, .0, function () {

            if (NodeList > 1) {
                if (elem.next().length > 0) {
                    elem.hide();
                    elem.css({ "filter": "alpha(opacity=100)" });
                    elem.css({ 'opacity': 1 });
                    InOut(elem.next(), msgID);
                } else {
                    elem.hide();
                    elem.css({ "filter": "alpha(opacity=100)" });
                    elem.css({ 'opacity': 1 });
                    elem.css({ "filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)" })
                    InOut(elem.siblings(':first'), msgID);
                };
            } else {
                InOut(elem, msgID);
            };

        });
    };

};
//*********** END Marquee message funtions ****************
//*********************************************************


//*********** global delete button ************************//
function CheckForUndefined(strType) {
    if (typeof strType == 'undefined') {
        strType = "";
    };

    return strType;
}

$(document).ready(function () {

    // Global elements array to hold the li widget animations.
    $(".ahn-global-delete-btn").click(function (event) {
        //prevents submit from firing off
        event.preventDefault();
        var msg_id = $(".ahn-global-delete-btn").attr("id")
        var delmsg = CheckForUndefined($(".ahn-global-delete-btn").attr("delmsg"));
        var xLink = ""

        _gblDelete(true, msg_id, delmsg, xLink);
    });

    //Classifieds.asp has it's own delete link - oh fun!
    $("a").click(function (event) {
        var link_class = $(this).attr("class")
        
        //*** links can have a delete icon or no delete icon.
        if (link_class == "ahn-item-icon delete" || link_class == "ahn-item-no-icon del") {
            event.preventDefault();
            var msg_id = ""
            var delmsg = CheckForUndefined($(".ahn-global-delete-btn").attr("delmsg"));
            var xLink = this.href;

            _gblDelete(false, msg_id, delmsg, xLink);
        }; // End if Link_Class
    }); // End a click function

});

function _gblDelete(eleBtnType, msg_id, delmsg,  xLink) {

    var bIsButton = eleBtnType;
    var standard_height = 75;
    var btn_action = "Confirm Delete";
    var standard_btn_msg = "Are you sure you wish to delete?"
    var rec_count = -1

    //Get the value/text from the list box selection
    var eFormValue = $(".form-select").val();
    var IsSelected = $(".form-select option:selected").length
    var eformText = $(".form-select option:selected").text();
    var rec_count = 0;

    if (bIsButton && IsSelected !=0) {
        //Button 
        if (typeof $(".form-select option:selected").attr("cnt") != 'undefined') {
            rec_count = $(".form-select option:selected").attr("cnt");
        };

        if (msg_id != "") {
            standard_height = 150;
            if (delmsg == "") {
                standard_btn_msg = "WARNING! When you delete a category you will remove all records in the " + msg_id + " category.<br>" +
                                "Are you sure you wish to delete?"
            } else {
                standard_btn_msg = delmsg + "<BR>Are you sure you wish to delete?"
            }
        };

        var x = showDiaglogBox(btnDelete_Click, standard_height, rec_count, eformText, delmsg)

    } else {
        //Link
        standard_height = 75;
        var x = showDiaglogBox(linkDelete_Click, standard_height, rec_count, "", delmsg)
    };



    function showDiaglogBox(fnName, xHeight, xcount, cat_name, delmsg) {
            var $deleteDialog = $("<div />")
                        .addClass("ahn-widget-delete-dialog")
                        .html("<div style=\"text-align: center; \">" + standard_btn_msg + "</div><div style=\"font-size: 0.8em; text-align: center; \"><br /></div>")

            if (xcount > 0) {
                modal_dialog("Category Delete " + cat_name, "<div style=\"font-size: 0.8em; text-align: center; \">"+delmsg+"</div>", 350, 100, "OK", null, false);
            } else {
                modal_dialog(btn_action,$deleteDialog,350,xHeight,"Delete",fnName,true,true); //modal
            } // rec_count
            var strBackground = $(".ui-dialog").css("background-color")
            if (strBackground == "transparent") {
                $(".ui-dialog").css("background", "url(images/ui-bg_flat_75_ffffff_40x100.png) #ffffff repeat-x 50% 50%");
            }
        };

        function btnDelete_Click(event) {
            var val = $(".action_type").val("Delete");
            var name = $(".action_type").attr("name", "action");
            $("form").submit();
        };

        function linkDelete_Click(event) {
            document.location.href = xLink;
        };

};




