// JavaScript Document

var udf = 'undefined';
var resizeTimer = null;
var hasCss = false;
var isIeHack = false;
var isIe6 = false;
var isFullScreen = true;
var winWidth;
var winWidthStart;
var winHeight;
var leftNavMinWidth = null;
var contentAreaWidthStart = '';
var fieldsetWidthStart;
var opn = "Open";
var cls = "Close";
var sbm = " submenu";
var imgCache;

$(document).ready(function()
{
    var lng = "en-US";
    var pr = "Print";
    var cj = "To protect your security, this content cannot be displayed within a frame.\n\nYou will now be redirected to our official site:\n";

    if (($('meta[http-equiv*=Content-Language]').length > 0) && ($('meta[http-equiv*=Content-Language]').attr('content').length > 0))
    {
        lng = $('meta[http-equiv*=Content-Language]').attr('content');
    }
    else
    {
        var meta = document.getElementsByTagName('meta');

        if (meta.length > 0)
        {
            var fnd = false;
            var i = 0;

            while ((i < meta.length) && (!fnd))
            {
                if (meta[i].httpEquiv == 'Content-Language')
                {
                    lng = meta[i].content;
                    fnd = true;
                }
                else
                {
                    i++;
                }
            }
        }
    }

    //Spanish
    if (lng == "es-ES")
    {
        opn = "Abrir";
        cls = "Cerrar";
        pr = "Imprimir";
        sbm = " submenú";
        cj = "Para proteger su seguridad, este contenido no se puede mostrar dentro de un frame en HTML.\n\nAhora va a ser redirigido a nuestro sitio oficial:\n";
    }

    //Clickjacking Prevention
    if (top != self)
    {
        top.location.replace(self.location.href);
        alert(cj + self.location.href);
        setInterval( function() { document.body.innerHTML = ''; }, 1);
    }

    winWidthStart = $(window).width();

    if ($('#divMobile').length == 1)
    {
        isFullScreen = false;
    }

    initSlidingMenus();

    if (($.browser.msie) && (($.browser.version == "6.0") || ($.browser.version == "7.0")))
    {
        isIeHack = true;

        if ($.browser.version == "6.0")
        {
            isIe6 = true;
        }

        if (isFullScreen)
        {
            $(window).resize(function()
            {
                if (resizeTimer)
                {
                    clearTimeout(resizeTimer);
                }

                resizeTimer = setTimeout(windowResize, 100);
            });
        }
    }
    else if (isFullScreen)
    {
        $(window).resize(windowResize);
    }

    hasCss = cssEnabled();

    if (isFullScreen)
    {
        if ($('#divLeftColumn').length > 0)
        {
            if ($('#divLeftColumn').css('min-width') != null)
            {
                leftNavMinWidth = parseInt($('#divLeftColumn').css('min-width'));
            }
            
            if ($('#divSectionContentArea').length > 0)
            {
                contentAreaWidthStart = stylesheetsPropertySearch('#divSectionContentArea', 'width');
                
                if ((contentAreaWidthStart == '') && ($('#divSectionContentArea').width() > 0) && ($('#divSectionBody').width() > 0) && ($('#divSectionContentArea').width() != $('#divSectionBody').width()))
                {
                    contentAreaWidthStart = (100 * (parseFloat($('#divSectionContentArea').width()) / $('#divSectionBody').width())).toFixed(1) + '%';
                }
            }
        }

        windowResize();
    }

    /*if (hasCss)
    {
        $('.textResizeMenu .i').addClass('textSizeIncrease');
        $('.textResizeMenu .d').addClass('textSizeDecrease');
        $('.textResizeMenu .r').addClass('textSizeReset');
        $('a.viewIcon').addClass('viewIconRollover');
        $('a.addIcon').addClass('addIconRollover');
        $('a.editIcon').addClass('editIconRollover');
        $('a.deleteIcon').addClass('deleteIconRollover');

        $('a.iconOnly img').addClass('hide');
    }
    else
    {*/
        $('.textResizeMenu a').addClass('rollover');
        $('a.view_icon').addClass('rollover');
        $('a.add_icon').addClass('rollover');
        $('a.edit_icon').addClass('rollover');
        $('a.delete_icon').addClass('rollover');
    //}

    if ($('#divToolBar.print').length > 0)
    {
        var prLink = "<a href=\"#\" class=\"printPage\">" + pr + "</a>";

        if ($('#divToolBar ul').length > 0)
        {
            $('#divToolBar ul:first').prepend("<li>" + prLink + "</li>");
        }
        else
        {
            $('#divToolBar').html(prLink);
        }
    }

    initGallery();

    if ($('form.form > fieldset:not(.action):not(.itemGroup)').length > 1)
    {
        var max = 0;

        $('form.form > fieldset:not(.action):not(.itemGroup)').each(function()
        {
            if (max < $(this).width())
            {
                max = $(this).width();
            }
        });

        fieldsetWidthStart = max;

        $('form.form > fieldset:not(.action):not(.itemGroup)').width(max);
    }

    //Necessary on districtlookup.aspx: most browsers wouldn't jump to the #Results anchor from FORM's ACTION
    if ($('h2.results').length > 0)
    {
        window.location.hash = "#Results";
    }

    if ($('.imageRotate').length > 0)
    {
        $('.imageRotate').cycle
        ({
            timeout: 10000,
            delay: 0,
            speed: 1000
        });

        $('.imageRotate img.hidden').removeClass('hidden');
    }

    if ($('img[usemap]').length > 0)
    {
        if (typeof (jQuery.fn.maphilight) != udf)
        {
            $('img[usemap]').maphilight();
        }
    }

    if ($('a.rollover img').length > 0)
    {
        var imgSrc = "";
        var i = 0;
        var found = false;

        imgCache = new Array();

        $('a.rollover img').each(function()
        {
            found = false;
            i = 0;
            imgSrc = $(this).attr('src').replace(".", "_on.");

            while ((!found) && (i < imgCache.length))
            {
                (imgCache[i][1] == imgSrc) ? found = true : i++;
            }

            if (!found)
            {
                var img = document.createElement('img');
                img.src = imgSrc;
                imgCache.push(new Array(img, imgSrc));
            }
        });

        $('a.rollover img').hover
        (
            function()
            {
                $(this).attr('src', $(this).attr('src').replace(".", "_on."));
            },
            function()
            {
                $(this).attr('src', $(this).attr('src').replace("_on.", "."));
            }
        );
    }

    $('input:checkbox.sectionNA:checked').each(function()
    {
        $(this).closest('fieldset').find(':input:not(input[type=hidden]):not(input:checkbox.sectionNA)').attr('disabled', 'disabled');

        if (isIeHack)
        {
            $(this).closest('fieldset').find('input[type=text],textarea').addClass('disabled');
        }
    });

    $('a.printPage').click(function()
    {
        window.print();
        return false;
    });

    $('input:checkbox.sectionNA').click(function()
    {
        if ($(this).is(':checked'))
        {
            $(this).closest('fieldset').find(':input:not(input[type=hidden]):not(input:checkbox.sectionNA)').attr('disabled', 'disabled');

            if (isIeHack)
            {
                $(this).closest('fieldset').find('input[type=text],textarea').addClass('disabled');
            }
        }
        else
        {
            $(this).closest('fieldset').find(':input:not(input[type=hidden]):not(input:checkbox.sectionNA)').removeAttr('disabled');

            if (isIeHack)
            {
                $(this).closest('fieldset').find('input[type=text],textarea').removeClass('disabled');
            }
        }
    });

    // Google Analytics Event Tracking
    if (typeof (_gaq) != udf)
    {
        var dmn = document.domain;

        $('a[href^="mailto"]').click(function() { _gaq.push(['_trackEvent', "Email", $(this).attr("href").replace("mailto:", "")]); });
        $('a[href$=".pdf"]').click(function() { _gaq.push(['_trackEvent', "Download", "PDF", $(this).attr("href")]); });
        $('a[href$=".doc"]').click(function() { _gaq.push(['_trackEvent', "Download", "Word", $(this).attr("href")]); });
        $('a[href$=".docx"]').click(function() { _gaq.push(['_trackEvent', "Download", "Word", $(this).attr("href")]); });
        $('a[href$=".xls"]').click(function() { _gaq.push(['_trackEvent', "Download", "Excel", $(this).attr("href")]); });
        $('a[href$=".xlsx"]').click(function() { _gaq.push(['_trackEvent', "Download", "Excel", $(this).attr("href")]); });
        $('a[href$=".wmv"]').click(function() { _gaq.push(['_trackEvent', "Download", "WMV Video", $(this).attr("href")]); });
        $('a[href$=".swf"]').click(function() { _gaq.push(['_trackEvent', "Download", "Flash Video", $(this).attr("href")]); });
        $('a[href$="fs\=d"]').click(function() { _gaq.push(['_trackEvent', "Resize Text", "Decrease"]); });
        $('a[href$="fs\=i"]').click(function() { _gaq.push(['_trackEvent', "Resize Text", "Increase"]); });
        $('a[href$="fs\=r"]').click(function() { _gaq.push(['_trackEvent', "Resize Text", "Reset"]); });
        $('a[href$="mv\=1"]').click(function() { _gaq.push(['_trackEvent', "Page View", "Mobile"]); });
        $('a[href$="mv\=0"]').click(function() { _gaq.push(['_trackEvent', "Page View", "Full Screen"]); });
        $('a.printPage').click(function() { _gaq.push(['_trackEvent', "Print", window.location]); });
        $('a[href^="#"]:not("a.printPage")').click(function() { _gaq.push(['_trackEvent', "Anchor", $(this).text(), $(this).attr("href").replace("#", "")]); });

        $('a[href^="http"]:not("[href*=\"://' + dmn + '\"]"):not(".lang a")').click(function() { _gaq.push(['_trackEvent', "Outgoing", $(this).attr("href")]); });
        $('.lang a[href^="http"]:not("[href*=\"://' + dmn + '\"]")').click(function() { _gaq.push(['_link', $(this).attr("href")]); });
    }
});

function cssEnabled()
{
    var d = document.createElement('div');
    d.id = 'divCssTest';
    
    $('body').append(d);
    $('#divCssTest').css({display:'none', height:'1px', width:'1px'});

    var css = ($('#divCssTest').width() == 1) ? true : false;

    $('#divCssTest').remove();

    return css;
}

function windowResize()
{
    winWidth = $(window).width();
    winHeight = $(window).height();

    initTopMenu();
    columnResize();
    setFieldsetWidth();
}

function columnResize()
{
    if ((isFullScreen) && (hasCss))
    {
        if ($('.headingList,.horizontal').length > 0)
        {
            var nxt;
            
            $('.horizontal').each
            (
                function()
                {
                    if ($(this).attr('class').search(/\s*horizontalTitle\d{1,2}pct\s*/) > -1)
                    {
                        $(this).children('dt').each
                        (
                            function()
                            {
                                if ($(this).next('dd').length > 0)
                                {
                                    if ($(this).next('dd').next('dd').length == 0)
                                    {
                                        nxt = $(this).next('dd');

                                        if (nxt.height() < $(this).height())
                                        {
                                            nxt.height($(this).height());
                                        }
                                        else
                                        {
                                            nxt.height('auto');
                                        }
                                    }
                                }
                            }
                        );
                    }
                }
            );
            
            $('.headingList').each
            (
                function()
                {
                    if ($(this).attr('class').search(/\s*headingListTitle\d{1,2}pct\s*/) > -1)
                    {
                        $(this).children('h2,h3,h4,h5').each
                        (
                            function()
                            {
                                if ($(this).next('.headingDescription').length > 0)
                                {
                                    if ($(this).next('.headingDescription').next('.headingDescription').length == 0)
                                    {
                                        nxt = $(this).next('.headingDescription');

                                        if (nxt.height() < $(this).height())
                                        {
                                            nxt.height($(this).height());
                                        }
                                        else
                                        {
                                            nxt.height('auto');
                                        }
                                    }
                                }
                            }
                        );
                    }
                }
            );
        }
        
        if ((leftNavMinWidth != null) && ($('#divLeftColumn').length == 1))
        {
            if ($('#divLeftColumn').width() > leftNavMinWidth)
            {
                if (contentAreaWidthStart != '')
                {
                    $('#divSectionContentArea').css('width', contentAreaWidthStart);
                }

                $('#divSectionContent').height('auto');
                
                if ($('#divLeftColumn').height() >= $('#divSectionContent').height()) 
                {
                    $('#divSectionContent').height($('#divLeftColumn').height());
                }

                var btm = parseInt($('#divSectionBody').offset().top + $('#divSectionBody').height() + $('#divFooter').height());

                if (btm < $(window).height())
                {
                    var ch = $('#divSectionBody').height() + ($(window).height() - btm);
                    
                    (isIeHack) ? ch -= 16 : ch += 3;

                    $('#divSectionContent').height(ch);
                }
            }
            else
            {
                $('#divSectionContent').height('auto');

                if (contentAreaWidthStart != '')
                {
                    $('#divSectionContentArea').css('width', '100%');
                }
            }
        }
    }
}

function initTopMenu()
{
    if (($('.topNav').length > 0) && ($('.topNav .subMenuHeader').length > 0))
    {
        var text = "";
        var title = "";

        //Display the Fully Dynamic Nav Bar
        if ((winWidth > 550) && (winHeight > 200))
        {
            if (!$('.topNav').hasClass('topNavDynamic'))
            {
                $('.topNav').addClass('topNavDynamic');
            }
            
            $('.topNav .subMenuHeader').each
            (
                function()
                {
                    text = $(this).text().replace('&', '\&amp;');
                    title = text + sbm;
                    
                    if (($(this).parent().find('li').find('.currentPage').length == 0) && (!$(this).hasClass('menuOpenByDefault')))
                    {
                        $(this).replaceWith('<a href="#" title="' + title + '">' + text + '</a>');
                   }
                   else
                   {
                        $(this).replaceWith('<a href="#" title="' + title + '" class="subMenuSection">' + text + '</a>');
                    }
                }
            );

            fixTopNavIE6();

            $('.topNavDynamic li ul').hover
            (
                function()
                {
                    $(this).parent().find("a:first").addClass("sffocus");
                },
                function()
                {
                    $(this).parent().find("a:first").removeClass("sffocus");
                }
            );

            $('.topNavDynamic a').focus
            (
                function()
                {
                    $(this).addClass("sffocus");            //a:focus
                    $(this).parent().addClass("sfhover");   //li < a:focus

                    if ($(this).parent().parent().parent().get(0).tagName.toLowerCase() == 'li')
                    {
                        $(this).parent().parent().parent().addClass("sfhover");  //li < ul < li < a:focus
                        $(this).parent().parent().parent().find("a:first").addClass("sffocus");  //li < a:hover < ul < li < a:focus
                    }
                }
            );

            $('.topNavDynamic a').blur
            (
                function()
                {
                    $(this).removeClass("sffocus");
                    $(this).parent().removeClass("sfhover");

                    if ($(this).parent().parent().parent().get(0).tagName.toLowerCase() == 'li')
                    {
                        $(this).parent().parent().parent().removeClass("sfhover");
                        $(this).parent().parent().parent().find("a:first").removeClass("sffocus");
                    }
                }
            );
        }
        //Window Resized Too Small:  Remove the Dynamic Nav Bar
        else if ($('.topNav').hasClass('topNavDynamic'))
        {
            if (isIe6)
            {
                $('.topNavDynamic li ul').css('width', 'auto');
            }

            $('.topNav').removeClass('topNavDynamic');
        }
    }
}

function fixTopNavIE6()
{
    if (isIe6)
    {
        //Simulate the CSS li:hover effect
        $('.topNavDynamic li').hover
        (
            function()
            {
                $(this).addClass("sfhover");
            },
            function()
            {
                $(this).removeClass("sfhover");
            }
        );
        
        //Set the 2nd Tier's Width to fill the screen
        var cssClassFullWidth = {width: (winWidth - 13)};
        $('.topNavDynamic li ul').css(cssClassFullWidth);
    }
}

function initSlidingMenus()
{
    if ($('.slidingMenu').length > 0)
    {
        var text = "";
        var title = "";

        $('.slidingMenu .subMenuHeader').each
        (
            function()
            {
                text = $(this).text().trim().replace('&', '\&amp;').replace('"', '&quot;');
                title = " " + text + sbm;

                if (($(this).parent().find('li').find('.currentPage').length == 0) && (!$(this).hasClass('subMenuOpenByDefault')))
                {
                    $(this).next().hide();
                    $(this).replaceWith('<a href="#" title="' + opn + title + '" class="subMenuClosed">' + text + '</a>');
                }
                else
                {
                    $(this).replaceWith('<a href="#" title="' + cls + title + '" class="subMenuOpened">' + text + '</a>');
                }
            }
        );

        $('.slidingMenu a.subMenuClosed').toggle
        (
            function()
            {
                $(this).addClass("subMenuOpened");
                $(this).removeClass('subMenuClosed');
                $(this).attr('title', $(this).attr('title').replace(opn, cls));
            },
            function()
            {
                $(this).addClass("subMenuClosed");
                $(this).removeClass("subMenuOpened");
                $(this).attr('title', $(this).attr('title').replace(cls, opn));
            }
        );

        $(".slidingMenu a.subMenuClosed").click(function()
        {
            $(this).next().slideToggle('normal', function() { columnResize(); });
        });

        $('.slidingMenu a.subMenuOpened').toggle
        (
            function()
            {
                $(this).addClass("subMenuClosed");
                $(this).removeClass('subMenuOpened');
                $(this).attr('title', $(this).attr('title').replace(cls, opn));
            },
            function()
            {
                $(this).removeClass("subMenuClosed");
                $(this).addClass('subMenuOpened');
                $(this).attr('title', $(this).attr('title').replace(opn, cls));
            }
        );

        $('.slidingMenu a.subMenuOpened').click
        (
            function()
            {
                $(this).next().slideToggle('normal', function() { columnResize(); });
            }
        );
    }
}

function initGallery()
{
    if (typeof(jQuery.fn.galleria) != udf)
    {
        if ($('#ulGallery').length > 0)
        {
            $('#ulGallery').addClass('galleryDynamic'); // adds new class name to maintain degradability
            $('#ulGallery > li:first').addClass('active');
            $('<p class="galleryNav"></p>').insertAfter('#divCurrentImage');
            $('p.galleryNav').html('<a href="#" id="lnkGalleryPrevious" title="View previous photo">' + String.fromCharCode(171) + ' Previous</a> | <a href="#" id="lnkGalleryNext" title="View next photo">Next ' + String.fromCharCode(187) + '</a> ' + String.fromCharCode(160) + ' ' + String.fromCharCode(160));

            $('#lnkGalleryPrevious').click(function(c)
            {
                c.preventDefault();
                c.stopPropagation();
                $.galleria.prev();
            });

            $('#lnkGalleryNext').click(function(c)
            {
                c.preventDefault();
                c.stopPropagation();
                $.galleria.next();
            });

            $('ul.galleryDynamic').galleria(
            {
                history: false, // activates the history object for bookmarking, back-button etc.
                clickNext: true, // helper for making the image clickable
                insert: '#divCurrentImage', // the containing selector for our main image
                onImage: function(image, caption, thumb)
                {
                    // fade in the image & caption
                    image.css('display', 'none').fadeIn(1000);
                    caption.css('display', 'none').fadeIn(700);

                    $('#divCurrentImage').addClass('captionedImage');
                    $('#divCurrentImage').css('width', image.width());
                    $('.galleryNav').css('width', image.width());

                    // fetch the thumbnail container
                    var _li = thumb.parents('li');

                    // fade out inactive thumbnail
                    _li.siblings().children('img.selected').fadeTo(500, 0.4);

                    // fade in active thumbnail
                    thumb.fadeTo('fast', 1).addClass('selected');

                    // add a title for the clickable image
                    image.attr('title', 'Next image >>');
                },
                onThumb: function(thumb) // thumbnail effects goes here
                {
                    // fetch the thumbnail container
                    var _li = thumb.parents('li');

                    // if thumbnail is active, fade all the way.
                    var _fadeTo = _li.is('.active') ? '1' : '0.4';

                    // fade in the thumbnail when finnished loading
                    thumb.css({ display: 'none', opacity: _fadeTo }).fadeIn(1500);

                    // hover effects
                    thumb.hover
                    (
				        function() { thumb.fadeTo('fast', 1); },
    			        function() { _li.not('.active').children('img').fadeTo('fast', 0.4); } // don't fade out if the parent is active
			        )
                }
            });
        }
    }	
}

function setFieldsetWidth()
{
    if (fieldsetWidthStart > 0)
    {
        // Enlarged Window
        if ((winWidth >= winWidthStart) && (fieldsetWidthStart > $('form.form > fieldset:not(.action):not(.itemGroup):first').width()))
        {
            $('form.form > fieldset:not(.action):not(.itemGroup)').width(fieldsetWidthStart);
        }
        // Shrunken Window
        else if (winWidth < winWidthStart)
        {
            var pad = 8;

            if (($('form.form > fieldset:not(.action):not(.itemGroup):first').width() + pad) > winWidth)
            {
                $('form.form > fieldset:not(.action):not(.itemGroup)').width(winWidth - pad);
            }
            else
            {
                $('form.form > fieldset:not(.action):not(.itemGroup)').width(fieldsetWidthStart);
            }
        }
    }
}

function querystring(param)
{
    param = param.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

    var reg = new RegExp("[\\?&]" + param + "=([^&#]*)");
    
    var match = reg.exec(window.location.href);

    if (match != null)
    {
        return match[1];
    }
    else
    {
        return "";
    }
}

if (!Number.toFixed)
{
    Number.prototype.toFixed = function(n)
    {
        return Math.round(this * Math.pow(10, n)) / Math.pow(10, n);
    }
}

String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/, "");
}

function stylesheetsPropertySearch(selector, property)
{
    var value = "";

    if ((selector != null) && (selector.trim().length > 0) && (document.styleSheets) && (document.styleSheets.length > 0))
    {
        for (var i = 0; i < document.styleSheets.length; i++)
        {
            if (stylesheetIsScreen(document.styleSheets[i].media))
            {
                value += stylesheetProperty(document.styleSheets[i], selector, property); 
            }
        }
    }

    return value;
}

function stylesheetIsScreen(media)
{
    var isScreen = false;
    
    if ((media != udf) && (media != null))
    {
        switch (typeof(media))
        {
            //IE
            case 'string':
            {
                if ((media.length == 0) || (media.indexOf('screen') > -1))
                {
                    isScreen = true;
                }
                
                break;
            }
            case 'object':
            {
                if ((media.mediaText != udf) && (media.mediaText != null) && (typeof (media.mediaText) == 'string'))
                {
                    if ((media.mediaText.length == 0) || (media.mediaText.indexOf('screen') > -1))
                    {
                        isScreen = true;
                    }
                }
                else
                {
                    isScreen = true;
                }

                break;
            }
            default:
            {
                isScreen = true;
                break;
            }
        }
    }
    else
    {
        isScreen = true;
    }
    
    return isScreen;
}

function stylesheetProperty(stylesheet, selector, property)
{
    var value = "";
    
    if (stylesheet.imports)
    {
        for (var i = 0; i < stylesheet.imports.length; i++)
        {
            if (stylesheetIsScreen(stylesheet.imports[i].media))
            {
                if ((value.length > 0) && (/[^;]\s*$/.test(value)))
                {
                    value += ";";
                }
                
                value += stylesheetProperty(stylesheet.imports[i], selector, property);
            }
        }
    }
    
    var rules = stylesheet.rules || stylesheet.cssRules;

    if ((rules) && (rules.length > 0))
    {
        for (var j = 0; j < rules.length; j++)
        {
            if (rules[j])
            {
                // Imported Stylesheets
                if ((rules[j].styleSheet) && (rules[j].styleSheet.cssRules) && (rules[j].styleSheet.cssRules.length > 0) && (stylesheetIsScreen(rules[j].styleSheet.media)))
                {
                    if ((value.length > 0) && (/[^;]\s*$/.test(value)))
                    {
                        value += ";";
                    }
                    
                    value += stylesheetProperty(rules[j].styleSheet, selector, property);
                }
                else if ((rules[j].selectorText) && (rules[j].style) && (rules[j].selectorText == selector))
                {
                    // Looking for a specific CSS Property
                    if ((property != null) && (property.trim().length > 0))
                    {
                        if (rules[j].style.getPropertyValue)
                        {
                            if (rules[j].style.getPropertyValue(property) != null)
                            {
                                if ((value.length > 0) && (/[^;]\s*$/.test(value)))
                                {
                                    value += ";";
                                }

                                value += rules[j].style.getPropertyValue(property);
                            }
                        }
                        else if ((rules[j].style.cssText) && (rules[j].style.cssText.length > 0))
                        {
                            var matches = (rules[j].style.cssText.match(new RegExp('(?:^|\\s+)' + property + '\\s*:\\s*([^\\s]+)\\s*(?:$|;)', 'gim')));
                            
                            if ((matches) && (matches.length > 0))
                            {
                                if ((value.length > 0) && (/[^;]\s*$/.test(value)))
                                {
                                    value += ";";
                                }
                                
                                value += matches[matches.length - 1].replace(new RegExp('(?:^|\\s+)' + property + '\\s*:\\s*', 'gim'), '');
                            }
                        }
                    }
                    // Looking for all CSS Properties for this Selector
                    else if ((rules[j].style.cssText) &&  (rules[j].style.cssText.length > 0))
                    {
                        value += rules[j].style.cssText;
                    }
                }
            }
        }
    }
    
    return value;
}

/* MegaMenu */

(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// if e.type == "mouseenter"
			if (e.type == "mouseenter") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "mouseleave"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
	};
})(jQuery);

$(document).ready(function() { 						  
			

//On Hover Over
function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in
    (function($) {
        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            $(this).find("ul").each(function() { //for each ul...
                rowWidth += $(this).width(); //Add each ul's width together
            });
        };
    })(jQuery); 

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

        $(this).find(".row").each(function() {	//for each row...
            $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rowWidth}); //Set Width

    }
}
//On Hover Out
function megaHoverOut(){
  $(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
      $(this).hide();  //after fading, hide it
  });
}


//Set custom configurations
var config = {
     sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
     interval: 100, // number = milliseconds for onMouseOver polling interval
     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
     timeout: 500, // number = milliseconds delay before onMouseOut
     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
};

$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations


}); 

