jQuery.noConflict();

jQuery(document).ready(function () {
    if (jQuery.browser.msie == false || jQuery.browser.version.substr(0, 1) > 6) {
        jQuery('.containerMainTab li')
		.focusin(function (e) {
		    jQuery(this)
				.data('hasFocus', true)
				.children('.containerDropDown').addClass('hover');
		})
		.focusout(function (e) {
		    var self = this;
		    jQuery(this).data('hasFocus', false);
		    setTimeout(function () {
		        if (!jQuery(self).data('hasFocus')) {
		            jQuery(self).children('.containerDropDown').removeClass('hover');
		        }
		    });
		});
    }
    var displaytimes = 2;
    for (var i = 0; i < displaytimes; i++) {
        setTimeout(function () {
            showAnimateLine();
        }, i * 11000);
    }
    getOutBoundLinks();
    jQuery(".readMore a").click(function (e) {
        e.preventDefault();
        window.open(this.href, 'popup', 'width=800,height=550, scrollbars,resizable=1');
    });
    jQuery(".contentBlock08 .contentBlock08a h3 a").click(function (e) {
        e.preventDefault();
        window.open(this.href, 'popup', 'width=800,height=550, scrollbars,resizable=1');
    });
    jQuery(".contentBlock13 li a").click(function (e) {
        e.preventDefault();
        window.open(this.href, 'popup', 'width=800,height=550, scrollbars,resizable=1');
    });

    jQuery('#textSize').fontSize({
        elem: '#mainContent',
        label: jQuery('#textSize span')[0].innerText
    });

    jQuery('div.tabs1').tabs({
        prepend: false
    });

    jQuery('div.tabs2').tabs({
        prepend: false
    });

    jQuery('div.tabs3').tabs({
        prepend: true,
        node: '.outerTabNode',
        content: 'outerTabContent',
        className: 'topLevelNav'
    });

    jQuery(document).ready(function () {
        jQuery('.listToSelect').listToSelect();
    });

    if (jQuery('.contentBlock13a').length != 0) {
        var timer = parseInt(jQuery('#refreshTime').val()) * 1000;
        //console.log(timer);
        if (jQuery('.contentBlock13a > ul').children().length > 1)
            iTimerID = setInterval(doRoll, timer);
    }

    jQuery('.openLightbox').each(function () {
        var $this = jQuery(this);
        jQuery(this).lightbox({
            close: '#profileLightboxClose',
            contents: jQuery('#lightboxContent')
        });
    });

    jQuery('.openLightboxImg').each(function () {
        var $this = jQuery(this);
        jQuery(this).lightbox({
            contents: '<p><img src="' + $this.attr('href') + '"/ ></p>',
            close: '#profileLightboxClose',
            trigger: $this
        });
    });
    jQuery('.customSelect').customSelect();

    /* Ensures all pods within a row are the same height */
    jQuery('.contentBlock08').each(function () {
        var $podContainer = jQuery(this);
        if (jQuery(this).find('.homepagePod').length > 1) {
            var heights = [];
            jQuery(this).find('.homepagePod').each(function (i) {
                heights.push(jQuery(this).height());
            });
            var max = Math.max.apply(null, heights) - 20;

            $podContainer.find('.homepagePod').each(function (i) {
                jQuery(this).height(max);
            });

        }
    });
    /* End of pod heights */

    buildTopNav();
    buildHomepageBanner();

    jQuery('.treeView').treeView({
        trigger: '.treeViewTrigger',
        content: '.treeViewContent'
    });

});

function showAnimateLine() {
    jQuery(".bganimation").css({ width: 0, opacity: 0 });
    jQuery(".bganimation_cover").css({ width: 0 });

    setTimeout(function () {
        jQuery(".bganimation").animate({ width: "757px", opacity: 1 }, 2000);
    }, 1000);
}

function buildHomepageBanner() {
    var $homepageBanner = jQuery('.homepageBanner');
    if ($homepageBanner.length) {
        var $contentBlockInner = $homepageBanner.find('.contentBlockInner'),
			$homeHeader = $homepageBanner.find('.homeHeader'),
			$bannerContentItem = $homepageBanner.find('.bannerContentItem');

        $contentBlockInner.css('overflow', 'auto');

        $bannerContentItem.not(':first').hide();

        $homeHeader.appendTo($contentBlockInner)
			.find('a').click(function (e) {
			    e.preventDefault();

				jQuery('.homeHeader h2').removeClass('selected');
				jQuery(this).parent().addClass('selected');

			    var index = $contentBlockInner.find('.homeHeader a').index(this);
			    $bannerContentItem.hide().eq(index).show();
			});

		jQuery('.homeHeader h2:first').addClass('selected');
    }
}

function buildTopNav() {
    var isOpen = false,
		index = 0,

		animDuration = 0,
		closedHeight = jQuery('.mainTab').eq(0).height(),
		openHeight = closedHeight + jQuery('.containerSubNav').eq(0).height();
    var topNavTimer, timerDuration = 100;
    jQuery('#topNav').height(closedHeight)
		.find('.containerSubNav').hide();

    jQuery('#topNav').hover(function () {


    }, function () {
        if (isOpen) {
            jQuery(this).animate({ height: closedHeight }, function () {
                jQuery('#topNav').find('.containerSubNav').hide();
            }
            );
            isOpen = false;
        }
    });
    jQuery('.mainTab').mouseenter(function () {
        index = jQuery('.mainTab').index(this);
        if (!isOpen) {

            topNavTimer = window.setTimeout(function () {
                jQuery('#topNav').animate({ height: openHeight }, function () {
                    isOpen = true;
                }
            );
                jQuery('.containerSubNav').hide()
			.eq(index).show();
            }, timerDuration);
        }
        else {
            jQuery('.containerSubNav').hide()
			.eq(index).show();

        }

    }).mouseleave(function () {
        window.clearTimeout(topNavTimer);
    }); ;



}

var listIndex = 0;

function doRoll() {
    var list = jQuery('.contentBlock13a > ul');

    var listLength = jQuery(list).children();
    if (listIndex != (listLength.length - 1)) {
        jQuery(list).animate({
            'margin-top': '-=30'
        }, 3000, function () {
            listIndex = listIndex + 1;
        });
    } else {

        jQuery(list).animate({
            'margin-top': '-=15'
        }, 1500, function () {

            jQuery(this).css({ 'margin-top': '30px' });

            jQuery(this).animate({
                'margin-top': '-=30'
            }, 1500, function () {
                listIndex = 1;
            });

        });

    }
}

function showHide(id) {
    jQuery('#' + id).slideToggle('slow');
}

(function (jQuery) {
    jQuery.fn.lightbox = function (options) {
        var defaults = {
            contents: '',
            className: '',
            close: '.close',
            trigger: '.openLightbox'
        };

        var opts = jQuery.extend(defaults, options),
			$overlay,
			$lightBox,
			$trigger = jQuery(opts.trigger);

        $trigger.click(function (e) {
            e.preventDefault();
            createLightbox();
        });

        jQuery(opts.contents).hide();

        function createLightbox() {
            jQuery(document.body).append(
				'<div id="profileLightboxContainer">' +
					'<div id="profileLightbox">' +
						'<div id="profileLightboxInner">' +
							'<div id="profileLightboxClose"><img src="/images/background/lightbox-close.png" /></div>' +
							jQuery(opts.contents).html() +
						'</div>' +
					'</div>' +
				'</div>'
			);

            $overlay = jQuery('#profileLightboxContainer');
            $lightBox = jQuery('#profileLightbox');

            $lightBox.css({
                'top': (jQuery(window).height() - $lightBox.height()) / 2 + 'px',
                'left': (jQuery(window).width() - $lightBox.width()) / 2 + 'px'
            });

            $lightBox.find(opts.close).click(function (e) {
                e.preventDefault();
                close();
            });
        }

        function close() {
            $overlay.remove();
            $lightBox.remove();
        }

        return $lightBox;
    }

})(jQuery);

function pickVideo(id) {
    if (location.search.substr(0, 4) != '?&i=') {
        location.search = '?&i=' + id;
    }
}

(function ($) {

    $.fn.customSelect = function (opts) {
        opts = $.extend({
            active: 'active',
            startValue: null,
            maxHeight: 300
        }, opts);

        return this.each(function (i) {
            var selectExists = true;
            if (!$(this).find('select').length) {
                selectExists = false;
            }

            var $this = $(this),
				$node = selectExists ? $this.find('select').remove() : $this.find('ul').remove(),
				$valueRegion = $('<div tabIndex="0" class="valueRegion"><div class="valueRegionInner"><div class="arrow"/></div></div>"').appendTo($this),
				$value = $('<div class="value" />').prependTo($valueRegion.find('.valueRegionInner')),
				$menu = $('<div class="customSelectMenu"><div class="customSelectMenuInner"><ul role="menu" id="menu' + i + '" /></div></div>').hide().appendTo($this),
				selectIndex = 0,
				changeCount = 0,
				scrollCount = 1,
				scrollTimer = null;

            if (selectExists) {
                if (typeof ($.fn.prop) == 'function') {
                    var selectIndex = $node.prop('selectedIndex');
                }
                else {
                    var selectIndex = $node.attr('selectedIndex');
                }
            }

            $node.find('option, li').each(function (i) {
                var className = '';
                if (i == $node.find('option, li').length - 1) {
                    className = 'last';
                }
                var $listItem = $('<li class="' + className + ' menuItem' + i + '" role="menuitem" aria-haspopup="menu' + i + '"><span>' + $(this).text() + '</span></li>').appendTo($menu.find('ul'));

                if ($(this).find('a').length) {
                    $listItem.html(
						'<span><a href="' + $(this).find('a').attr('href') + '">' + $(this).text() + '</a></span>'
					);
                }
            });

            var $scrollTop = $('<div class="scroll scrollTop" />'),
				$scrollBtm = $('<div class="scroll scrollBottom" />');

            if ($menu.height() > opts.maxHeight) {
                var $scrollRegion = $('<div class="scrollRegion" />')
						.append($menu.find('ul'))
						.css({
						    height: opts.maxHeight,
						    overflow: 'hidden',
						    position: 'relative'
						});
                $scrollTop
					.css('visibility', 'hidden')
					.hover(function () {
					    scrollMenu();
					}, function () {
					    clearInterval(scrollTimer);
					}),
				$scrollBtm
					.hover(function () {
					    scrollMenu(true);
					}, function () {
					    clearInterval(scrollTimer);
					});

                $menu.find('.customSelectMenuInner')
					.append($scrollRegion)
					.prepend($scrollTop)
					.append($scrollBtm);

                $menu.find('ul').css({
                    position: 'relative',
                    top: 0,
                    left: 0
                });


                $menu.show();
                if ($(window).height() <= $menu.outerHeight() + $valueRegion.outerHeight()) {
                    opts.maxHeight = ($(window).height() - ($menu.outerHeight() - $scrollRegion.height())) - ($valueRegion.outerHeight() + 40);
                    $scrollRegion.height(opts.maxHeight);
                }
                $menu.hide();
            }

            $valueRegion.click(function (e) {
                e.preventDefault();
                if ($menu.is(':visible')) {
                    highlight();
                    close();
                }
                else {
                    open();
                }
            });
            $(document).click(function (e) {
                if (!$.contains($this[0], e.target)) {
                    close();
                }
            });
            var $links = $menu.find('li');
            $links.each(function (i) {
                $(this)
					.click(function () {
					    selectIndex = i;
					    change();
					    $menu.hide();
					})
					.hover(function () {
					    selectIndex = i;
					    highlight();
					}, function () {
					    $(this).removeClass(opts.active);
					});
            });
            $valueRegion.keyup(function (e) {
                var keycode = e.keyCode,
					listSize = $menu.find('li').length - 1;
                if (keycode <= 40 && keycode >= 13) {
                    if ((keycode == 40) && (e.altKey)) { //alt & down key
                        if (!$menu.is(':visible')) {
                            open();
                        }
                    }
                    else if (((keycode == 38) && (e.altKey)) || (keycode == 27)) { //alt & up key or esc key
                        if ($menu.is(':visible')) {
                            close();
                        }
                    }
                    else if ((keycode == 40) || (keycode == 39)) { //down or right key
                        if (selectIndex < listSize) {
                            selectIndex++;
                        }
                    }
                    else if ((keycode == 38) || (keycode == 37)) { //up or left key
                        if (selectIndex > 0) {
                            selectIndex--;
                        }
                    }
                    else if ((keycode == 34) || (keycode == 35)) { //page down or end key
                        if (selectIndex < listSize) {
                            selectIndex = listSize;
                        }
                    }
                    else if ((keycode == 33) || (keycode == 36)) { //page up or home key
                        if (selectIndex > 0) {
                            selectIndex = 0;
                        }
                    }
                    else if (keycode == 13) { //enter key
                        close();
                        if (!selectExists) {
                            document.location = $menu.find('li a').eq(selectIndex).attr('href');
                        }
                    }
                    change();
                }
            });

            change();

            /**
            * Opens the menu
            */
            function open() {
                $menu.show();
                $valueRegion.addClass('open');
                $this.trigger('onopencustomselect');
            }
            /**
            * Closes the menu
            */
            function close() {
                $menu.hide();
                $valueRegion.removeClass('open');
                $this.trigger('onclosecustomselect');
            }
            /**
            * Scrolls the menu content
            * @param: down (boolean) - whether to scroll down or up
            */
            function scrollMenu(down) {
                scrollTimer = setInterval(function () {
                    var top = (10 * scrollCount) * -1;
                    if (down && top <= opts.maxHeight - $menu.find('ul').outerHeight()) {
                        clearInterval(scrollTimer);
                        $scrollTop.css('visibility', 'visible');
                        $scrollBtm.css('visibility', 'hidden');
                    }
                    else if (!down && top >= 0) {
                        clearInterval(scrollTimer);
                        $scrollTop.css('visibility', 'hidden');
                        $scrollBtm.css('visibility', 'visible');
                    }
                    else {
                        $menu.find('ul').css({
                            top: top
                        });
                        $scrollTop.css('visibility', 'visible');
                        $scrollBtm.css('visibility', 'visible');
                        if (down) { scrollCount++; }
                        else { scrollCount--; }
                    }
                }, 50);
            }
            /**
            * Remove the active class from all menu items and add it to the selected index
            */
            function highlight() {
                $links.removeClass(opts.active);
                $links.eq(selectIndex).addClass(opts.active);
            }
            /**
            * Change the selected value of the custom and real select boxes
            */
            function change() {
                $valueRegion.removeClass('open');
                if (changeCount == 0 && opts.startValue != null) {
                    $value.text(opts.startValue);
                }
                else {
                    $value.text($menu.find('li').eq(selectIndex).text());
                }
                if (selectExists) {
                    if (typeof ($.fn.prop) == 'function') {
                        $node.prop('selectedIndex', selectIndex);
                    }
                    else {
                        $node.attr('selectedIndex', selectIndex);
                    }
                }
                highlight();
                changeCount++;
            }
        });
    }

})(jQuery);

/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

(function ($) {

    $.fn.fontSize = function (opts) {

        var opts = $.extend({
            fontSizes: [100, 112.5, 118.75],
            label: 'Text Size:',
            startIndex: 0,
            imagePath: '/images/buttons/',
            elem: 'body'
        }, opts);

        var index = $.cookie('tdw.fontsize') || opts.startIndex;
        var d = new Date()

        var $widgets = this

        d.setFullYear(3000);

        function setSize(i) {
            var $elem = $(opts.elem);
            for (var j = 0; j < opts.fontSizes.length; j++) {
                $elem.removeClass('zoom' + j);
            }
            $elem.css('fontSize', opts.fontSizes[i] + '%').addClass('zoom' + i);
            enableDisable(i);
            $.cookie('tdw.fontsize', i, { expires: d, path: '/' });
        }

        function enableDisable(i) {
            $widgets.find('a.increase').addClass('disabled');
            $widgets.find('a.decrease').addClass('disabled');
            $widgets.find('a.reset').addClass('disabled');
            if (i < opts.fontSizes.length - 1) {
                $widgets.find('a.increase').removeClass('disabled');
            }
            if (i > 0) {
                $widgets.find('a.decrease').removeClass('disabled');
                $widgets.find('a.reset').removeClass('disabled');
            }
        }

        $widgets.each(function () {

            var $container = $(this);

            $container.append('<span>' + opts.label + '</span>');

            $('<a href="#" class="decrease" title="Decrease Text">\
				  <img alt="Decrease Text" src="' + opts.imagePath + 'font-minus.gif" width="15" height="13" />\
				  <img alt="Decrease Text" src="' + opts.imagePath + 'font-minus_disabled.gif" class="disabled" width="15" height="13" />\
			   </a>')
			.click(function (e) {
			    e.preventDefault();
			    if (index > 0) {
			        setSize(--index);
			    }
			})
			.appendTo($container);

            $('<a href="#" class="increase" title="Increase Text">\
				  <img alt="Increase Text" src="' + opts.imagePath + 'font-plus.gif" width="15" height="13" />\
			   	  <img alt="Increase Text" src="' + opts.imagePath + 'font-plus_disabled.gif" class="disabled" width="15" height="13" />\
			   </a>')
			.click(function (e) {
			    e.preventDefault();
			    if (index < opts.fontSizes.length - 1) {
			        setSize(++index);
			    }
			})
			.appendTo($container);

            $('<a href="#" class="reset" title="Reset Text Size">\
				  <img alt="Reset Text Size" src="' + opts.imagePath + 'font-reset.gif" width="15" height="13" />\
			   	  <img alt="Reset Text Size" src="' + opts.imagePath + 'font-reset_disabled.gif" class="disabled" width="15" height="13" />\
			   </a>')
			.click(function (e) {
			    e.preventDefault();
			    setSize(0);
			    index = 0;
			})
			.appendTo($container);

        });

        setSize(index);

        return $widgets;

    }

})(jQuery);

(function ($) {

    $.fn.listToSelect = function () {
        var $list = this.find('ul, ol'),
			$select = $('<select />'),
			locations = [];

        $list.find('li').each(function (i) {
            var $item = $(this);
            $select.append(
				'<option value="' + $item.find('a').attr('href') + '">' + $item.text() + '</option>'
			);
            locations.push($item.find('a').attr('href'));
            if (typeof locations[i] === 'undefined') {
                $select.attr('selectedIndex', i);
            }
        });

        $select.change(function () {
            if (locations[$select.attr('selectedIndex')]) {
                document.location = locations[$select.attr('selectedIndex')];

            }

        })


        $list.remove();
        this.append($select);
    }

})(jQuery);

(function ($) {
    $.fn.treeView = function (opts) {
        opts = $.extend({
            activeClass: 'open',
            duration: 'normal',
            event: 'click',
            trigger: 'li a',
            triggerAll: '.treeViewTriggerAll',
            content: 'ul'
        }, opts);

        return this.each(function (i) {
            var $self = $(this),
				$trigger = $self.find(opts.trigger),
				$triggerAll = $self.find(opts.triggerAll),
				$content = $self.find(opts.content),
				isOpenFAQ = false;

            $content.hide();

            $trigger.bind(opts.event, function (e) {
                e.preventDefault();
                var index = $trigger.index(this);
                $content.eq(index).slideToggle(opts.duration);
                $(this).toggleClass(opts.activeClass);
                isOpenFAQ = true;
            });

            $triggerAll.bind(opts.event, function (e) {
                e.preventDefault();
                $content.toggle(!isOpenFAQ);
                isOpenFAQ = !isOpenFAQ;
            });

        });

    };
})(jQuery);

