jQuery(document).ready(function() {
    // Global Style settings 
    $(".rsrclink a[href$=pdf]").addClass("iconr pdf");
    $(".rsrclink a[href$=zip]").addClass("iconr zip");
    
    // site tabs
    addTabs();

    // back to careers button    
    backtoButtons();

    // interior carousels
    interiorCarousels();
   
    //determine interior banner image background placement
    $(".interiorBanner").addClass("interiorBanner" + Math.floor(Math.random()*10));
    $(".landingpageBanner").addClass("landingpageBanner" + Math.floor(Math.random()*3));
    //restrict content to first portion of first paragraph (for use anywhere)
    $(".brevify").each(function(i) {
        $(this).html("<p>" + $(this).find("p:first").html() + "</p>");
        var ptext = $(this).html();
        brpos = ptext.toLowerCase().indexOf("<br", 0);
        if (brpos > 0) {
            newtext = ptext.substring(0, brpos);
            $(this).html(newtext);
        }
    });


    //remove date of on-demand webinars (year=2111)
    if ($('.webinardate').length) { 
        $('.webinardate').each(function(){
            var $t = jQuery(this);
            if ($t.text().indexOf("2111") >= 1) {
                if ($('.homepage').length) {
                    $t.text("On-demand Webinar");
                    $t.show();
                } else {                                        
                    $t.remove();
                }
            } else {
                $t.show();
            }  
        });        
    }

    if ($('.truncateTeaser').length) { 
        //remove links from truncateTeaser section
        $('.truncateTeaser a').each(function(){
            var $t = jQuery(this);
            $t.after($t.text());
            $t.remove();
        });
        // limit to 150 characters, add ellipses and CTA link (for use on homepage)
        $(".truncateTeaser").each(function(){
            var teaser = $(this);
            //teaser.find('a').html().remove();
            var shortP = teaser.children("p:first-child");
            shortP.html(shortP.html().substring(0,150)+"&hellip;");
            var teaserContainer = $(this).parent('div');
            var CTAlink = teaserContainer.find('a:first').attr("href");
            var CTAtext = "";
            if (teaserContainer.attr("class") == 'event' ) {
                CTAtext = "Learn&nbsp;more";
            } else if (teaserContainer.attr("class") == 'webinar' ) {
                CTAtext = "Register&nbsp;now";
            } else {
                CTAtext = "Read&nbsp;more";
            }
            shortP.append('  <a href="'+ CTAlink +'">'+ CTAtext +'</a>');
        });
    }
    
    // first 3 items per feedburner-inserted blog list
    // $( ".hometabs table .feedburnerFeedBlock[id ^= 'EnterpriseLicenseOptimization'] li:gt(2)" ).hide();
    // $( ".hometabs table .feedburnerFeedBlock[id ^= 'EntitlementComplianceManagement'] li:gt(2)" ).hide();
    // $( ".hometabs table .feedburnerFeedBlock[id ^= 'InstallTalk'] li:gt(2)" ).hide();
    $( ".feedburnerFeedBlock div" ).hide(); //removes creditfooter div
    
    // remove some empty elements
    // TODO: shift responsibility to RedDot: conditionally include this div
    $("div.feat-footnote, div.intro-teaser, div.subheader3, ul").each(function() {
        if (jQuery.trim ( $(this).text() ) == "") $(this).remove();
    });
    $("div.intro-teaser").next("div.clear").remove();
    
    //L1 & Utility navigation
    addNav();
    // search button
    $("#search-form .glass i").hover( function() {
        $(this).addClass("hover")
    }, function () {
        $(this).removeClass("hover")
    });
    $('#search-form .glass i').click(function() {
      $('#search-form').submit();
    });
    
    // move content into place
    $("#utilitynavContent").appendTo("#utilitynavWrapper").show();
    $("#L1NavContent").appendTo("#L1NavWrapper").show();
    $("#sidebarContent").appendTo("#sidebar").show();
    $("#breadcrmb div").html("");
    $("#breadcrumbContent").appendTo("#breadcrmb div").show();
    // repurpose youtube sidebar blocks into video page feature items (no descriptions needed)
    $(".featureblock:not(.TBstatic) .sidebox").each(function() { 
        if ($(this).has('.text a img')) {
            $(this).find('.text').find('a').has('img').appendTo(this);
            $(this).find('.text').remove();
        }    
    });    
    // Remove empty product CTA element
    $("div#prodCTAs:empty").hide();
    
    if ($('.readmore').length) { 
        // read more functionality
        $("div.readmore").prev().append('<a class="readmore plus">More</a>');
        $("div.readmore").hide();
        $("a.readmore").toggle(function(event) {
            $(this).text("Less").removeClass("plus").addClass("minus");
            $(this).parent().next("div.readmore").show('500');
            return false;
        }, function(event) {
            $(this).text("More").removeClass("minus").addClass("plus");
            $(this).parent().next("div.readmore").hide('500');
            return false;
        });
    }
    
    // Old JS Functions (mostly RedDot workarounds)
    contentFunctions();
    // homepage carousel
    if ($('.homepage').length) { initHomepage(); }
    // demote second H4 for items within sidebar and Additional Resources (.featureblock)
    $("#sidebar .sidebox h4.boxKicker, .TBstatic.featureblock .sidebox h4.boxKicker").next("h4.boxTitle").each(function() {
        $(this).replaceWith( "<b>" + $(this).html() + "</b>" );
    });
    // equal height columns: for interior columnized feature items (often under additional resources)
    equalHeight($(".TBstatic.featureblock .TBitem > div").slice(0,3)); //last bit restricts it to the first row (3 items) - assumes there will be 6 or less
    equalHeight($(".featureblock .sidebox h4")); // for the headlines
    
    //product intro box - equal height columns
    if ($('#prodFeature').length) { 
        // $('#prodIntro').addClass("narrow");
        randomItem($('#prodFeature > div'));
    }
    $('#prodCTAs').show();
    $('.featureblock, ul.socialmedia').show().css('left','0px');
    
    $('.filltext').textfill({ maxFontPixels: 17, innerTag: 'span' });
    
    //make entire element clickable (relies on first contained link) 
    $(".passThroughClick").click(function() { 
        window.location = $(this).find("a:first").attr("href");
        return false;
    });    
    
    /************************************  (from old js)
    FancyBox wireup */
    $("a.fancybox-youtube").fancybox({
         'frameWidth': 425,
         'frameHeight': 344,
         'overlayOpacity': 0.4,
         'overlayColor': '#000000'
     });
    $("a.fancybox-img").fancybox({
        'overlayOpacity': 0.4,
        'overlayColor': '#000000',
        'zoomSpeedIn': 600,
        'zoomSpeedOut': 300
    });
    // buttonify
        /* sample: <a href="#" class="buttonify yellowarrow">Button Label</a>
           converts to: <div class="button"><a href="#" class="yellowarrow"><span>Button Label</span></a></div> 
           can also provide static code, like so: <div class="button"><a href="#" class="yellow left" style="width:250px;"><span>linktext</span></a></div> 
           note: width applied, "left" aligns text left    */
    var buttonifyLinks = $('a.buttonify');
    buttonifyLinks.each(function(i) {
        var i = $(this);
        i.wrap('<div class="button" />');
        i.wrapInner('<span />');
        i.removeClass('buttonify');
     });
     // form button
    $(".formbutton").hover(function() { 
        $(this).addClass('formbuttonHover'); 
    } , function() { 
        $(this).removeClass('formbuttonHover'); 
    });     
    //roundrect-ify linked images
    //  [for hyperlinked images (a.rndRectify > img)]
    var rritems = $('a.rndRectify');
    rritems.each(function(i) {
        var i = $(this);
        var iwidth = $(this).find('img').width();
        var iheight = $(this).find('img').height();
        i.wrap('<div class="rndRectWrapper" />');
        i.before('<div class="rndRectOverlayLeft"><div></div></div><div class="rndRectOverlayRight"><div></div></div>');
        i.parent(".rndRectWrapper").css("width", iwidth+2).css("height", iheight+2);
        i.removeClass('rndRectify');
     });

    // for div.rndRectify (div.rndRectify) -- requires width&height
    var rritems = $('div.rndRectify');
    rritems.each(function(i) { 
        var i = $(this);
        var iwidth = $(this).width();
        var iheight = $(this).height();
        i.wrap('<div class="rndRectWrapper" />');
        i.before('<div class="rndRectOverlayLeft"><div></div></div><div class="rndRectOverlayRight"><div></div></div>');
        i.parent(".rndRectWrapper").css("width", iwidth+2).css("height", iheight+2);
        // i.removeClass('rndRectify');
     });
    //  [for direct image application (img.rndRectify)]
    var rritems = $('img.rndRectify');
    rritems.each(function(i) {
        var i = $(this);
        var iwidth = $(this).width();
        var iheight = $(this).height();
        i.wrap('<div class="rndRectWrapper" />');
        i.before('<div class="rndRectOverlayLeft"><div></div></div><div class="rndRectOverlayRight"><div></div></div>');
        i.parent(".rndRectWrapper").css("width", iwidth+2).css("height", iheight+2);
        i.removeClass('rndRectify');
     });     

    // jQuery GA Event Tracker  (updated for GA async code)
    trackGAevents();
     
}); // end jquery ready

/* ***********************************
FUNCTIONS 
*********************************** */
function addNav() {       
    // L1 navigation - current section
    pageURL = $(location).attr('href').toLowerCase();
    navLI = $("ul#f3nav li");
    utilLI = $("ul#utilitynav li");
    if (pageURL.indexOf("com/solutions") >= 0) {
        navLI.has("a.solutions").addClass('current');
    } else if (pageURL.indexOf("resources/trial") >= 0) {
        navLI.has("a.freetrial").addClass('current');
    } else if (pageURL.indexOf("com/resources") >= 0) {
        navLI.has("a.resources").addClass('current');
    } else if (pageURL.indexOf("com/products") >= 0) {
        navLI.has("a.products").addClass('current');
    } else if (pageURL.indexOf("com/services") >= 0) {
        navLI.has("a.services").addClass('current');
    } else if (pageURL.indexOf("com/support") >= 0) {
        navLI.has("a.support").addClass('current');
    } else if (pageURL.indexOf("com/purchase") >= 0) {
        navLI.has("a.purchase").addClass('current');
    } else if (pageURL.indexOf("com/company/contact.htm") >= 0) {
        utilLI.has("a.unav-contactus").addClass('current');
    } else if (pageURL.indexOf("com/company") >= 0) {
        utilLI.has("a.unav-company").addClass('current');
    } else if (pageURL.indexOf("com/partners") >= 0) {
        utilLI.has("a.unav-partners").addClass('current');
    }   
    // L1 navigation: mobile devices
    $('ul#f3nav li.L1 a.L1').click(function() {
        if ( isMobile() ) {
            var parentLi = $(this).parent('li');
            $('div.f3L2').hide();
            $("ul#f3nav li").removeClass('hover').removeClass('displayMenu');
            $("ul#f3nav li.xcurrent").removeClass('xcurrent').addClass('current');
            if ( !(parentLi.hasClass('tapped'))) {
                $("ul#f3nav li").removeClass('tapped');
                $(this).parent("li.current").removeClass('current').addClass('xcurrent');
                parentLi.addClass('hover').addClass('displayMenu').addClass('tapped');
                parentLi.find("div.f3L2").show();
            }
            return false;
        }
    });
    // L1 navigation: PCs
    $("ul#f3nav li").hover(function() { 
        if ( !(isMobile()) ) {
            $(this).addClass('hover').addClass('displayMenu'); 
            if ( $(this).hasClass('current') ) { 
                $(this).addClass('xcurrent').removeClass('current'); 
            }
            $(this).find("div.f3L2").show();
        }
    } , function() { 
        if ( !(isMobile()) ) {
            $(this).find("div.f3L2").hide();
            $(this).removeClass('hover').removeClass('displayMenu'); 
            if ( $(this).hasClass('xcurrent') ) { 
                $(this).addClass('current').removeClass('xcurrent'); 
            }
        }
    });
     
    // Utility navigation
    $('ul#utilitynav li.un:has(div.flyoutMenu) a.un').click(function() {
        if ( isMobile() ) {
            var parentLi = $(this).parent('li');
            $('div.utilityMenu').hide();
            $("ul#utilitynav li").removeClass('hover');
            $("ul#utilitynav li.xcurrent").removeClass('xcurrent').addClass('current');
            if ( !(parentLi.hasClass('tapped'))) {
                $("ul#utilitynav li").removeClass('tapped');
                $(this).parent("li.current").removeClass('current').addClass('xcurrent');
                parentLi.addClass('hover').addClass('tapped');
                parentLi.find("div.utilityMenu").show();
            }
            return false;
        }
    });    
    $("ul#utilitynav li.un").hover(function() { 
        if ( !(isMobile()) ) {
            $(this).addClass('hover'); 
            if ( $(this).hasClass('current') ) { 
                $(this).addClass('xcurrent').removeClass('current'); 
            }
            $(this).find("div.utilityMenu").show();
        }    
    } , function() { 
        if ( !(isMobile()) ) {
            $(this).find("div.utilityMenu").hide();
            $(this).removeClass('hover'); 
            if ( $(this).hasClass('xcurrent') ) { 
                $(this).addClass('current').removeClass('xcurrent'); 
            }
        }    
    });
    $("ul#utilitynav li.un a.unav-twitter").click(function () {// L1 exception
        return false;
    });
    // Follow navigation
    $('ul.followNav li.un:has(div.flyoutMenu) a.un').click(function() {
        if ( isMobile() ) {
            var parentLi = $(this).parent('li');
            $('div.utilityMenu').hide();
            $("ul.followNav li").removeClass('hover');
            $("ul.followNav li.xcurrent").removeClass('xcurrent').addClass('current');
            if ( !(parentLi.hasClass('tapped'))) {
                $("ul.followNav li").removeClass('tapped');
                $(this).parent("li.current").removeClass('current').addClass('xcurrent');
                parentLi.addClass('hover').addClass('tapped');
                parentLi.find("div.utilityMenu").show();
            }
            return false;
        }
    });    
    $("ul.followNav li.un").hover(function() { 
        if ( !(isMobile()) ) {
            $(this).addClass('hover'); 
            if ( $(this).hasClass('current') ) { 
                $(this).addClass('xcurrent').removeClass('current'); 
            }
            $(this).find("div.utilityMenu").show();
        }    
    } , function() { 
        if ( !(isMobile()) ) {
            $(this).find("div.utilityMenu").hide();
            $(this).removeClass('hover'); 
            if ( $(this).hasClass('xcurrent') ) { 
                $(this).addClass('current').removeClass('xcurrent'); 
            }
        }    
    });
    $("ul.followNav li.un a.unav-twitter").click(function () {// L1 exception
        return false;
    });
    // add sidenav highlight for subpages
    if ( !$('.sidenav a.a').length) {
        // sidenav: transform current URL into most likely parent URL (grab path, append.htm)
        var parentPage = pageURL.slice( (pageURL.indexOf('.com/') +4),pageURL.lastIndexOf('/')) + ".htm"; 
        // sidenav: find any sidebar hrefs that match parentPage, add class to highlight it
        $('.sidenav a[href|='+parentPage+']').addClass('a');
        // special case: newscenter/, which doesn't match news.htm 
        if (pageURL.indexOf("newscenter") >= 0) {
                $('.sidenav a[href*="company/news"]').addClass('a');
        }       
        //news center current tabs
                if (pageURL.indexOf("press-releases") >= 0) {
                        $('ul.TBtabs:first li').has('a[href*="press-releases"]').first().addClass('current');
                } else if (pageURL.indexOf("articles-reviews") >= 0) {  
                        $('ul.TBtabs:first li').has('a[href*="articles-reviews"]').first().addClass('current');
                } else if (pageURL.indexOf("awards") >= 0) {    
                        $('ul.TBtabs:first li').has('a[href*="awards"]').first().addClass('current');
                }
    }    
    $("ul#utilitynav").show();
    $("#f3nav").show();
}; //addNav

function initHomepage() {     
    //homepage carousel
    $("#carouselWrapper #carouselItems").reorder();    //optionally reorder items
    $("#carouselWrapper #carouselItems .first").remove().prependTo("#carouselWrapper #carouselItems"); // optionally pin one item to front of list
    $("#carouselWrapper #carouselItems").carouFredSel({
        height: 228,
        width: 786,
        items: {
            visible: 1,
            width: 786,
            height: 228
        },
        direction: "up",
        pagination  : "#carouselControls #carouselPagination",
        scroll: {
            items: 1,
            pauseOnHover: true
            // onBefore: function() {
            //     $("#carouselWrapper").fadeOut('normal');
            // },
            // onAfter: function() {
            //     $("#carouselWrapper").fadeIn('normal');
            // }
        },
        auto: 7700 // sets the interval between slides, in ms
    });    
    $("#carouselWrapper").css("left","0");
}; //initHomepage

function isMobile() {
    var deviceAgent = navigator.userAgent.toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
    if (agentID) {return true;}
};
function addTabs() {
    // unhide & move tab nav
    $("#TBnavonlySource").appendTo("#TBnavonlyContainer").addClass("TBnavonly").show();
    // first, exclude any TBitems without TBtabify as parent
    $(".TBtabify .TBitem, .TBstatic .TBitem, .TBcontained .TBitem").addClass("preserve");
    $(".TBitem").not('.preserve').removeClass("TBitem");
    //now we can set up the tabs    
    var tabifyContainers = $('div.TBtabify > div[title]');
    $(".TBtabify").prepend('<ul class="TBtabs"></ul>');// set up tabify menu (link list) 
    tabifyContainers.each(function(i) {
        var thisone = $(this);
        thisone.attr("id", "TBitemlink" + i);
        thisone.addClass('TBitem');
        $(".TBtabify .TBtabs").append("<li><a id='link" + i + "' href='#TBitemlink" + i + "'>" +  thisone.attr("title") + "</a></li>");
     });
    $(".TBtabify .TBtabs li").filter(':first').addClass('first').addClass('current');
    // other prep
    $('.TBnavonly .TBtabs li').filter(':first').addClass('first'); //add "first" class to first tab
    $(".TBcontained .TBitem").addClass('TBitemcontained'); //add class for our round box
    // prep static single tab
    var staticContainers = $('div.TBstatic').has('h2');
    staticContainers.each(function(i) {
        var thisone = $(this);
        var str = thisone.find('h2').text();
        thisone.find('h2').after('<ul class="TBtabs"><li>'+str+'</li></ul>').remove();
        thisone.find('.TBtabs li').addClass("current").wrapInner(document.createElement("a")); // for tab backgrounds
     });    
    $('.TBtabs li a').wrapInner(document.createElement("span")); // for tab backgrounds
    $('.TBtabs').show();
    var tabContainers = $('div.TBitem');
    $('.TBtabify .TBtabs li a').eq(0).addClass("first");
    if (!$('.TBtabify .TBtabs li.current a').length) { // create a current tab if there isn't already one
        $('.TBtabify .TBtabs li').eq(0).addClass("current"); // first tab active
    }
    var tabInit = $('.TBtabify .TBtabs li.current a').attr('href');
    if(tabInit) { // show content corresponding to "current" tab
        var    tabInitialID = tabInit.replace("#", ""); //remove pound character.  IE no likey if tabInit has no value
        tabContainers.hide().filter('#' + tabInitialID).show();
        }
    $('.TBtabify ul.TBtabs a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        $('.TBtabify ul.TBtabs li').removeClass('current');
        $(this).parent('li').addClass('current');
        return false;
    }).filter(':first').click();
    $(".TBnavonly .TBtabs li a.a").parent("li").addClass("current");//convert RedDot a.a to tbtabs-friendly li.current 
    $(".TBnavonly .TBtabs.reverse").attr("id","reversetab");
    reverse(document.getElementById('reversetab'));
    // style subtabs (tbtabs --> tbsubtabs)    
    $(".pgbody #TBnavonlyContainer").next(".TBtabify").addClass("TBsubtabify").find("ul.TBtabs").addClass("TBsubtabs");
    // style subtabs (variant found in the news section) 
    $(".pgbody #TBnavonlyContainer").next(".TBnavonly").addClass("TBsubtabify").find("ul.TBtabs").addClass("TBsubtabs");
    // small text tabs
    $(".TBtabsNarrow").parents(".pgbody").find(".TBsubtabs").addClass("TBtabsNarrow");
    // END: site tabs
};


// "back to [careers|news center]" sidebar buttons
function backtoButtons() {     
    var pageURL = $(location).attr('href').toLowerCase();
    var pageReferrer = document.referrer.split('/')[2];
    if (!pageReferrer) {pageReferrer = "none"};
    // if [referrer is blank or not www.flexerasoftware.com] AND [page is a careers page]
    if ( (pageReferrer.indexOf("www.flexerasoftware.com") == -1) && (pageURL.indexOf("careers") > -1) ) {
        // create session cookie
        $.cookie("returnLink", "careers", {path: "/"});
    }
    // if cookie exists, display image if we're not currently on a careers page
    if ( ($.cookie("returnLink") == "careers") && (pageURL.indexOf("careers") == -1) ) {
        $(".sidenav").after('<a href="/company/careers.htm"><img src="http://www.flexerasoftware.com/static/images/button-returnto-careers1.png" style="margin:0 0 12px 0;" ></a>');
    }
}; //backtoButtons 


function interiorCarousels() {
    if ($('#sideCarousel').length) { 
        $("#sideCarousel").css('filter', 'alpha(opacity=99)').reorder().show();
        $("#sideCarousel").carouFredSel({
            items: 1,
            scroll: {
                fx: "fade",
                //easing: "linear",
                //duration: 800,
                pauseOnHover: true
            },
            auto: {
                pauseDuration: 3000,
                delay: 500
            }
        });    
    }
    if ($('#quoteCarousel').length) { 
        $("#quoteCarousel").css('filter', 'alpha(opacity=99)').reorder().show();
        $("#quoteCarousel img").css('filter', 'alpha(opacity=99)');
        $("#quoteCarousel").carouFredSel({
            items: 1,
            scroll: {
                fx: "slide",
                //easing: "linear",
                //duration: 800, //800 for prod
                pauseOnHover: true
            },
            pagination  : ".carouselControls .carouselPagination",
            auto: {
                pauseDuration: 7000, //6000 for prod
                delay: 500 // 8000 for prod
            }
        });    
    }    
};

function contentFunctions () {
    /************************************ (from old js)
    Note: we should be able to remove this
    Old tabs js */
    // Default first tab show
    $("div#subtabs ul li a:first").addClass("a");
    $("div.pgtab-inner").hide();
    $("div.pgtab-inner:first").show();
    // Tab toggling
    $("div#subtabs ul li").click(function(event) {
        /* Set CSS for click */
        event.preventDefault();
        $("div#subtabs ul li").find("a").removeClass("a");
        $(this).find("a").addClass("a");
        /* Toggle tab data */
        $(".pgtab-inner").hide();
        var elemID = $(this).attr("id");
        $("div#" + elemID + "_Data").show();
    });
    //reverse tab order: for tabs that navigate pages, not toggle divs */
    $("div.subtabs ul").attr("id","reversetab");
    $("div#subtabs ul").attr("id","");
    /* reverse(document.getElementById('reversetab')); */
    
    /************************************ (from old js)
    Resources */
    $(".rsrc-group a.details-link").toggle( function() {
        $(this).removeClass("plus").addClass("minus");
        $(this).next().show();
        return false;
    }, function () {
        $(this).removeClass("minus").addClass("plus");
        $(this).next().hide();
        return false;
    });
    $(".linkhdr #jumpto").change( function() {
        var hash = "#" + $(this).val();
        $.scrollTo(hash, 700, { easing:'easeOutExpo' }); 
        /* insert top anchor and "top" links if we haven't already */
        if($('#topanchor').length == 0)
            $('body').prepend("<a id='topanchor' name='top'></a>");
        if($('.toplink').length == 0)
            $('.rsrc-toppicks .icon').prepend("<div class='toplink'><a href='#top'>top</a></div>");
    });
    /* display description, remove expand link with .expandAll */
    $(".rsrc-group a.details-link").next().show();
    $(".rsrc-group a.details-link").hide();
    /* if we're in the resources section, expand all */
    if (window.location.href.indexOf("resources")!=-1) {
        $("div.rsrc-group a.details-link").hide();
       $("div.rsrc-group div.details p").show();
    }
    /* misc resource cleanup */
    $(".rsrc-toppicks #featured").next("h3").hide();
    $(".rsrc-toppicks #featured").parents("table.rsrc-toppicks").addClass('featuredVideos').find("td.icon").removeClass('icon');
    $(".featuredVideos .videoPromoImg").show();
    $(".featuredVideos .videoPromoDesc").hide();
    equalHeight($(".featuredVideos h4")); // for the headlines    
    
    /* restrict table to 5 rows.  Initially for events page: ".top5rows" applied to the H2 of that section */
    $(".top5rows").parent().next("table").find("tr:gt(4)").hide();
    
    /************************************ (from old js)
    Product Features */
    // build features page
    if ($("table.featlist").length) {  
        //populate each section with a copy of the table header  
        tableheader = $("table.featlist thead.tableheader tr:first"); // column headings
        $("table.featlist thead.tableheader").remove();
        $(tableheader).prependTo("table.featlist > tbody");
        // expand/collapse functionality
        $("table.featlist").children("thead").next("tbody").hide();
        $("table.featlist thead a").toggle(function(event) {
            event.preventDefault();
            $(this).removeClass("plus-lg").addClass("minus-lg");
            $(this).parents("thead").next("tbody").show();
        }, function(event) {
            event.preventDefault();
            $(this).removeClass("minus-lg").addClass("plus-lg");
            $(this).parents("thead").next("tbody").hide();
        });
    }
    $("div.feat-showall a").toggle(function(event) {
        event.preventDefault();
        $(this).parents("div").next("table").find("thead").next("tbody").show(); // on feature pages show main sections also      
        $(this).parents("div").next("table").find("thead a").removeClass("plus-lg").addClass("minus-lg");
        $("table.featlist div.full").show();
        $("table.featlist a.iconr.plus").text("Less").removeClass("plus").addClass("minus");
        $(this).text("Hide All").removeClass("plus").addClass("minus");
        $("span.overview").removeClass("overview").addClass("overviewlt");
    }, function(event) {
        event.preventDefault();
        $(this).parents("div").next("table").find("thead").next("tbody").hide();    
        $(this).parents("div").next("table").find("thead a").removeClass("minus-lg").addClass("plus-lg");
        $("table.featlist div.full").hide();
        $("table.featlist a.iconr.minus").text("More").removeClass("minus").addClass("plus");
        $(this).text("Show All").removeClass("minus").addClass("plus");
        $("span.overviewlt").removeClass("overviewlt").addClass("overview");
    });
    // Features hide/show
    if ($("table.featlist a.iconr").length) { 
        $("table.featlist div.full").hide();
        $("table.featlist a.iconr").click(function(event) {
            event.preventDefault();
            $(this).next().slideToggle("slow");
        });
        $("table.featlist a.iconr.plus, table.featlist a.iconr.minus").toggle(function(event) {
            $(this).text("Less").removeClass("plus").addClass("minus");
            $(this).prev().removeClass("overview").addClass("overviewlt");
        }, function(event) {
            $(this).text("More").removeClass("minus").addClass("plus");
            $(this).prev().removeClass("overviewlt").addClass("overview");
        });
    }  else {
        $("div.feat-showall").hide();
    }
    // table row hover highlight
    $(".rowhover tbody tr:has(td)").mouseover(function() {
        $(this).addClass("rollover");
    }).mouseout(function() {
        $(this).removeClass("rollover");
    });


    /************************************ 
    Select navigation menu */
    $("#select-nav select").change(function() {
        window.location = $("#select-nav select:not(.placeholder) option:selected").val();
    });
    // $("#select-nav").hide();
    /************************************ (from old js)
    RedDot content cleanup/overrides */
    if (window.location.href.indexOf("resources")!=-1) {
        // graphical list cleanup, initiated within Partner Section
        $('.subtabs:not(:has(ul))').hide();
        // display description, remove expand link with .expandAll
        $(".rsrc-group a.details-link").next().show();
        $(".rsrc-group a.details-link").hide();
    }
    if (window.location.href.indexOf("resources")!=-1) {
        // if we're in the resources section, expand all 
        $("div.rsrc-group a.details-link").hide();
        $("div.rsrc-group div.details p").show();
    }
    if ($('.noitems:not(:has(.rsrc-group))').length) { 
        // if no items, hide section & heading 
        $(".noitems").hide();
        $(".noitems").prev().hide();
    }
    if ($('.top5rows').length) { 
        /* restrict table to 5 rows.  Initially for events page: ".top5rows" applied to the H2 of that section */
        $(".top5rows").parent().next("table").find("tr:gt(4)").hide();
    }    
};
function trackGAevents() {
    // jQuery GA Event Tracker  (updated for GA async code)
    // downloads
    var fileTypes = ['doc','xls','pdf','ppt'];
    $('a').click(function() {
      var $a = $(this);
      var href = $a.attr('href');
      var hrefArray = href.split('.');
      var extension = hrefArray[hrefArray.length - 1];
      if ($.inArray(extension,fileTypes) != -1) {
        //pageTracker._trackEvent('download', extension, href);
        _gaq.push(['_trackEvent', 'download', extension, href]);
      }
    });
    // external links
    $('a').click(function() {
      var $a = $(this);
      var href = $a.attr('href');
      // see if the link is external
      if ( (href.match(/^http/)) && (! href.match(document.domain)) ) {
        // if so, register an event
        var category = 'outgoing';
        var event = 'click';
        var label = href;
        //pageTracker._trackEvent(category, event, href);
        _gaq.push(['_trackEvent', category, event, href]);
      }
    }); 
};
$.fn.reorder = function() {
    // randomly arranges children
    // sample call: $("#carouselWrapper #carouselItems").reorder();
    function randOrd() { return(Math.round(Math.random())-0.5); }
    return($(this).each(function() {
        var $this = $(this),
                $children = $this.children(),
                childCount = $children.length;
        if (childCount > 1) {
            $children.remove();
            var indices = [];
            for (i=0;i<childCount;i++) { indices[indices.length] = i; }
            indices = indices.sort(randOrd);
            $.each(indices,function(j,k) { $this.append($children.eq(k)); });
        }
    }));
};
function reverse(n) {       
    if (n){
        var kids = n.childNodes; 
        var numkids = kids.length;
        for(var i = numkids-1; i >= 0; i--) {  
            var c = n.removeChild(kids[i]);    
            n.appendChild(c);                 
        }
    }
};
function equalHeight(group) {
    var tallest = 0;
    group.each(function() {
        var thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
};
function randomItem(items) {
    var count = items.length;
    $(items).hide();
    $(items).eq(Math.floor(Math.random()*count)).show();
};
;(function($) {
    /**
    * Resizes an inner element's font so that the inner element completely fills the outer element.
    * @param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
    * @return All outer elements processed
    * @example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
    */
    $.fn.textfill = function(options) {
        var defaults = {
            maxFontPixels: 40,
            innerTag: 'span'
        };
        var Opts = jQuery.extend(defaults, options);
        return this.each(function() {
            var fontSize = Opts.maxFontPixels;
            var ourText = $(Opts.innerTag + ':visible:first', this);
            var maxHeight = $(this).height();
            var maxWidth = $(this).width();
            var textHeight;
            var textWidth;
            do {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
            } while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
        });
    };
})(jQuery);
