jQuery.noConflict();

var iCurrentRelativeFontSize = 0;

jQuery(document).ready(function () {
    readFontSize();
    //readDynBackChoice();

    // set up modal dialog for exiting the site
    jQuery('.jqmWindow_EXIT').jqm({ onShow: function (h) { h.w.fadeIn(); } });
    jQuery('.jqmWindow_EXIT').jqmAddTrigger(jQuery('a[rel="external"]'));
    jQuery('a[rel="external"]').click(function () {
        oExternalLinker = jQuery('div.jqmWindow_EXIT a.externalLinker');
        oExternalLinker.text(jQuery(this).attr('href'));
        oExternalLinker.attr('href', jQuery(this).attr('href'));
        return false;
    });

    // set up modal dialog for Feedback Form (will likely not be used)
    jQuery('.jqmWindow_FEEDBACK').jqm({ onShow: function (h) { h.w.fadeIn(); } });
    jQuery('.jqmWindow_FEEDBACK').jqmAddTrigger(jQuery('a[rel="feedback"]'));
    jQuery('a[rel="feedback"]').click(function () {
        return false;
    });

    // set up modal dialog for external URL Feedback Form (will likely not be used)
    jQuery('.jqmWindow_FEEDBACKEXTERNAL').jqm({ onShow: function (h) { h.w.fadeIn(); }, ajax: 'feedbackform.html' });
    jQuery('.jqmWindow_FEEDBACKEXTERNAL').jqmAddTrigger(jQuery('a[rel="feedbackexternal"]'));
    jQuery('a[rel="feedbackexternal"]').click(function () {
        return false;
    });

    // set up modal dialog for iFRAME external URL Feedback Form
    var loadInIframeModal = function (hash) {
        var trigger = jQuery(hash.t);
        var modal = jQuery(hash.w);
        var myUrl = trigger.attr('href');
        var modalContent = jQuery('#jqmContent');
        modalContent.attr('src', myUrl);
        modal.fadeIn();
    }
    jQuery('.jqmWindow_FEEDBACKIFRAME').jqm({
        trigger: 'a.feedbackiframe',
        target: '#jqmContent',
        onShow: loadInIframeModal
    });
    //jQuery('.jqmWindow_FEEDBACKIFRAME').jqmAddTrigger(jQuery('a.feedbackiframe'));
    jQuery('a.feedbackiframe').click(function () {
        return false;
    });
});





// ### TABLE STRIPING

// Initialize table row striping
// Adds the "alt" class to every odd TR
// Must pass in a CSS selector for the TBODY tag
function initializeTableStripe(sSelectorForTableBody) {
    jQuery(sSelectorForTableBody + ' tr:odd').addClass("alt");
}







// ### MyAE MSG BOX

// Initialize the click functionality for the blue msg box that can appear above the MyAE account and bookmark tabs
function initializeMyAEMsgBox() {
    jQuery('.myae_msgbox').css('cursor', 'pointer').click(function (event) {
        //event.preventDefault();
        jQuery(this).slideUp(500);
        jQuery(this).hide();
    });
}






// ### CALLOUT TABLE

// Initialize all functionality for Callout Tables
function initializeCalloutTable() {
    // turn off the dashed bottom border for the TDs in the last TR of each Callout Table
    jQuery('table.callouttable tr:last-child td').css('border-bottom', '0px');
}






// ### CALLOUT IMAGE

// Set the proper width for the Callout Image A container
function setCalloutImageSizeA(oThis, iWidth) {
    oContainer = oThis.closest('.calloutimageA');
    oContainer.width(iWidth + 2);
}

// Set the proper width for the Callout Image B container
function setCalloutImageSizeB(oThis, iWidth) {
    oContainer = oThis.closest('.calloutimageB');
    oContainer.width(iWidth);
}

// Initialize Callout Images
function initializeCalloutImage() {
    jQuery('.calloutimageA img.inset').load(function () {
        oThis = jQuery(this);
        setCalloutImageSizeA(oThis, this.width);
    });

    jQuery('.calloutimageB img.inset').load(function () {
        oThis = jQuery(this);
        setCalloutImageSizeB(oThis, this.width);
    });
}







function initializeBookmarkTogglers() {
    jQuery('.bookmarks_item').hover(function () {
        var oContent = jQuery(this).find('.bookmarks_item_content');
        if (oContent.is(':visible')) {
            jQuery(this).find('.bookmarks_item_buttons').show();
        }
    }, function () {
        jQuery(this).find('.bookmarks_item_buttons').hide();
    });

    jQuery('.bookmarks_item_buttons .editbutton').click(function (event) {
        event.preventDefault();
        var oButtons = jQuery(this).parent();
        var oItem = oButtons.parent();
        var oNoteButton = oItem.find('a.note');
        var oNoteContent = oItem.find('.notecontent');
        var oContent = oItem.find('.bookmarks_item_content');
        var oEdit = oItem.find('.bookmarks_item_edit');
        oContent.hide();
        oButtons.hide();
        oNoteButton.removeClass('on');
        oNoteContent.hide();
        oEdit.show();
    });

    jQuery('.bookmarks_item_text a.note').click(function (event) {
        event.preventDefault();
        var oButton = jQuery(this);
        var oContent = oButton.parent().find('.notecontent');
        if (oButton.hasClass('on')) {
            oButton.removeClass('on');
            oContent.hide();
        } else {
            oButton.addClass('on');
            oContent.show();
        }
    });

    jQuery('.bookmarks_item_text .notecontent').click(function (event) {
        event.preventDefault();
        var oContent = jQuery(this);
        var oButton = oContent.parent().find('a.note');
        oContent.hide();
        oButton.removeClass('on');

    });

    jQuery('.bookmarks_main a.addanotherlink').click(function (event) {
        event.preventDefault();
        //alert('add another still needs clarification');
        var oNewFolderFields = jQuery(this).parent().parent().parent().find('.newfolderfields');
        if (!oNewFolderFields.is(':visible')) {
            oNewFolderFields.show();
        }
    });

    jQuery('.bookmarks_main .suggestedtagsdata a').live('click', function (event) {
        event.preventDefault();
        var oTag = jQuery(this);
        var oTagData = oTag.parent();
        var sTagText = oTag.text();
        var oInput = oTagData.parent().parent().find('input.suggestedtagsinput');
        var sInputText = oInput.val();
        oInput.val(sInputText + ', ' + sTagText);
        oTag.remove();
        var sTagDataText = oTagData.html();
        sTagDataText = trimCommas(sTagDataText, true, true)
        oTagData.html(sTagDataText);
    });

    jQuery('.bookmarks_item .bookmarks_item_edit_table_buttons a.cancelbutton').click(function (event) {
        event.preventDefault();
        var oButton = jQuery(this);
        var oItem = oButton.closest('.bookmarks_item');
        var oNoteButton = oItem.find('a.note');
        var oNoteContent = oItem.find('.notecontent');
        var oContent = oItem.find('.bookmarks_item_content');
        var oEdit = oItem.find('.bookmarks_item_edit');
        oContent.show();
        //oButtons.hide();
        oEdit.hide();
    });

    jQuery('.bookmarks_header_buttons a.renamebutton').click(function (event) {
        event.preventDefault();
        var oFormDiv = jQuery(this).parent().parent().find('.bookmarks_header_form');
        if (oFormDiv.length > 0) {
            oFormDiv.toggle();
        }
    });

    jQuery('.bookmarks_header_form .bookmarks_item_edit_table_buttons a.cancelbutton').click(function (event) {
        event.preventDefault();
        var oFormDiv = jQuery(this).closest('.bookmarks_header_form');
        oFormDiv.hide();
    });

    jQuery('.bookmarks_nav_foot a.createfolderlink').click(function (event) {
        event.preventDefault();
        var oFormDiv = jQuery(this).parent().find('.bookmarks_nav_foot_createform');
        if (oFormDiv.length > 0) {
            oFormDiv.toggle();
        }
    });

    jQuery('.bookmarks_nav_foot .bookmarks_item_edit_table_buttons a.cancelbutton').click(function (event) {
        event.preventDefault();
        var oFormDiv = jQuery(this).closest('.bookmarks_nav_foot_createform');
        oFormDiv.hide();
    });
}

function initializeMyAEChip() {
    jQuery('.myaechip a.addanotherlink').click(function (event) {
        event.preventDefault();
        //alert('add another still needs clarification');
        var oNewFolderFields = jQuery(this).parent().parent().parent().find('.newfolderfields');
        if (!oNewFolderFields.is(':visible')) {
            oNewFolderFields.show();
        }
    });

    jQuery('.myaechip .suggestedtagsdata a').live('click', function (event) {
        event.preventDefault();
        var oTag = jQuery(this);
        var oTagData = oTag.parent();
        var sTagText = oTag.text();
        var oInput = oTagData.parent().parent().find('input.suggestedtagsinput');
        var sInputText = oInput.val();
        oInput.val(sInputText + ', ' + sTagText);
        oTag.remove();
        var sTagDataText = oTagData.html();
        sTagDataText = trimCommas(sTagDataText, true, true)
        oTagData.html(sTagDataText);
    });
}

function trimCommas(s, collapse, addspace) {
    s = s.replace(/[,\s]*,[,\s]*/g, ",").replace(/^,/, "").replace(/,$/, "");
    if (collapse) {
        s = s.replace(/[\s]+/, " ");
    }
    if (addspace) {
        s = s.replace(/,/g, ", ");
    }
    return s;
}





// ### POLL ROW SLIDING

// Global Poll Row Sliding variables 
var bTablePollsClickLock = false;

// Handles clicks on poll table rows
// Toggles the poll details in and out of view
function handleTablePollsRowClick(oThisRow) {
    if (!bTablePollsClickLock) {
        bTablePollsClickLock = true;

        oIconImg = oThisRow.find('td.icon img');
        sIconImgSrc = oIconImg.attr('src');

        oDetailsRow = oThisRow.next();

        if (oThisRow.hasClass('on')) {
            // turn off
            oThisRow.removeClass('on');
            oIconImg.attr('src', oIconImg.attr('src').replace('arrow_up_white.gif', 'arrow_down_blue.gif'));
            oDetailsRow.hide();
        }
        else {
            // turn on
            oThisRow.addClass('on');
            oIconImg.attr('src', oIconImg.attr('src').replace('arrow_down_blue.gif', 'arrow_up_white.gif'));
            oDetailsRow.show();
        }

        bTablePollsClickLock = false;
    }
}

// Initialize the poll row click system
function initializeTablePolls() {
    // special table row striping for poll tables
    jQuery('.searchResults table tbody tr:not(.details):odd').addClass("alt");

    // include mouse pointer icon only when javascript is enabled (since otherwise rows are not clickable
    jQuery('.searchResults table tbody tr:not(.details)').css('cursor', 'pointer');

    // click handler
    jQuery('.searchResults table tbody tr:not(.details)').click(function () {
        oThisRow = jQuery(this);
        handleTablePollsRowClick(oThisRow);
    });
}








// ### UTILITY TOOLS

// Global Utility Tools variables 
var iUtilityToolsSlideSpeed = 500;
var bUtilityToolsClickLock = false;

// Handles clicks on the Email button
function handleUtilityToolsEmailClickEvent(oThis, oEvent) {
    oEvent.preventDefault();
    handleUtilityToolsEmailClick(oThis);
}

// Does the real work of clicking the Email button
function handleUtilityToolsEmailClick(oThis) {
    if (!bUtilityToolsClickLock) {
        bUtilityToolsClickLock = true;

        oJThis = jQuery(oThis);

        oBoxEmail = jQuery('.utilitytools_email');
        oBoxPrint = jQuery('.utilitytools_print');
        oBoxShare = jQuery('.utilitytools_share');

        jQuery('.utilitytools_buttons a').removeClass('on');
        oBoxPrint.hide();
        oBoxShare.hide();

        if (oBoxEmail.is(':visible')) {
            //hide
            oBoxEmail.slideUp(iUtilityToolsSlideSpeed, function () {
                bUtilityToolsClickLock = false;
            });
        }
        else {
            //show
            /*
            oJThis.addClass('on');
            oBoxEmail.slideDown(iUtilityToolsSlideSpeed, function() {
            bUtilityToolsClickLock = false;
            });
            */
            bUtilityToolsClickLock = false;
        }
    }
}

// Opens the Email form content in a quick manner
// For use on page load when you want to show the Email form content immediately (such as for showing form validation errors)
function showUtilityToolsEmail() {
    jQuery('a.utilitytools_buttons_email').addClass('on');
    jQuery('.utilitytools_email').show();
}

// Handles clicks on the Print button
function handleUtilityToolsPrintClick(oThis, oEvent) {
    oEvent.preventDefault();

    if (!bUtilityToolsClickLock) {
        bUtilityToolsClickLock = true;

        oJThis = jQuery(oThis);

        oBoxEmail = jQuery('.utilitytools_email');
        oBoxPrint = jQuery('.utilitytools_print');
        oBoxShare = jQuery('.utilitytools_share');

        jQuery('.utilitytools_buttons a').removeClass('on');
        oBoxEmail.hide();
        oBoxShare.hide();

        if (oBoxPrint.is(':visible')) {
            //hide
            oBoxPrint.slideUp(iUtilityToolsSlideSpeed, function () {
                bUtilityToolsClickLock = false;
            });
        }
        else {
            //show
            oJThis.addClass('on');
            oBoxPrint.slideDown(iUtilityToolsSlideSpeed, function () {
                bUtilityToolsClickLock = false;
            });
        }
    }
}

// Handles clicks on the Share button
function handleUtilityToolsShareClick(oThis, oEvent) {
    oEvent.preventDefault();

    if (!bUtilityToolsClickLock) {
        bUtilityToolsClickLock = true;

        oJThis = jQuery(oThis);

        oBoxEmail = jQuery('.utilitytools_email');
        oBoxPrint = jQuery('.utilitytools_print');
        oBoxShare = jQuery('.utilitytools_share');

        jQuery('.utilitytools_buttons a').removeClass('on');
        oBoxEmail.hide();
        oBoxPrint.hide();

        if (oBoxShare.is(':visible')) {
            //hide
            oBoxShare.slideUp(iUtilityToolsSlideSpeed, function () {
                bUtilityToolsClickLock = false;
            });
        }
        else {
            //show
            oJThis.addClass('on');
            oBoxShare.slideDown(iUtilityToolsSlideSpeed, function () {
                bUtilityToolsClickLock = false;
            });
        }
    }
}

// Handles clicks on the top bar or X close link for any expanded content box
// Closes the content box
function handleUtilityToolsCloseClick(oThis, oEvent) {
    oEvent.preventDefault();

    if (!bUtilityToolsClickLock) {
        bUtilityToolsClickLock = true;

        oJThis = jQuery(oThis);
        oBoxToClose = oJThis.parent();

        jQuery('.utilitytools_buttons a').removeClass('on');

        oBoxToClose.slideUp(iUtilityToolsSlideSpeed, function () {
            bUtilityToolsClickLock = false;
        });
    }
}

// Handles clicks on any CANCEL button that might be included at the bottom of an expanded content box
// Closes the content box
function handleUtilityToolsCancelClick(oThis, oEvent) {
    oEvent.preventDefault();

    if (!bUtilityToolsClickLock) {
        bUtilityToolsClickLock = true;

        oJThis = jQuery(oThis);
        oBoxToClose = oJThis.closest('.utilitytools_content');

        jQuery('.utilitytools_buttons a').removeClass('on');

        oBoxToClose.slideUp(iUtilityToolsSlideSpeed, function () {
            bUtilityToolsClickLock = false;
        });
    }
}

// Handles clicks on either font size changer button
function handleUtilityToolsFontClick(oThis, oEvent, iFontChange) {
    oEvent.preventDefault();
    iCurrentRelativeFontSize = iCurrentRelativeFontSize + iFontChange;

    if (iCurrentRelativeFontSize < 0) {
        // font can't go lower than zero levels
        iCurrentRelativeFontSize = 0;
    }
    else if (iCurrentRelativeFontSize > 6) {
        // font can't go larger than six levels
        iCurrentRelativeFontSize = 6;
    }

    enactFontSize();
    saveFontSize();
}

// Accomplishes the real work of changing the font size by adding a font size (in pixels) to the document BODY tag
// All other font sizes in the document are derived as percentages based on the BODY's pixel font size
// This function should be called whenever the user clicks the font size changer buttons and also when the document loads (to enact any previously chosen font size)
function enactFontSize() {
    var aFontSizes = new Array('12px', '13px', '14px', '15px', '16px', '17px', '18px');
    var sFontSizeCssValue = aFontSizes[iCurrentRelativeFontSize];
    jQuery('body').css('font-size', sFontSizeCssValue);
    //jQuery('body').css('line-height', 1.334);
}

// Save the most recently chosen font size in a local cookie for reference each time the visitor loads a new page
function saveFontSize() {
    jQuery.cookie('aefontsize', iCurrentRelativeFontSize);
}

// Read the most recently chosen font size from a local cookie (if available) and enact the font size
// Normally called on page load
function readFontSize() {
    iCurrentRelativeFontSize = parseInt(jQuery.cookie('aefontsize'));
    if (isNaN(iCurrentRelativeFontSize)) {
        iCurrentRelativeFontSize = 0;
    }
    enactFontSize();
}

// Initialize all Utility Tool functionality
function initializeUtilityTools() {
    // Click handler for Email button
    jQuery('a.utilitytools_buttons_email').click(function (event) {
        handleUtilityToolsEmailClickEvent(this, event);
    });

    // Click handler for Print button
    jQuery('a.utilitytools_buttons_print').click(function (event) {
        handleUtilityToolsPrintClick(this, event);
    });

    // Click handler for Share button
    jQuery('a.utilitytools_buttons_share').click(function (event) {
        handleUtilityToolsShareClick(this, event);
    });

    // Click handler for expanded content box headers and X close buttons
    jQuery('div.utilitytools_content_head').click(function (event) {
        handleUtilityToolsCloseClick(this, event);
    });

    // Click handler for CANCEL buttons inside content boxes
    jQuery('img.utilitytools_content_cancel').click(function (event) {
        handleUtilityToolsCancelClick(this, event);
    });

    // Click handler for negative font size changer button
    jQuery('a.utilitytools_buttons_fontminus').click(function (event) {
        handleUtilityToolsFontClick(this, event, -1);
    });

    // Click handler for positive font size changer button
    jQuery('a.utilitytools_buttons_fontplus').click(function (event) {
        handleUtilityToolsFontClick(this, event, 1);
    });
}








// ### SEARCH FILTERS

// Global Search Filter variables 
var iFilterExpanderSlideSpeed = 500;

// Handles clicks on the Select All and Deselect All links for a filter group
// Forces all checkboxes in that group to either turn on or turn off
function handleFiltersSelectAllClick(oThis, oEvent, bSelectOrNot) {
    oEvent.preventDefault();
    oJThis = jQuery(oThis);
    oCheckboxes = oJThis.parent().parent().find('input:checkbox');
    oCheckboxes.attr('checked', bSelectOrNot);
}

// Handles clicks on the expander plus/minus link for a filter subgroup
// Toggles visibility of that subgroup
function handleFiltersExpanderClick(oThis, oEvent) {
    oEvent.preventDefault();
    oJThis = jQuery(oThis);
    sImgSrc = oJThis.attr('src');
    oExpanderBox = oJThis.parent().next();
    if (oExpanderBox.is(':visible')) {
        //hide
        oExpanderBox.slideUp(iFilterExpanderSlideSpeed);
        oJThis.attr('src', sImgSrc.replace('filters_minus.gif', 'filters_plus.gif'));
    }
    else {
        //show
        oExpanderBox.slideDown(iFilterExpanderSlideSpeed);
        oJThis.attr('src', sImgSrc.replace('filters_plus.gif', 'filters_minus.gif'));
    }
}

// Initialize all search form filter functionality
function initializeFilters() {
    // Click handler for the Select All links
    jQuery('.filters a.selectall').click(function (event) {
        handleFiltersSelectAllClick(this, event, true);
    });

    // Click handler for the Deselect All links
    jQuery('.filters a.deselectall').click(function (event) {
        handleFiltersSelectAllClick(this, event, false);
    });

    // Click handler for expander plus/minus links
    jQuery('.filters img.expandericon').click(function (event) {
        handleFiltersExpanderClick(this, event);
    });

    // Close all expandable subgroups unless the group has a special class on it at page load
    // You can use this special class to force subgroups to be open when the page loads
    jQuery('.filters div.expanderbox').not('.expanderbox_openatfirst').slideUp(iFilterExpanderSlideSpeed);
}








// ### CALENDAR WIDGET

// Global Calendar Widget variables 
var iTotalCalendarItems = 0;
var iCurrentCalendarItem = 1;

// Hide all calendar items
function calendarHideAll() {
    jQuery('.calendarcontentitem').hide();
}

// Turn on visibility for the current calendar item
function calendarTurnOnItem() {
    jQuery('#calendar' + iCurrentCalendarItem).fadeIn(500);
}

// Render the current state of the calendar
// Turn off all items (to ensure that the previous calendar item gets turned off) and then turn on just the current item
function calendarRenderItem() {
    calendarHideAll();
    calendarTurnOnItem();
}

// Handle clicks on the advance arrow button in the calendar widget
function calendarHandleAdvanceClick() {
    if (iCurrentCalendarItem < iTotalCalendarItems) {
        iCurrentCalendarItem = iCurrentCalendarItem + 1;
        if (iCurrentCalendarItem > iTotalCalendarItems) {
            iCurrentCalendarItem = 1;
        }
        calendarSetImages();
        calendarRenderItem();
    }
}

// Handle clicks on the previous arrow button in the calendar widget
function calendarHandlePreviousClick() {
    if (iCurrentCalendarItem > 1) {
        iCurrentCalendarItem = iCurrentCalendarItem - 1;
        if (iCurrentCalendarItem < 1) {
            iCurrentCalendarItem = 1;
        }
        calendarSetImages();
        calendarRenderItem();
    }
}

// Toggles style for the calendar advance arrow buttons to indicate whether you can advance further
function calendarSetAdvanceImage() {
    oImg = jQuery('#calendarAdvance');
    if (oImg.length !== 0) {
        if (iCurrentCalendarItem >= iTotalCalendarItems) {
            oImg.attr('src', oImg.attr('src').replace('forwardImage.png', 'graySpacer.png'));
        }
        else {
            oImg.attr('src', oImg.attr('src').replace('graySpacer.png', 'forwardImage.png'));
        }
    }
}

// Toggles style for the calendar previous arrow buttons to indicate whether you can retreat further
function calendarSetPreviousImage() {
    oImg = jQuery('#calendarPrevious');
    if (oImg.length !== 0) {
        if (iCurrentCalendarItem <= 1) {
            oImg.attr('src', oImg.attr('src').replace('backImage.png', 'graySpacer.png'));
        }
        else {
            oImg.attr('src', oImg.attr('src').replace('graySpacer.png', 'backImage.png'));
        }
    }
}

// Toggles style for both calendar arrow buttons
function calendarSetImages() {
    calendarSetAdvanceImage();
    calendarSetPreviousImage();
}

// Initialize all Calendar Widget functionality
function calendarInitialize() {
    // save the total count of available calendar items
    iTotalCalendarItems = jQuery('.calendarcontentitem').size();

    // click handler for the advance arrow button
    jQuery('#calendarAdvance').click(function () {
        calendarHandleAdvanceClick();
    });

    // click handler for the previous arrow button
    jQuery('#calendarPrevious').click(function () {
        calendarHandlePreviousClick();
    });

    // set the initial styles for both arrow buttons
    calendarSetImages();

    // show the first calendar item
    calendarRenderItem();
}






// ### DYNAMIC LEADS WIDGET

// Global Calendar Widget variables 
var iTotalDynamicLeadAreaItems = 0;
var iCurrentDynamicLeadAreaItem = 1;
var oDynamicLeadTimeOutInstance = null;
var iDynamicLeadRotationTimeInMS = 5000;
var iDynamicLeadRotationTimeAfterClickInMS = 12000;
var iDynamicLeadFadeTimeInMS = 400;

// Hide all Dynamic Lead items
function dynamicLeadAreaHideAll() {
    jQuery('.dynamicLeadAreaItem').hide();
}

// Show a specific Dynamic Lead item
function dynamicLeadAreaTurnOnItem() {
    jQuery('#dynamicLeadAreaItem' + iCurrentDynamicLeadAreaItem).fadeIn(iDynamicLeadFadeTimeInMS);
}

// Render the current state of the Dynamic Lead widget
function dynamicLeadAreaRenderItem() {
    dynamicLeadAreaHideAll();
    dynamicLeadAreaTurnOnItem();
}

// Remove the ON class from all nav links (which will turn them all off)
function dynamicLeadAreaClearAllLinkClasses() {
    jQuery('#dynamicLeadAreaNav a').removeClass('on');
}

// Add the ON class to a specific nav link (which will turn that nav link on)
function dynamicLeadAreaTurnOnLinkClass() {
    jQuery('#dynamicLeadAreaNavLink' + iCurrentDynamicLeadAreaItem).addClass('on');
}

// Render the appropriate style for the nav links
// Turns all nav links off and then turns on the currently-selected nav link
function dynamicLeadAreaSetLinkClasses() {
    dynamicLeadAreaClearAllLinkClasses();
    dynamicLeadAreaTurnOnLinkClass();
}

// Handles a click on a nav button
function dynamicLeadAreaHandleClick(oLink, oEvent) {
    // cancel the delayed event for the next auto rotation and set a new longer delayed rotation event (so you can see the item you clicked on for a while before fading starts again)
    clearTimeout(oDynamicLeadTimeOutInstance);
    oDynamicLeadTimeOutInstance = setTimeout(dynamicLeadAreaRotate, iDynamicLeadRotationTimeAfterClickInMS);

    oEvent.preventDefault();

    dynamicLeadAreaHandleClickLogic(oLink);
}

// The main logic that occurs whenever a click event fires
function dynamicLeadAreaHandleClickLogic(oLink) {
    sIdAttrVal = oLink.attr('id');
    iItemId = parseInt(sIdAttrVal.substring(22)); // 22 is the length of 'dynamicLeadAreaNavLink' which is always the link id prefix
    if (iItemId != iCurrentDynamicLeadAreaItem) {
        iCurrentDynamicLeadAreaItem = iItemId;
        dynamicLeadAreaRenderItem();
        dynamicLeadAreaSetLinkClasses();
    }
}


// Dynamically generates a nav link
// Usually run only at initialization
// Automatically adds the ON class to the first nav link
function dynamicLeadAreaAddNavLink(iNum) {
    sOnClass = '';
    if (iNum == 1) {
        sOnClass = ' class="on"';
    }

    oNavBox = jQuery('#dynamicLeadAreaNav');
    oNavBox.append('<a href="#" id="dynamicLeadAreaNavLink' + iNum + '"' + sOnClass + '></a>');

    jQuery('#dynamicLeadAreaNavLink' + iNum).click(function (event) {
        oLink = jQuery(this);
        dynamicLeadAreaHandleClick(oLink, event);
    });
}

// Automatically Rotate through Dynamic Lead Widget items
function dynamicLeadAreaRotate() {
    var iItemNumToClick = 0;
    var oLinkToClick;

    if (iCurrentDynamicLeadAreaItem >= iTotalDynamicLeadAreaItems) {
        iItemNumToClick = 1;
    }
    else {
        iItemNumToClick = iCurrentDynamicLeadAreaItem + 1;
    }

    oLinkToClick = jQuery('#dynamicLeadAreaNav a#dynamicLeadAreaNavLink' + iItemNumToClick);
    if (oLinkToClick.length !== 0) {
        dynamicLeadAreaHandleClickLogic(oLinkToClick);
    }

    dynamicLeadAreaRotateRecurse();
}

// Launch a new delayed rotation event
function dynamicLeadAreaRotateRecurse() {
    oDynamicLeadTimeOutInstance = setTimeout(dynamicLeadAreaRotate, iDynamicLeadRotationTimeInMS);
}

// Make the entire slide clickable by launching the same URL linked in the H4 (inner link)
function dynamicLeadAreaHandleSlideClick(oEvent, oThis) {
    oEvent.preventDefault();
    oThis = jQuery(oThis);
    var oInnerLink = oThis.find('h4 a');
    if (oInnerLink.length > 0) {
        var sInnerLinkUrl = oInnerLink.attr('href');
        if (sInnerLinkUrl !== '' && sInnerLinkUrl !== null && sInnerLinkUrl !== undefined) {
            document.location = sInnerLinkUrl;
        }
    }
}

// Initialize the Dynamic Lead Widget system
function dynamicLeadAreaInitialize() {
    // store the total count of available dynamic lead items
    var oDynLeadItems = jQuery('.dynamicLeadAreaItem');
    iTotalDynamicLeadAreaItems = oDynLeadItems.size();

    if (oDynLeadItems.length > 0) {
        // set up click handler to make entire slide clickable
        oDynLeadItems.css('cursor', 'pointer');
        oDynLeadItems.click(function (event) {
            dynamicLeadAreaHandleSlideClick(event, this);
        });

        // dynamically generates the appropriate number of nav links depending on the number of content items available
        for (i = 1; i <= iTotalDynamicLeadAreaItems; i++) {
            dynamicLeadAreaAddNavLink(i);
        }

        // render the first content item
        dynamicLeadAreaRenderItem();

        // start the automatic rotation process
        dynamicLeadAreaRotateRecurse();
    }
}






// ### FEATURES SLIDING WIDGET

// Global Features Sliding Widget variables 
var iTotalFeaturesItems = 0;
var iTotalFeaturesGroups = 0;
var iCurrentFeaturesGroup = 1;
var iNumItemsPerFeaturesGroup = 3;
var iPixelWidthOfEachFeaturesItem = 320;
var iTextRolloverFadeSpeed = 100;
var iTotalWidthOfContainer = iPixelWidthOfEachFeaturesItem;
var bFeaturesClickLock = false;

// Enacts a move to the next item, including updating the styles for nav buttons
function featuresMoveNext() {
    if (iCurrentFeaturesGroup < iTotalFeaturesGroups && !bFeaturesClickLock) {
        bFeaturesClickLock = true;
        iCurrentFeaturesGroup = iCurrentFeaturesGroup + 1;
        featuresAnimate();
        featuresUpdateNav();
    }
}

// Enacts a move to the previous item, including updating the styles for nav buttons
function featuresMovePrev() {
    if (iCurrentFeaturesGroup > 1 && !bFeaturesClickLock) {
        bFeaturesClickLock = true;
        iCurrentFeaturesGroup = iCurrentFeaturesGroup - 1;
        featuresUpdateNav();
        featuresAnimate();
    }
}

// Handles the sliding animation for any navigation operation
function featuresAnimate() {
    iNewLeftMargin = (iPixelWidthOfEachFeaturesItem * iNumItemsPerFeaturesGroup * (iCurrentFeaturesGroup - 1)) + 20; // there is a 20 pixel side margin on each item in the CSS
    jQuery('.features-inner').animate({ marginLeft: '-' + iNewLeftMargin + 'px' }, 1000, function () {
        bFeaturesClickLock = false;
    });
}

// Updates the navigation arrow button styles
// Indicates whether or not a next and/or previous movement is currently available
function featuresUpdateNav() {
    sPrevSrc = jQuery('#featuresNavPrev').attr('src');
    sNextSrc = jQuery('#featuresNavNext').attr('src');

    if (iCurrentFeaturesGroup <= 1) {
        jQuery('#featuresNavPrev').attr('src', sPrevSrc.replace('filter2.png', 'filterBk2.png'));
    }
    else {
        jQuery('#featuresNavPrev').attr('src', sPrevSrc.replace('filterBk2.png', 'filter2.png'));
    }

    if (iCurrentFeaturesGroup >= iTotalFeaturesGroups) {
        jQuery('#featuresNavNext').attr('src', sNextSrc.replace('filter.png', 'filterBk.png'));
    }
    else {
        jQuery('#featuresNavNext').attr('src', sNextSrc.replace('filterBk.png', 'filter.png'));
    }
}

// Handles a click on an item in a nicer way
// Normally the A tag is only on the text inside the H5
// This function enables a click anywhere on the entire item to activate the link
function featuresHandleClick(oThis) {
    oThisContainer = jQuery(oThis);
    oThisLink = oThisContainer.find('h5 a');
    document.location = oThisLink.attr('href');
}

// Handles a hover ON of the headline area for any featured item promo (makes additional text visible)
function featuresHandleHoverOn() {
    oThis = jQuery(this);
    oH5 = oThis.find('h5');
    oP = oThis.find('p');

    oH5.hide();
    oP.fadeIn(iTextRolloverFadeSpeed);
}

// Handles a hover OFF of the headline area for any featured item promo (makes additional text invisible again)
function featuresHandleHoverOff() {
    oThis = jQuery(this);
    oH5 = oThis.find('h5');
    oP = oThis.find('p');

    oH5.fadeIn(iTextRolloverFadeSpeed);
    oP.hide();
}

// Initialize all Features Sliding Widget functionality
function featuresInitialize() {
    // store the total count of items
    iTotalFeaturesItems = parseInt(jQuery('.features-item').size());

    // calculate the total number of item groups
    iTotalFeaturesGroups = Math.ceil(iTotalFeaturesItems / iNumItemsPerFeaturesGroup);

    // calculate the total necessary width of the "inner" container that must contain all item groups and slide back and forth
    iTotalWidthOfContainer = iTotalFeaturesItems * iPixelWidthOfEachFeaturesItem;

    // assign the total "inner" width
    jQuery('.features-inner').css('width', iTotalWidthOfContainer + 'px');

    // click handler for the next arrow nav button
    jQuery('#featuresNavNext').click(function () {
        featuresMoveNext();
    });

    // click handler for the prev arrow nav button
    jQuery('#featuresNavPrev').click(function () {
        featuresMovePrev();
    });

    // show the proper initial styles for the arrow nav buttons
    featuresUpdateNav();

    // run the basic initialize features for features-item promos, such as making the whole promo clickable and setting up text rollovers
    featuresInitializeLite();
}

// Initialize functionality for Features Promos, but without most of the complex handling for sliding
// This is for use on index and Just For You pages where "features-item" promos are used outside of a slider widget
function featuresInitializeLite() {
    // click handler for items
    jQuery('.features-item').click(function () {
        featuresHandleClick(this);
    });

    // show a special mouse pointer icon only when javascript is enabled (since otherwise you can't click on the whole item, you can only click on the link in the H5 text)
    jQuery('.features-item').css('cursor', 'pointer');

    // set up mouseover text
    jQuery('.features-item .content .headline').hover(featuresHandleHoverOn, featuresHandleHoverOff);
}









// ### ARTS SLIDER WIDGET

// Global Arts Slider Widget variables 
var iTotalArtsSliderItems = 0;
var iTotalArtsSliderGroups = 0;
var iCurrentArtsSliderGroup = 1;
var iNumItemsPerArtsSliderGroup = 7;
var iPixelWidthOfEachArtsSliderItem = 85;
var iTotalWidthOfArtsSliderContainer = iPixelWidthOfEachArtsSliderItem;
var bArtsSliderClickLock = false;

// Handle clicks on the next arrow
function ArtsSliderMoveNext() {
    if (iCurrentArtsSliderGroup < iTotalArtsSliderGroups && !bArtsSliderClickLock) {
        bArtsSliderClickLock = true;
        iCurrentArtsSliderGroup = iCurrentArtsSliderGroup + 1;
        ArtsSliderAnimate();
        ArtsSliderUpdateNav();
    }
}

// Handle clicks on the prev arrow
function ArtsSliderMovePrev() {
    if (iCurrentArtsSliderGroup > 1 && !bArtsSliderClickLock) {
        bArtsSliderClickLock = true;
        iCurrentArtsSliderGroup = iCurrentArtsSliderGroup - 1;
        ArtsSliderUpdateNav();
        ArtsSliderAnimate();
    }
}

// Enacts the proper sliding animation whenever a nav button is clicked
function ArtsSliderAnimate() {
    iNewLeftMargin = (iPixelWidthOfEachArtsSliderItem * iNumItemsPerArtsSliderGroup * (iCurrentArtsSliderGroup - 1)) + 5; // item groups have a 5 pixel side margin
    jQuery('.artsslider-inner').animate({ marginLeft: '-' + iNewLeftMargin + 'px' }, 1000, function () {
        bArtsSliderClickLock = false;
    });
}

// Updates styling on the nav buttons to indicate whether or not a next and/or prev movement are possible
function ArtsSliderUpdateNav() {
    sPrevSrc = jQuery('#ArtsSliderNavPrev').attr('src');
    sNextSrc = jQuery('#ArtsSliderNavNext').attr('src');

    if (iCurrentArtsSliderGroup <= 1) {
        jQuery('#ArtsSliderNavPrev').attr('src', sPrevSrc.replace('filter2.png', 'filterBk2.png'));
    }
    else {
        jQuery('#ArtsSliderNavPrev').attr('src', sPrevSrc.replace('filterBk2.png', 'filter2.png'));
    }

    if (iCurrentArtsSliderGroup >= iTotalArtsSliderGroups) {
        jQuery('#ArtsSliderNavNext').attr('src', sNextSrc.replace('filter.png', 'filterBk.png'));
    }
    else {
        jQuery('#ArtsSliderNavNext').attr('src', sNextSrc.replace('filterBk.png', 'filter.png'));
    }
}

// Initialize all Arts Slider Widget functionality
function artssliderInitialize() {
    // store the total count of items
    iTotalArtsSliderItems = parseInt(jQuery('.artsslider-item').size());

    // calculate the number of item groups
    iTotalArtsSliderGroups = Math.ceil(iTotalArtsSliderItems / iNumItemsPerArtsSliderGroup);

    // calculate the total necessary width of the "inner" container that must contain all item groups and slide back and forth
    iTotalWidthOfArtsSliderContainer = iTotalArtsSliderItems * iPixelWidthOfEachArtsSliderItem;

    // assign the total "inner" width
    jQuery('.artsslider-inner').css('width', iTotalWidthOfArtsSliderContainer + 'px');

    // show a special mouse pointer icon only when javascript is enabled
    jQuery('.artsslider-item').css('cursor', 'pointer');

    // click handler for next arrow button
    jQuery('#ArtsSliderNavNext').click(function () {
        ArtsSliderMoveNext();
    });

    // click handler for prev arrow button
    jQuery('#ArtsSliderNavPrev').click(function () {
        ArtsSliderMovePrev();
    });

    // show the appropriate initial styling for nav arrow buttons
    ArtsSliderUpdateNav();
}








// ### HIDDEN DATE PICKER

// Initialize Hidden Date Picker functionality
function HiddenDatePickerInitialize() {
    // initialize the jQuery UI DatePicker plugin on any form field with the ID "hiddenDate"
    jQuery('#hiddenDate').datepicker({
        showOn: 'button',
        buttonImage: '/Sites/ArtsEdge/images/buttons/calendar.gif',
        buttonImageOnly: true
    });

    // enforce a limit on the dates that can be navigated to in certain date pickers (such as the one on the Arts Days right column
    var dTodaysDate = new Date();
    var sTodaysYear = dTodaysDate.getFullYear();
    jQuery('.restrictedDates').datepicker('option', 'minDate', new Date(sTodaysYear, 0, 1));
    jQuery('.restrictedDates').datepicker('option', 'maxDate', new Date(sTodaysYear + 3, 11, 31));

    // Handler for any change to the Hidden Date Picker value (normally want to take the new value, parse it, and change some other dropdown values based on the hidden date picker value)
    jQuery('#hiddenDate').change(function () {
        // extract the value selected in the date picker
        var sDateVal = jQuery('#hiddenDate').val();
        var dDate = new Date(sDateVal);
        var sDay = dDate.getDate();
        var sMonth = dDate.getMonth();

        if (sDay < 10) {
            sDay = '0' + sDay;
        }

        var month = new Array(12);
        month[0] = "january";
        month[1] = "february";
        month[2] = "march";
        month[3] = "april";
        month[4] = "may";
        month[5] = "june";
        month[6] = "july";
        month[7] = "august";
        month[8] = "september";
        month[9] = "october";
        month[10] = "november";
        month[11] = "december";

        // select the correct date dropdown options based on the date selected by the visitor from the jQuery UI DatePicker widget
        oMonthInput = jQuery('select.minisearchMonth');
        oDayInput = jQuery('select.minisearchDay');
        oFullDateInput = jQuery('input.minisearchFullDate');
        if (oMonthInput.length !== 0) {
            oMonthInput.val(month[parseInt(sMonth)]);
        }
        if (oDayInput.length !== 0) {
            oDayInput.val(sDay);
        }
        if (oFullDateInput.length !== 0) {
            oFullDateInput.val(sDateVal);
        }
    });
}







// ### SEARCH RESULTS EXPANDER

// Global Search Results Expander variables 
var bSearchResultsExpanderClickLock = false;

// Handle a click on any Search Results Expander
// Normally used to hide/show extra descriptive text inside a row in a search results table
function handleSearchResultsExpanderClick(oThis, oEvent) {
    if (!bSearchResultsExpanderClickLock) {
        bSearchResultsExpanderClickLock = true;

        oJThis = jQuery(oThis);

        oJThisImg = oJThis.find('img');
        oJThisSpan = oJThis.find('span');
        sJThisImgSrc = oJThisImg.attr('src');
        sJThisSpanTxt = oJThisSpan.text();

        oAllDescTextItems = jQuery('.searchResultsList .item .itemcontent p');

        if (sJThisSpanTxt == 'Show Description') {
            // show
            oJThisSpan.text('Hide Description');
            oJThisImg.attr('src', sJThisImgSrc.replace('show_small', 'hide_small'));
            oAllDescTextItems.slideDown(500, function () {
                bSearchResultsExpanderClickLock = false;
            });
        }
        else {
            // hide
            oJThisSpan.text('Show Description');
            oJThisImg.attr('src', sJThisImgSrc.replace('hide_small', 'show_small'));
            oAllDescTextItems.slideUp(500, function () {
                bSearchResultsExpanderClickLock = false;
            });
        }
    }
}

// Initialize all Search Results Expander functionality
function searchResultsExpanderInitialize() {
    // click handler for any expander paragraph
    jQuery('.searchResultsLegend .expander p').click(function (event) {
        handleSearchResultsExpanderClick(this, event);
    });

    // add a special mouse pointer when javascript is enabled (since only then does the user have the ability to click and see more info)
    jQuery('.searchResultsLegend .expander p').css('cursor', 'pointer');
}







// ### SIMPLE TABS

// Handle tab clicks
// Normally used for simple tabbed controls in the right column
// Turns off all tabs and then turns on only the clicked tab and its content
function handleTabsClick(oThis, oEvent) {
    oEvent.preventDefault();
    oJThis = jQuery(oThis);
    jQuery('.tabsnav a').removeClass('on');
    oJThis.addClass('on');
    jQuery('.tabscontentbox').removeClass('on');
    jQuery('.tabscontentbox:eq(' + oJThis.index() + ')').addClass('on');
}

// Initialize all Simple Tab functionality
function initializeTabs() {
    // turn off all tabs
    jQuery('.tabscontentbox').removeClass('on');

    // turn on the first tab
    jQuery('.tabscontentbox:first').addClass('on');

    // click handler for tabs
    jQuery('.tabsnav a').click(function (event) {
        handleTabsClick(this, event);
    });

    // look for URL hash and if one exists preselect the correct tab
    initializeTabsHash();

    // monitor the URL hash for changes and run function to open + close tabs when it does change
    jQuery(window).bind('hashchange', initializeTabsHash);
}

// Open + Close tabs based on a hash in the URL 
function initializeTabsHash() {
    // look for URL hash and if one exists preselect the correct tab
    if (window.location.hash) {
        // turn off all tabs at first to set the stage for turning on the proper tab
        jQuery('.tabscontentbox').removeClass('on');
        jQuery('.tabsnav a').removeClass('on');

        // initialize variables
        var iTabIndexToTurnOn = 0; // default to the first tab in case we can't match the hash to any tab text
        var sUrlHash = jQuery.trim(window.location.hash.substr(1).toLowerCase().replace(/%20/g, ' ')); // strip out %20 spaces for IE and other browsers that encode URL spaces

        // loop through all tabs to determine if our hash matches any
        jQuery('.tabsnav a').each(function (iIndex) {
            var jThisTab = jQuery(this);
            //var sTabText = jQuery.trim(jThisTab.text().toLowerCase());
            var sTabText = jQuery.trim(jThisTab.attr('rel').toLowerCase());
            if (sUrlHash == sTabText) {
                iTabIndexToTurnOn = iIndex;
            }
        });

        // turn on the appropriate tab
        jQuery('.tabscontentbox:eq(' + iTabIndexToTurnOn + ')').addClass('on');
        jQuery('.tabsnav a:eq(' + iTabIndexToTurnOn + ')').addClass('on');
    }
}









// ### MOST POPULAR

// Handle clicks on Most Popular nav links
// Turns off all nav items and then turns on only the clicked item and its content
function handleTabsMostPopularClick(oThis, oEvent) {
    oEvent.preventDefault();
    oJThis = jQuery(oThis);
    jQuery('.mostpopulartabsnav a').removeClass('on');
    oJThis.addClass('on');
    jQuery('.mostpopulartabscontentbox').removeClass('on');
    jQuery('.mostpopulartabscontentbox:eq(' + oJThis.index() + ')').addClass('on');
}

// Initialize all Most Popular functionality
function initializeTabsMostPopular() {
    // turn off all nav items
    jQuery('.mostpopulartabscontentbox').removeClass('on');

    // turn on the first nav item
    jQuery('.mostpopulartabscontentbox:first').addClass('on');

    // click handler for nav items
    jQuery('.mostpopulartabsnav a').click(function (event) {
        handleTabsMostPopularClick(this, event);
    });
}







// ### SIMPLE SLIDER

// Global Simple Slider variables
var iSliderSpeed = 500;

// Handle clicks on the slider
// Toggles visibility for the slider's expanded content 
function handleSliderClick(sId, oEvent) {
    oEvent.preventDefault();
    jQuery('#' + sId + ' h4.sliderhead').toggleClass('on');
    jQuery('#' + sId + ' .slidercontent').slideToggle(iSliderSpeed);
}

// Initialize all Simple Slider functionality
function initializeSlider(sId) {
    // hide the slider's expanded content at first
    jQuery('#' + sId + ' .slidercontent').slideUp(iSliderSpeed);

    // click handler for clicks on the slider
    jQuery('#' + sId + ' h4.sliderhead').click(function (event) {
        handleSliderClick(sId, event);
    });
}







// ### UTILITY PRINT

// Handle clicks on the basic "Print" link
// Removes a special class from all tab content boxes to ensure that only the currently-selected tab content is printed
function handlePrintLink(oEvent) {
    oEvent.preventDefault();
    if (jQuery('.tabscontentbox').hasClass('tabscontentbox_printall')) {
        jQuery('.tabscontentbox').removeClass('tabscontentbox_printall');
    }
    launchBrowserPrintDialog();
}

// Handle clicks on the "Print All" link
// Adds a special class from all tab content boxes to ensure that all tab content is printed, not just the currently-selected tab content
function handlePrintLinkAll(oEvent) {
    oEvent.preventDefault();
    if (!jQuery('.tabscontentbox').hasClass('tabscontentbox_printall')) {
        jQuery('.tabscontentbox').addClass('tabscontentbox_printall');
    }
    launchBrowserPrintDialog();
}

// Launch the web browser's print dialog
function launchBrowserPrintDialog() {
    window.print();
}

// Initialize Utility Print link functionality
function initializePrintLinks() {
    // click handler for basic "Print" links
    jQuery('.printlink').click(function (event) {
        handlePrintLink(event);
    });

    // click handler for "Print All" links
    jQuery('.printlink_all').click(function (event) {
        handlePrintLinkAll(event);
    });
}






// ### FILTER BY DROPDOWN

// Handle clicks on the close X link for a Filter By Dropdown
function handleFilterByRobustDropXClick(oEvent) {
    oEvent.preventDefault();
    closeAllFilterByRobustDrops();
}

// Handle clicks on the Update button for a Filter By Dropdown
// Closes the dropdown (by closing all dropdowns)
function handleFilterByRobustDropUpdateClick(oEvent) {
    closeAllFilterByRobustDrops();
}

// Handle clicks on Select All or Deselect All links
// Automatically turns on or off all checkboxes inside the relevant Filter By Dropdown
function handleFilterByRobustDropSelecterClick(oThis, oEvent, bCheckedValue) {
    oEvent.preventDefault();
    oLink = jQuery(oThis);
    oContainer = oLink.parent().parent().parent();
    oContainer.find("input:checkbox").attr('checked', bCheckedValue);
}

// Handles clicks on the main button for each Filter By Dropdown
// Closes all dropdowns and then turns on the relevant dropdown if necessary
function handleFilterByRobustDropClick(oThis, oEvent) {
    oEvent.preventDefault();
    closeAllFilterByRobustDrops();
    oButton = jQuery(oThis);
    oDropContainer = oButton.parent();
    oDropContainer.toggleClass('on');
    closeBigGridItem();
}

// Closes all dropdowns
function closeAllFilterByRobustDrops() {
    jQuery('.filterbybox_robustdrop').removeClass('on');
}

// Initialize all Filter By Dropdown functionality
// Normally used for the robust Filter By Dropdowns on the Themes and Multimedia pages
function initializeFilterBy() {
    // click handler for main dropdown buttons
    jQuery('a.filterbybox_robustdrop_button').click(function (event) {
        handleFilterByRobustDropClick(this, event);
    });

    // click handler for the close X button in each dropdown
    jQuery('a.filterbybox_robustdrop_closex').click(function (event) {
        handleFilterByRobustDropXClick(event);
    });

    // click handler for the Update button in each dropdown
    jQuery('a.filterbybox_robustdrop_update').click(function (event) {
        handleFilterByRobustDropUpdateClick(event);
    });

    // click handler for the Select All links
    jQuery('a.filterbybox_robustdrop_selectall').click(function (event) {
        handleFilterByRobustDropSelecterClick(this, event, true);
    });

    // click handler for the Deselect All links
    jQuery('a.filterbybox_robustdrop_deselectall').click(function (event) {
        handleFilterByRobustDropSelecterClick(this, event, false);
    });
}







// ### BIG GRID

// Global Bug Grid variables
var bBigGridOverItem = false;
var bBigGridOverPopup = false;
var oThisItem = null;
var iThisItemIndex = null;

// Handle mouse over on a Big Grid item
// Figures out which item you are hovering and sets a function to turn on the appropriate popup content after a set wait time
// The wait time allows you to swipe your mouse cursor across the grid items without having tons of large popups opening and closing quickly
function handleBigGridHoverOn() {
    bBigGridOverItem = true;
    oThisItem = jQuery(this);
    iThisItemIndex = oThisItem.index();
    setTimeout('turnOnBigGridItem(' + iThisItemIndex + ')', 300);
}

// Handles mouse out for Big Grid items
// Closes any open item content popups
function handleBigGridHoverOut() {
    closeBigGridItem();
}

// Turns on the content popup for a specific grid item
// Closes any open Filter By dropdowns since they might interfere with the content popup's visibility or CSS z-index
// Determines the width and height for the content popup and uses those values to calculate the proper absolute positioning of the content popup
// This includes determining whether the arrow should be on the right or left of the popup and how to vertically center the arrow and the popup itself 
function turnOnBigGridItem(iIndexOfSupposedItem) {
    if (oThisItem.index() == iIndexOfSupposedItem && bBigGridOverItem) {
        bBigGridOverItem = true;
        closeAllFilterByRobustDrops();
        sHTML = oThisItem.find('.item_detail').html();
        iLeftOfItem = parseInt(oThisItem.offset().left);
        iTopOfItem = parseInt(oThisItem.offset().top);
        iIndex = parseInt(oThisItem.index()) + 1;
        oPopup = jQuery('.biggrid_popup');
        bLeft = true;
        fIndexDecimal = parseFloat(iIndex / 6) - parseInt(iIndex / 6);
        bFullWidth = true;

        // see if the grid items are inside a partial width column, like the "content" column on a standard index page
        if (oPopup.closest('div.content').length !== 0) {
            bFullWidth = false;
            fIndexDecimal = parseFloat(iIndex / 4) - parseInt(iIndex / 4);
        }

        if (fIndexDecimal > .5 || fIndexDecimal == 0) {
            bLeft = false;
            oPopup.addClass('biggrid_popup_right');
        }
        else {
            oPopup.removeClass('biggrid_popup_right');
        }

        oPopup.find('.biggrid_popup_body').html(sHTML);
        iHeight = parseInt(oPopup.height());
        iTopForPopup = iTopOfItem - (Math.round((iHeight - 105) / 2));
        iLeftForPopup = iLeftOfItem + 138; // if grid item is in the "left" portion of the grid, make the CSS x position for the popup appear to the right of the grid item - 138 relates to the width of grid items 

        if (!bLeft) {
            iLeftForPopup = iLeftOfItem - (158 + 208); // if grid item is in the "right" portion of the grid, make the CSS x position for the popup appear to the right of the grid item - 158 and 208 relate to the width of grid items and popup items
        }

        iTopForArrow = (Math.round(iHeight / 2)) - 14; // set the CSS y position for the arrow in the vertical middle of the popup's height - 14 relates to the height of the arrow graphic
        oPopup.css('top', iTopForPopup);
        oPopup.css('left', iLeftForPopup);
        oPopup.find('.biggrid_popup_arrow').css('top', iTopForArrow);
        oPopup.fadeIn(200);
    }
}

// Allows content popup to close after a very shot timeout
// The timeout allows you to swipe your mouse away from a popup for a split second without the popup closing in an annoying fashion
function closeBigGridItem() {
    bBigGridOverItem = false;
    setTimeout(bigGridPopupCloser, 50);
}

// Turn on a global variable whenever you've hovered over a grid item
function handleBigGridPopupHoverOn() {
    bBigGridOverPopup = true;
}

// Turn off a global variable whenever you've hovered away from a grid item
function handleBigGridPopupHoverOff() {
    bBigGridOverPopup = false;
    setTimeout(bigGridPopupCloser, 50);
}

// Turns off visibility for an open popup
function bigGridPopupCloser() {
    if (bBigGridOverPopup == false && bBigGridOverItem == false) {
        jQuery('.biggrid_popup').fadeOut(200);
    }
}

// Handle clicks on a grid item
// Allow the A tag link in the label to work for any click on the entire item
function bigGridItemHandleClick(oThis) {
    oThisContainer = jQuery(oThis);
    oThisLink = oThisContainer.find('a.label');
    document.location = oThisLink.attr('href');
}

// Initialize all Big Grid functionality
function initializeBigGrid() {
    // Add mouse hover handlers for grid items, use special mouse cursor when javascript is enabled, add click handler for clicks on grid items
    jQuery('.biggrid_inner .item').hover(handleBigGridHoverOn, handleBigGridHoverOut).css('cursor', 'pointer').click(function () {
        bigGridItemHandleClick(this);
    });

    // Add mouse hover handlers for content popups
    jQuery('.biggrid_popup').hover(handleBigGridPopupHoverOn, handleBigGridPopupHoverOff);
}





// ### DYNBACKS

// Global DynBack variables
var aDynBacks = new Array();
var iCurrentDynBackId = '1'; // should be set to the unique ID from sitecore/database for the default dynamic background

var iIndexBackgroundId = 0;
var iIndexBackgroundName = 1;
var iIndexBackgroundColorHex = 2;
var iIndexBackgroundImgPath = 3;
var iIndexBackgroundImgTopWhitePath = 4;
var iIndexBackgroundImgBottomWhitePath = 5;
var iIndexBackgroundImgThumbPath = 6;

// Display the most recently chosen dynamic background graphics				
function dynBackRender() {
    var iCurrentArrayId = dynBackFindCurrentArrayId();
    jQuery('body').css('background-color', '#' + aDynBacks[iCurrentArrayId][iIndexBackgroundColorHex]);
    jQuery('body').css('background-image', 'url(' + aDynBacks[iCurrentArrayId][iIndexBackgroundImgPath] + ')');
    jQuery('.dynbacktop').css('background-image', 'url(' + aDynBacks[iCurrentArrayId][iIndexBackgroundImgTopWhitePath] + ')');
    jQuery('.dynbackbottom').css('background-image', 'url(' + aDynBacks[iCurrentArrayId][iIndexBackgroundImgBottomWhitePath] + ')');
}

// Determine the sitecore/database ID for the currently selected dynamic background 
function dynBackFindCurrentArrayId() {
    var iReturnVal = 0;
    for (i = 0; i < aDynBacks.length; i++) {
        if (iCurrentDynBackId == (aDynBacks[i][iIndexBackgroundId] + '')) {
            iReturnVal = i;
            break;
        }
    }

    return iReturnVal;
}

// Handle a click on a dynamic background thumbnail
function dynBackThumbClick(oThis, oEvent) {
    oEvent.preventDefault();
    oClickedThumb = jQuery(oThis);
    jQuery('.dynbacks_thumbs img.inset').removeClass('on');
    oClickedThumb.addClass('on');
    iCurrentDynBackId = oClickedThumb.attr('rel') + '';
    dynBackRender();
    saveDynBackChoice();
}

// Dynamically generates a nav link
// Usually run only at initialization
// Automatically adds the ON class to the appropriate nav link
function dynBackAddNavLink(iNum) {
    sOnClass = '';
    if (iCurrentDynBackId == (aDynBacks[iNum][iIndexBackgroundId] + '')) {
        sOnClass = ' on';
    }

    oNavBox = jQuery('.dynbacks_thumbs_inner');
    oNavBox.append('<img src="' + aDynBacks[iNum][iIndexBackgroundImgThumbPath] + '" alt="" rel="' + aDynBacks[iNum][iIndexBackgroundId] + '" class="inset' + sOnClass + '" />');
}

// Save the most recently chosen dynamic background image in a local cookie for reference each time the visitor loads a new page
function saveDynBackChoice() {
    jQuery.cookie('aedynback', iCurrentDynBackId, { path: '/' });
}

// Read the most recently chosen dynamic background from a local cookie (if available) and render
// Normally called on page load
function readDynBackChoice() {
    iCurrentDynBackId = jQuery.cookie('aedynback') + '';
    if (iCurrentDynBackId === null) {
        iCurrentDynBackId = '1'; // should be set to the unique ID from sitecore/database for the default dynamic background
    }
    dynBackRender();
}

// Initialize the dynBack thumbnail choice system
function dynBackThumbInitialize() {
    // dynamically generates the appropriate number of thumbnail links depending on the number of dynamic backgrounds available
    for (i = 0; i < aDynBacks.length; i++) {
        dynBackAddNavLink(i);
    }

    // make all thumbnails active functional links
    jQuery('.dynbacks_thumbs img.inset').click(function (event) {
        dynBackThumbClick(this, event);
    });
}




// ### myAE STUFF
// disabled until https is enabled
//jQuery(document).ready(function() {
//    jQuery(document).login_box({
//        button: jQuery('a.login-button'),
//        box: jQuery('div.login-dropdown'),
//        close_button: jQuery('a.login-cancel'),
//        username: jQuery('input.login-username'),
//        password: jQuery('input.login-password2'),
//        password_text: 'Password'
//    });
//});

function initializeFormToggles() {
    jQuery('div.form-toggle').each(function () {
        var form = jQuery(this).find('div.toggle-form');
        var info = jQuery(this).find('div.toggle-info');
        var show = jQuery(this).find('a.show-form');
        var hide = jQuery(this).find('a.hide-form');
        if (form.hasClass('form-toggle-on')) {
            // act as if show was clicked
            info.hide();
            show.addClass('noshow');
        } else {
            form.hide();
        }
        show.click(function () {
            info.hide();
            form.css('display', 'inline-block'); // for IE7
            show.addClass('noshow');
            return false;
        });
        hide.unbind().click(function () {
            info.css('display', 'inline-block'); // for IE7
            form.hide();
            show.removeClass('noshow');
            return false;
        });
    });
}

function initializeSuggestedTags() {
    jQuery('.suggested-tags a').click(function () {
        var h = jQuery(this).html();
        var input = jQuery(this).parent().prev();
        var v = input.val();
        var nv = v + ', ' + h;
        input.val(nv);
        jQuery(this).remove();
        var h = jQuery('.suggested-tags').html();
        var nh = h.split(', ,').join(',');
        jQuery('.suggested-tags').html(nh);
        // re initialize
        initializeSuggestedTags();
        return false;
    });
}

function initializeSelectMenus(options) {
    if ((/msie/i.test(navigator.userAgent)) && !(/opera/i.test(navigator.userAgent))) {
        return false; // do nothing
    }
    // go on
    if (options.sel === undefined) {
        options.sel = '.select-menu';
    }
    if (options.width === undefined) {
        options.width = 200;
    }
    jQuery('select' + options.sel).selectmenu({
        width: options.width
    });
}

/// <summary>
/// Posts the updated bookmark data to the service
/// </summary>
function initializeEditBookmarks() {
    jQuery('div.bookmarks_item_edit_table_buttons a.updateBookmark').click(function () {

        var key = jQuery(this).attr('rel');
        var tags = jQuery('input[name=' + key + ':tags]').val();
        var folder = jQuery('select[name=' + key + ':folder.select] :selected').val();
        var newFolderName = jQuery('input[name=' + key + ':folder.new]').val();
        var note = jQuery('textarea[name=' + key + ':note]').val();

        jQuery.ajax({
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            url: "/Sites/ArtsEdge/MyArtsEdge/Services/UpdateBookmark.ashx",
            data: "{'key':'" + key + "','tags':'" + tags + "','folderKey':'" + folder + "','newFolder':'" + newFolderName + "','note':'" + note + "'}",
            success: function (result) {
                if (result.Success) {
                    // for now, update ui the easy way...
                    location.reload();
                } else {
                    // Error message
                }
            }
        });

    });

    jQuery('div.bookmarks_item_buttons a.deleteBookmark').click(function () {
        var key = jQuery(this).attr('rel');
        jQuery.ajax({
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            url: "/Sites/ArtsEdge/MyArtsEdge/Services/DeleteBookmark.ashx",
            data: "{'key':'" + key + "'}",
            success: function (result) {
                if (result.Success) { // refresh the page to remove the bookmark
                    location.reload();
                } else {
                    // Error message
                }
            }
        });
    });
}

/// <summary>
/// support ajax renaming of folders from All Folders page
/// </summary>
function initializeEditBookmarkFolders() {
    jQuery('div.bookmarks_item_edit_table_buttons a.savebutton').click(function () {
        // get the folder key
        var key = jQuery(this).attr('rel');
        var newFolderName = jQuery('input[name=' + key + ':folder.new]').val();

        jQuery.ajax({
            type: "POST",
            contentType: 'application/json',
            dataType: 'json',
            url: "/Sites/ArtsEdge/MyArtsEdge/Services/RenameBookmarkFolder.ashx",
            data: "{'key':'" + key + "','newFolder':'" + newFolderName + "'}",
            success: function (result) {
                if (result.Success) { // refresh the page to remove the bookmark
                    location.reload();
                } else {
                    // Error message
                }
            }
        });
    });
}
