// object to hold all the ABC configurations;
var abc = {};

// variables for the used plugins;
abc.v = {
audioPlayerSWF: '/_res/swf/audioPlayer.swf',
jwPlayerSWF: '/_res/swf/player.swf',
jwPlayerXML: '/_res/img/jwplayer/glow/glow.xml'
};

// a container for functions;
abc.f = {};

// redefine the jQuery shortcut because Coveo loads jQuery as well (and would overwrite all the plugins we load);
abc.f.jquery = jQuery.noConflict();

// everything needs to be in an init function because this needs to be called after the DOM is ready for Coveo;
abc.f.init = function(){
	// Try/catch: http://w.sharethis.com/button/buttons.js is sometimes unavailable
	// this keeps it from choking the whole file.
		try{
			stButtons.locateElements();
		}
		catch(e){
		 //catch and just suppress error
		}
	//try{stLight.onReady();} catch(err){console.log(err);}
	
	// apply class to body if browser is IE.
	abc.f.jquery(function($){
		if ($.browser.msie) {
			$('body').addClass('msie');
			$('body').addClass('msie' + $.browser.version.charAt(0));
		}
	});

    /* allows the enter key to submit forms; */
    abc.f.jquery(function($){
        $('input[type=text]').keydown(function(e) {
            if(e.which || e.keyCode) {
                if ((e.which === 13) || (e.keyCode === 13)) {
                    //find the next input button in the DOM and click it
                    $(this).parent().find('input[type=submit]').click();
                    return false;
                }
                else {
                    return true;
                }
            }
        });
    });

    // let the CSS know JS is enabled;
    abc.f.jquery(function($){
        $('html').removeClass('nojs');
    });
	
    /* need to remove all inline styles on TABLEs; 
       restricting it to the TABLE tag because the other inline styles can be targeted through CSS; */
    abc.f.jquery(function($){
        $('table').removeAttr('style').removeAttr('align');
    });
    
	// addresses "phantom tab", see sifter item 8446
	abc.f.jquery(function($){
		$('div.tabs')
			.children()
			.children()
			.children()
			.children()
			.each(
				function(){		
					if($(this).text().length===0){
						$(this).css('display','none');
					}
				});
	});
	
	
	// Sifter item 9013
	// Replaces break tag with a pipe character following date so it displays inline with other content in You May Also Like section
	abc.f.jquery(function($){
		$('div#maincontent_0_pnlYouMayAlso').children().children().children('p.meta').children('br').replaceWith('&#124;');
	});


	// addresses wrapping issue per sifter item 9033; CSS fix works in all browsers except IE7 and below
	abc.f.jquery(function($){
		 if (($.browser.msie) && ($.browser.version < 8)) {
			 $('div#contentMainNav').children('ul').children().css('display', 'inline');
		 }
	});	
	
    // colorbox plugin, overlay for video/login/etc;
    abc.f.jquery(function($){
        function isAudioPlayer(){
            $('a.audioPlayer').each(function(i){
                /* setup MP3 Player; */
                AudioPlayer.setup(abc.v.audioPlayerSWF, {  
                    width: 460, 
                    transparentpagebg: 'yes',  
                    bg: '104354',             // Background
                    leftbg: '03314B',         // Speaker icon/Volume control background
                    lefticon: 'ffffff',       // Speaker icon
                    voltrack: 'ffffff',       // Volume track
                    volslider: '999999',      // Volume slider
                    rightbg: '274754',        // Play/Pause button background
                    rightbghover: '274754',   // Play/Pause button background (hover state)
                    righticon: 'ffffff',      // Play/Pause icon
                    righticonhover: 'ffffff', // Play/Pause icon (hover state)
                    loader: 'ffffff',         // Loading bar
                    track: 'cccccc',          // Loading/Progress bar track backgrounds
                    tracker: '999999',        // Progress track
                    border: '0b4c61',         // Progress bar border
                    skip: '167894',           // Previous/Next skip buttons
                    text: 'ffffff'            // Text
                });
                
                var id = 'jsAudioPlayer' + i;
                var url = $(this).attr('href');
                
                $(this).attr('id', id);
                
                
                AudioPlayer.embed(id, {
                    soundFile: url
                });
            });
        }
        
        isAudioPlayer();
        
        /* setup JW Player; */
        function isJWPlayer(){
            if($('#jwplayer').length){
                jwplayer('jwplayer').setup({
                    //flashplayer:    abc.v.jwPlayerSWF,
                    skin:            abc.v.jwPlayerXML,
                    modes: [
										   {type: 'html5'},
										   {type: 'flash', src: abc.v.jwPlayerSWF},
										   {type: 'download'}
										]
                });
                //specific class for player overlay
                $('#cboxContent').addClass('playerContainer');
            }
        }
        
        isJWPlayer();
    
        $('a.loginLink').colorbox({
            width: '270px', 
            height: '350px', 
            iframe: true,
            scrolling: false
        });
            
        $('a.ajaxLink, h3.ajaxLink a')
            .removeAttr('onclick')
            .colorbox({
                height: '10000px',
                innerHeight: '10000px',
                initialHeight: '10000px',
                scrolling: false,
                onComplete: function(){
                    isJWPlayer();
                    isAudioPlayer();
                    
                    if($('span.url input').size() > 0) {
                        $('span.url input').val(window.location.href.toString());
                    }
                    
                    //is this a log in box? - specific class for log in overlay
                    if($('.formPopup').length) {
                        $('#cboxContent').addClass('formContainer');
                    }
                    
                    //not going to use the default close button so we will hijack it
                    if($('#chartOverlay').length) {
                        $('#cboxContent').addClass('chartContainer');
                        //$('#chartOverlay').css('width', $('#chartOverlay img').width());
                        if($('#chartOverlay .close a').length){
                            $('#chartOverlay .close a').click(function(e){
                                e.preventDefault();
                                $('#cboxClose').click();
                            });
                        }
                    }
                    //$.colorbox.resize(); // resize was killing the viewport because the videos haven't loaded yet;
                },
                onClosed: function(){
                    //clean up our classes that might have been added
                    $('#cboxContent').removeClass('playerContainer').removeClass('formContainer');
                },
                onCleanup: function(){ 
                    //if(jwplayer('jwplayer')) {
                    //    (typeof jwplayer('jwplayer') == 'object') ? jwplayer('jwplayer').destroy() : 0; 
                    //}
                }
            });
    });
    
    // accordion toggles for forms in the right rail;
    abc.f.jquery(function($){
        $('h2.toggle, h4.toggle')
            .each(function(){    
                if(!$(this).hasClass('opened')) {
                     $(this).addClass('closed').next().css('display','none');
                }
            })
            .click(function(e){
                e.preventDefault();
                if($(this).hasClass('opened')){
                    $(this).removeClass('opened').addClass('closed');
                    if($.browser.msie && parseInt($.browser.version, 10) < 8){
                        $(this).next().hide();
                    }
                    else{
                        $(this).next().slideUp(400);
                    }
                } 
                else {
                    $(this).removeClass('closed').addClass('opened');
                    if($.browser.msie && parseInt($.browser.version, 10) < 8){
                        $(this).next().show();
                    }
                    else{
                        $(this).next().slideDown(400);
                    }
                }
            });
    });
    
    // study table of contents;
    abc.f.jquery(function($){
        $('div.exec-toc li.toggle')
            .append('<span />')
            .each(function(){
                if($(this).hasClass('opened') === false) {
                     $(this)
                        .addClass('closed')
                         .find('ul')
                         .css({display:'none',zoom:'1'});
                }
            })
            .find('span')
            .click(function(e){
                e.preventDefault();
                e.stopPropagation();
                if($(this).parent().hasClass('opened')){
                    $(this)
                        .parent()
                        .removeClass('opened')
                        .children('ul')
                        .slideUp('400')
                        .parent()
                        .addClass('closed');
                }
                else {
                    $(this)
                        .parent()
                        .removeClass('closed')
                        .children('ul')
                        .slideDown('400',function(){
                            $(this).parent().addClass('opened');
                        });
                }
            });
    });
    
    // select all/none controls, for checkboxes in the right rail;
    abc.f.jquery(function($){
        // check all checkboxes in this div.block;
        $('ul.selectThis li.all').click(function(e){
            e.preventDefault();
            $(this)
                .parent()
                .parent()
                .find('input:checkbox')
                .attr('checked','checked');
        });
        
        // uncheck all checkboxes in this div.block;
        $('ul.selectThis li.none').click(function(e){
            e.preventDefault();
            $(this)
                .parent()
                .parent()
                .find('input:checkbox')
                .removeAttr('checked');
        });
        
        // uncheck all checkboxes in the right rail;
        $('a.clearAll a').click(function(e){
            e.preventDefault();
            $('#contentRelated input:checkbox').removeAttr('checked');
        });
    });
    
    // jquery ui datepicker;
    abc.f.jquery(function($){
        var dates = $('#startdate,#enddate').datepicker({
                onSelect: function( selectedDate ) {
                    var option = this.id === "startdate" ? "minDate" : "maxDate",
                    instance = $(this).data("datepicker");
                    date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings );
                    dates.not(this).datepicker("option", option, date);
                }
        });
    });
    
    // jquery ui tabs;
    abc.f.jquery(function($){
        $('.tabs').tabs({ 
            fx: [
                { opacity: 'toggle', duration: 'fast' },
                { opacity: 'toggle', duration: 'fast' }
            ]
        });
    });
    
    // zebra striped tables;
    abc.f.jquery(function($){
        $('div.pad table').parent().removeClass('pad').addClass('zebra');
    });
    
    // make nested menus look like drop downs with a dropdown arrow class
    abc.f.jquery(function($){
        $('#navPersonal > li, #contentRelatedNav > li, #navLanguage > li, .yourTopics ul > li').each(function(){
            if($(this).children('ul').length) {
                $(this).addClass('dd');
            }
        });
    });
    
    // non-standards compliant browser support;
    abc.f.jquery(function($){
        $('tbody tr:odd').addClass('odd');
        $('tbody td:first-child, th:first-child').addClass('first');
        $('tbody td:last-child, th:last-child').addClass('last');
        
        $('ul li:last-child, .row .col13:last-child, .row .col12:last-child').addClass('last');
        $('ul li:first-child, .row .col13:first-child, .row .col12:first-child').addClass('first');
    });
    
    // hoverintent plugin, mouseover effects for navigation menus;
    abc.f.jquery(function($){
        $('ul#navPersonal > li, ul#contentRelatedNav > li, ul#navLanguage > li, .yourTopics ul > li').hoverIntent({
            sensitivity: 7,        // number = sensitivity threshold (must be 1 or higher)
            interval:    100,    // number = milliseconds of polling interval
            timeout:     100,    // number = milliseconds delay before onMouseOut function call
            over: (                // function = onMouseOver callback (required)
                function(){
                    $(this)
                        .children('ul:first')
                        .fadeIn(100)
                        .siblings()
                        .children('ul:first')
                        .fadeOut(50);
                }
            ),  
            out: (                // function = onMouseOut callback (required)
                function(){
                    $(this).children('ul:first').fadeOut(200);
                }
            )
        });
        // cancel the default clicking behavior on the trigger elements for these dropdowns
        $('ul#contentRelatedNav > li > a, .yourTopics > ul > li > a').click(function(){
            this.blur();
            return false;
        });
        $('ul#navPersonal > li > a').not('ul#navPersonal > li.last > a').click(function(){
            this.blur();
            return false;
        });
    });
    
    // form field placeholder to value replacement for no placeholder support
    abc.f.jquery(function($){
        $('input[type=text]').each(function(){
            //if we have a placeholder
            if (($(this).attr('value') === '') && ($(this).attr('placeholder'))) {
                var tmp = $(this).attr('placeholder');
                //init the value to the placeholder
                $(this)
                    .attr('value', tmp)
                    .focus(function(){
                        //if we are using placeholder empty the container
                        if($(this).attr('value') === tmp){
                            $(this).attr('value', '');
                        }
                    })
                    .blur(function(){
                        //if nothing was added repopulate with placeholder attrib value
                        if($(this).attr('value') === ''){ 
                            $(this).attr('value', tmp);
                        }
                    });
            }
        });
    });
    
    // star rating plugin, used on comment forms;
    abc.f.jquery(function($){
        $('.star').rating();
    });
    
    // search results automatically submit form (there's no submit button);
    abc.f.jquery(function($){
        $('div.searchResultsFilter select').change(function(){
            $(this).parents('form').submit();
        });
    });
    
    // tweet feed plugin, used in the right rail;
    abc.f.jquery(function($){
        $('div.tweets').tweet({
            join_text:              'auto',
            username:               'daily_briefing',
            count:                   2,
            auto_join_text_default: 'we said,', 
            auto_join_text_ed:      'we',
            auto_join_text_ing:     'we were',
            auto_join_text_reply:   'we replied',
            auto_join_text_url:     'we were checking out',
            loading_text:           'loading tweets...'
        });
    });
    
    // hero image + slideshow;
    abc.f.jquery(function($){
        $('div.hero').each(function(i){
            // find out if there are slides;
            var c = $(this).find('img').size();
            // if so, set the height of the container - height of the slides are variable per instance;
            if(c > 0) {
                var h = $(this).find('img').eq(0).attr('height');
                //$(this).css('height', h + 'px'); // commented out because the IMG is not display: block;
            }
            // if there are more than one slide - initialize jQuery cycle;
            if(c > 1) {
                $(this)
                    .append('<div class="pager pager-' + i + '" />') // making sure incase we use more than one cycle on a page we have unique pagers
                    .cycle({
                        fx:        'fade', 
                        pager:     'div.pager-' + i,
                        slideExpr: 'img',
                        speed:      750,
                        timeout:    8000
                    });
            }
        });
    });
    
    // directory experts (headshot with content overlay on mouseover);
    abc.f.jquery(function($){
        $('div.expertList div.expertListItem')
            .hover(
                function(){
                    $(this)
                        .find('div.expertListItemDetail')
                        .animate(
                            { top: 0 }, 1000
                        );
                },
                function(){
                    $(this)
                        .find('div.expertListItemDetail')
                        .animate(
                            { top: 142 }, 1000
                        );
                }
            );
    });
    
    // identify featured search results (via a hidden image);
    abc.f.jquery(function($){
        $('img.featuredSearchResultIcon').each(function(){
            $(this)
                .parents('div.searchResult')
                .addClass('searchResultFeatured');
        });
    });
    
    // print is configured, email and share are done via the ShareThis component;
    abc.f.jquery(function($){
        $('li.print a').click(function(e){
            e.preventDefault();
            window.print();
        });
        $('li.email a').click(function(e){
            e.preventDefault();
        });
        $('li.share a').click(function(e){
            e.preventDefault();
        });
    });
    
    // Go To Webinar link;
    abc.f.jquery(function($){
        var goToWebinar = function(){
            // create new form;
            var $form = $('<form action="https://www.gotomeeting.com/en_US/island/webinar/registration.flow" target="_blank" class="goToWebinarForm"></form>'),
                $div = $('div.goToWebinarFields');
            
            // remove the old form (may be present if the user has already clicked on this button);
            $('form.goToWebinarForm').remove();
            
            // insert the new form;
            $('body').append($form);
            
            // populate form field values; 
            $('div.goToWebinarValues input').each(function(i) {
                var $this = abc.f.jquery(this),
                    $input = abc.f.jquery('#' + $this.attr('class'));
                
                $input.val($this.val());
            });
            
            // insert form fields (clones of the .NET ones) into this new form;
            $form.append($div.clone());
            
            // submit the form;
            $form.submit();
        };
        
        // attach function to the button;
        $('a.goToWebinarButton').click(function(e){
            e.preventDefault();
            goToWebinar();
        });
    });
};

// onload initialize everything (can be called after load too);
abc.f.jquery(function($){
    abc.f.init();
});

