/* define a new shortcut for jQuery to prevent conflict with Prototype */
jQuery.noConflict(); 

// Creating custom :external selector
jQuery.expr[':'].external = function(obj){
    return (obj.href.indexOf('mailto:') < 0) &&   // make sure the link isn't a mailto:
           (obj.href.indexOf('msrb.org') < 0) &&  // make sure it's not a link to msrb.org
           (jQuery(obj).attr('href') != undefined) && // make sure it's not an <a> tag
           (obj.hostname != location.hostname);   // make sure the domain in the link is not the domain we're on
};

/* define the MSRB object to avoid conflicts with any third party code */
var MSRB = {};

/* define all configurable variables used for the MSRB site */
MSRB.vars = {
    hideDelayTimer: [],
    
    ruleNavOffset: 0,
    ruleUtilityOffset: 0,
    
    homepageSlideshowDelay: 8, /* 0 for no auto rotation */
    
    mainNavDelayOver: 0,
    mainNavDelayOut: 0.75,
    mainNavTimerOver: '', /* a setTimeout var to start the mouseOver event of the main nav. */
    mainNavTimerOut: '',  /* a setTimeout var to start the mouseOut  event of the main nav. */
    
    utilityHTML: '<a class="print"></a><a href="/pdf.aspx?url=' + location.href + '" class="utilityPDF" target="_blank"></a><a class="addthis_button_email"></a><a href="http://addthis.com/bookmark.php?v=250&amp;pub=xa-4ac0be175257e7a7" class="addthis_button_expanded"></a>'
};

/* define all reusable functions for the MSRB site */
MSRB.functions = {
    /* form validation */
    emailValidation: function(str){
        var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (str.match(emailRegEx)) {
            return 1;
        }
        else {
            return 0;
        }
    },
    
    /* start the timer to actually hide the navigation */
    helpHide: function(i) {
        if (MSRB.vars.hideDelayTimer[i]) {
            clearTimeout(MSRB.vars.hideDelayTimer[i]);
        }
        MSRB.vars.hideDelayTimer[i] = setTimeout(function() {
            MSRB.vars.hideDelayTimer[i] = null;
            MSRB.functions.helpHideForReals(i);
        }, 1500);
    },
    
    /* hide the navigation */
    helpHideForReals: function(i) {
        var top = parseInt(jQuery('div.helpPopup').eq(i).css('top'));
        
        jQuery('div.helpPopup')
            .eq(i)
            .animate({ 
                    top: top-10,
                    opacity: 0.1
                }, 
                500,
                function(){
                    jQuery(this).hide();
                });
    },
    
    /* show the navigation */
    helpShow: function(i) {
        var objA = jQuery('a.help').eq(i);
        var objDIV = jQuery('div.helpPopup').eq(i);
        
        if (MSRB.vars.hideDelayTimer[i]) {
            clearTimeout(MSRB.vars.hideDelayTimer[i]);
        }
        else {
            var left = jQuery(objA).offset().left;
            var top = jQuery(objA).offset().top;
            
            var height = jQuery(objDIV).height();
            var width = jQuery(objDIV).width();
            
            jQuery('div.helpPopup')
                .eq(i)
                .css('top', (top-height-5+10) + 'px')
                .css('left', (left-(width/2)+3) + 'px')
                .css('opacity', '0.1')
                .css('display', 'block')
                .animate({ 
                        top: top-height-5,
                        opacity: 1
                    }, 
                    300,
                    function(){
                        jQuery(this).show();
                    });
        }
    },
    
    /* main navigation mouseover */
    mainNavMouseOver: function(obj, i) {
        jQuery('#navMain li.hover').removeClass('hover');
        jQuery(obj).addClass('hover');
        
        // hide SELECT form elements if IE6
        if(jQuery.browser.msie === true && parseInt(jQuery.browser.version) < 7) {
            jQuery('select').css('visibility', 'hidden');
        }
    },
    
    /* main navigation mouseout */
    mainNavMouseOut: function() {
        jQuery('#navMain li.hover').removeClass('hover');
        
        // show SELECT form elements if IE6
        if(jQuery.browser.msie === true && parseInt(jQuery.browser.version) < 7) {
            jQuery('select').css('visibility', 'visible');
        }
    }
};



/* jQuery DOMdocument.ready */
jQuery(document).ready(function(){
/* HTML; add HTML to the page that is not content. this HTML either purely decorative, or purely functional (requiring JS to work). */
    jQuery('div.utility').html(MSRB.vars.utilityHTML); /* add utility HTML to the page */
    
    /* external links */
    jQuery('#content a:external').not('div.utility a').addClass('external');
    
    
/* Interactions; define the intereactive components of the page. */
    jQuery('a.print').click(function(){
        window.print();
        return false;
    });
    /* slideshow */
    jQuery('div.leadStoryContainer')
        .before('<div class="leadStoryNav"><span class="playPause"><span class="play">&nbsp;</span></span></div>') 
        .cycle({ 
            fx:     'fade', 
            speed:  'fast', 
            timeout: MSRB.vars.homepageSlideshowDelay * 1000, 
            pager:  'div.leadStoryNav' 
        })
        .prev()
        .find('span.playPause span')
        .click(function(){
            if(jQuery(this).is('.play')) {
                jQuery(this).removeClass('play').addClass('pause');
                jQuery(this).parent().parent().parent().find('div.leadStoryContainer').cycle('pause');
            }
            else {
                jQuery(this).removeClass('pause').addClass('play');
                jQuery(this).parent().parent().parent().find('div.leadStoryContainer').cycle('resume');
            }
        });
    
    /* help popup. each help popup is loaded into the page after the page loads */
    jQuery('a.help').each(function(i) {
        jQuery(this).data('i', i); /* add a number to the A so we know what help div to show/hide */
        var url = jQuery(this).attr('href');
        
        /* add help pop up DIV */
        jQuery('body')
            .append('<div class="helpPopup"><div class="helpPopupContent"></div></div>')
            .find('div.helpPopup')
            .eq(i)
            .mouseover(function(){
                MSRB.functions.helpShow(i);
                return false;
            })
            .mouseout(function(){
                MSRB.functions.helpHide(i);
                return false;
            });
        
        /* load help pop up content */
        jQuery('div.helpPopupContent').eq(i).load(url);
        
        /* add events to the A */
        jQuery(this)
            .click(function(){
                MSRB.functions.helpShow(i);
                return false;
            })
            .mouseover(function(){
                MSRB.functions.helpShow(i);
                return false;
            })
            .mouseout(function(){
                MSRB.functions.helpHide(i);
                return false;
            });
    });
    
    /* generic form validation */
    jQuery('#content form').submit(function(){
        jQuery('div.error').removeClass('error');
        
        jQuery(this).find('input,select,textarea').each(function(i){
            var parent = jQuery(this).parent();
            if(jQuery(parent).find('span.error').size() > 0 && jQuery(this).attr('value') === ''){
                jQuery(parent).addClass('error');
            }
            if(jQuery(parent).find('input.email').size() > 0) {
                if(MSRB.functions.emailValidation(jQuery(this).attr('value')) === 0) {
                    jQuery(parent).addClass('error');
                }
            }
        });
        
        /* if we no DIV.erros are visible, we don't have any errors */
        if(jQuery('div.error:visble').size() === 0) {
            return true;
        }
        else {
            scroll(0,0);
            jQuery('p.errorMessage').slideDown();
            return false;
        }
    });
    
    /* add hover events to the main/primary navigation */
    jQuery('#navMain>ul>li').each(function(i){
        jQuery(this).hover(
            /* mouseOver */
            function(){ 
                var obj = jQuery(this);
                clearTimeout(MSRB.vars.mainNavTimerOut);
                MSRB.vars.mainNavTimerOver = setTimeout(
                    function() {
                        MSRB.functions.mainNavMouseOver(obj, i);
                    },
                    MSRB.vars.mainNavDelayOver * 1000
                );
            },
            /* mouseOut */
            function(){ 
                clearTimeout(MSRB.vars.mainNavTimerOver);
                MSRB.vars.mainNavTimerOut = setTimeout(
                    function() {
                        MSRB.functions.mainNavMouseOut();
                    },
                    MSRB.vars.mainNavDelayOut * 1000
                );
            }
        );
    });
    
    /* links classified as external - add a popup interstitial layer informing the user they are leaving the site */
    jQuery('a.external').click(function(){
        var url = jQuery(this).attr('href');
        jQuery('body')
            .append('<div id="externalOverlay">&nbsp;</div><div id="externalWindow"><div id="externalContent"><h2>Warning</h2><p>This link will redirect you to an external site. Click no to stay in mrsb.org</p><p>Would you like to continue?</p><div class="clearfix"><div class="fieldSubmit"><input type="submit" value="No" onclick="jQuery(\'#externalOverlay, #externalWindow\').remove();" /></div><div class="fieldSubmit"><input type="submit" value="Yes" onclick="location.href=\'' + url + '\';" /></div></div></div></div>')
            .find('#externalOverlay')
            .click(function(){
                jQuery('#externalOverlay, #externalWindow').remove();
            })
            .end()
            .find('#externalWindow')
            .fadeIn();
        return false;
    });


/* Visual Clean-Up; */
    /* set the widths of each tab */
    jQuery('div.tabs').each(function(i){
        var divWidth = jQuery(this).width();
        var num = jQuery(this).find('a').size();
        var padding = 14; //padding, border, and margin
        var tabWidth = parseInt((divWidth/num)-padding);
        
        jQuery(this).find('a').css('width', tabWidth);
        jQuery(this).find('a:last').css('width', tabWidth + 2); // add 2 because of the margin
        
        var diff = divWidth - ((tabWidth+padding)*num);
        if(diff < 0) {
            jQuery(this).find('a:last').css('width', tabWidth - diff + 2);
        }
        else if(diff > 0) {
            jQuery(this).find('a:last').css('width', tabWidth + diff + 2);
        }
    });
    
    /* last A; border is removed through CSS */
    jQuery('div.nav a:last').addClass('last');
    
    /* add spacing above each anchor point in the ruleContent so the Utility DIV doesn't overlap the title */
    jQuery('div.interpretationContent').find('*[id]').each(function(i){
        //jQuery(this).css('padding-top', '30px');
    });
    
    /* non-standards browser cleanup */
    jQuery('li:last-child').addClass('last-child');
    jQuery('li:first-child').addClass('first-child');
    
    /* flag to allow the CSS to know JS is enabled */
    jQuery('body').addClass('wjs'); 
    
    /* IE specific CSS flag */
    if(jQuery.browser.msie == true) {
        jQuery('body').addClass('msie');
    }
    
    /* Firefox 2 specific CSS flag */
    if(jQuery.browser.mozilla == true && jQuery.browser.version.substr(0,3) == '1.8') {
        jQuery('body').addClass('ff2');
    }
});

/* Interpretive Notices Page Navigation */
jQuery(function($){
    /* users may come to the page with a predefined piece of content linked to show/hide other content */
    jQuery('div.interpretationNav').each(function(){
        /* hide/show content based on the nav clicked */
        jQuery(this).find('a').click(function(){
            var obj = jQuery(this).attr('href');
            if(obj != '#_all') {
                jQuery('div.interpretationContent>div[id]').hide();
                jQuery(obj).show();
            }
            else {
                jQuery('div.interpretationContent>div[id]').show();
            }
        });
        
        // define the anchor point
        var hash = jQuery.url.attr('anchor');
        // if there is a hash in the URL, click the link it's associated with (interaction defined above)
        if(hash) {
            jQuery(this).find('a[href$=#' + hash + ']').click(); // act like the user clicked on the left nav
            window.scroll(0,0); // user is coming to the page for the first time, let them see the whole page (doesn't work in all browsers)
        }
    });
});

/* Interpretive Notices Utility Bar */
jQuery(function($){
    /* persistant rule Navigation */
    if(jQuery('div.interpretationUtility').size() > 0) {
        /* add spacing above each anchor point in the the parent so the Utility DIV doesn't overlap the title */
        jQuery('div.interpretationUtility').parent().find('div[id]').each(function(){
            if(jQuery.browser.msie == true && parseInt(jQuery.browser.version) == 7) {
                jQuery(this).prepend('<p style="margin: 0;">&nbsp;<br>&nbsp;</p>');
            }
            else {
                jQuery(this).css('padding-top', '30px');
            }
        });
    }
});

/* Rule Page Navigation */
jQuery(function($){
    if(jQuery('div.ruleNav').size() > 0) {
        /* add spacer so parent DIV doesn't collapse */
        jQuery('div.ruleNav').parent().append('&nbsp;'); 
        
        /* define original offset */
        MSRB.vars.ruleNavOffset = jQuery('div.ruleNav').offset().top;
    
        /* if we scroll past it's original offset, set it to position: fixed. */
        jQuery(window).bind('scroll', function(){
            if(MSRB.vars.ruleNavOffset < jQuery(window).scrollTop()) {
                var obj = jQuery('div.ruleNav');
                if(jQuery(obj).css('position') == 'static') {
                    jQuery(obj)
                       .css('position', 'fixed')
                       .css('top', 0);
                }
            }
            if(MSRB.vars.ruleNavOffset > jQuery(window).scrollTop()) {
                var obj = jQuery('div.ruleNav');
                if(jQuery(obj).css('position') == 'fixed') {
                    jQuery(obj)
                       .css('position', 'static');
                }
            }
        });
    }
});

/* Rule Page Utility Bar */
jQuery(function($){
    /* persistant rule Navigation */
    if(jQuery('div.ruleUtility').size() > 0) {
        /* add spacing above each anchor point in the the parent so the Utility DIV doesn't overlap the title */
        jQuery('div.ruleUtility').parent().find('div[id]').each(function(){
            if(jQuery.browser.msie == true && parseInt(jQuery.browser.version) == 7) {
                jQuery(this).prepend('<p>&nbsp;<br>&nbsp;</p>');
            }
            else {
                jQuery(this).css('padding-top', '30px');
            }
        });
        
        /* define original offset */
        MSRB.vars.ruleUtilityOffset = jQuery('div.ruleContent').offset().top;
    
        /* if we scroll past it's original offset, set it to position: fixed. */
        jQuery(window).bind('scroll', function(){
            if(MSRB.vars.ruleUtilityOffset < jQuery(window).scrollTop()) {
                var obj = jQuery('div.ruleUtility');
                if(jQuery(obj).css('position') == 'static') {
                    jQuery(obj)
                       .css('position', 'fixed')
                       .css('top', 0)
                       .parent()
                       .prepend('<div class="utilityPlaceholder"></div>');
                }
            }
            if(MSRB.vars.ruleUtilityOffset > jQuery(window).scrollTop()) {
                var obj = jQuery('div.ruleUtility');
                if(jQuery(obj).css('position') == 'fixed') {
                    jQuery(obj)
                       .css('position', 'static')
                       .parent()
                       .find('div.utilityPlaceholder')
                       .remove();
               }
           }
        });
    }
});

function clickButton(e, buttonID)
{
    var evt = e ? e : window.event;
    var bt = document.getElementById(buttonID);
    if(bt)
    {
        if(evt.keyCode == 13)
        {
            bt.click();
            return false;
        }
    }
}
