$(function() {
    //replaces body class
    $('body').removeClass('js-disabled').addClass('js-enabled');

    $('a.thickbox').each(function() {
        href = $(this).attr('href');
        // *************

        // *************
        $(this).attr('href', href.replace(/\?/, "?js=yes&"));
    });

    // png fix init /* COMMON */
    var isIE6 = $.browser.msie && $.browser.version < 7;

    if (isIE6) {
        $.ifixpng.pixel = '/magazine/graphics/pixel.gif';
        $('img[src$=".png"],input[src$=".png"]').not('.nofix').ifixpng();
    }

    // avatar popup functionality
    $('div.avatar').hover(function() {
        $(this).addClass('over').children('.avatar_options').show();
    }, function() {
        $(this).removeClass('over').children('.avatar_options').hide();
    });

    $('input.text[title]').setFormInstructions();

    //Homepage
    $("#content .popularLinksAreaContent").yaa({
        headClass: "popularLinksBoxExpander",
        contentClass: "accordionContent",
        slideActionUsed: false,
        initiallyHidden: false,
        onSlideCallback: function() {
            var sHashLink = "#popular-links", ele = $("#content .popularLinksAreaContent");
            ele = ele.toggleClass("expanded");
            ele.find(".popularLinksBoxExpander").toggleClass("expanded");
        }
    });

    var imgFolderBase = '../tesassets/images/carousel/',
		carouselImgPrefix = 'carousel_slot_',
		carouselImgCirclePrefix = 'b_home_carousel_page_',
		$carouselContainer = $('.carousel'),
		$carousel = $carouselContainer.children('.carousel-items'),
		$carouselWrapper = null,
		$fakeCarouselWrapper = null,
		isCarouselCreated = false,
		$textslot = $('div.carousel-text'),
		$paging = $('div.carousel-paging'),
    // Added "=" to hasAtrribute selector, bug for empty custom attributes: http://bugs.jquery.com/ticket/5637
		$content = $carousel
						.find('li')
							.has('a[data-MainLink=]')
							.addClass('clickable')
							.bind('click', function() {
							    window.location = $textslot.find('a[data-MainLink=]').attr('href');
							})
						.end()
						.find('div.content')
							.detach();

    // Create fake carousel for the first picture animation
    $fakeCarouselWrapper = $(document.createElement('div'));
    $fakeCarouselWrapper.attr('id', 'carouselLoadingWrap');

    $fakeCarousel = $(document.createElement('ul'));
    $fakeCarousel.css({ 'margin': '0px', 'float': 'none', 'position': 'absolute', 'top': '0px', 'left': '0px', 'width': '6500px', 'height': '285px' });

    var picNo = [$carousel.children('li').length, 1];
    for (i = 0; i < 2; i++) {
        $fakeCarouselItem = $(document.createElement('li')).css('background-image', 'url(' + imgFolderBase + carouselImgPrefix + picNo[i] + '.jpg)');
        $fakeCarousel.append($fakeCarouselItem);
    }

    $fakeCarouselWrapper.prepend($fakeCarousel);
    $carouselContainer.prepend($fakeCarouselWrapper);

    $fakeCarousel.animate({ 'left': '-=650px' }, {
        duration: 500,
        complete: function() {
            // swap carousels, but only after making sure the new carousel has been created
            var tries = 5;
            swapCarousels = function() {
                if (isCarouselCreated) {
                    $carousel.find('.first-item').css('display', 'list-item'); // show() wasn't being helpful in IE
                    $fakeCarouselWrapper.replaceWith($carouselWrapper);
                    loadCarouselPanel(0);
                }
                // just in case carousel can't load or is too slow to do so ... let's still try to show the first item
                else if (tries-- > 1) {
                    $carouselContainer.html('<ul class="carousel-items"><li class="first-item"></li></ul>');
                    $carouselContainer.find('.first-item').append($content[0]).show().find('h3, p').show();
                }
                else {
                    setTimeout(swapCarousels, 150);
                }
            };
            swapCarousels();
        }
    });
    // End of fake carousel


    // Carousel helpers
    var circleLinks = function() { //precache images
        var images = { black: null, white: null, red: null },
            fileExt = isIE6 ? '.gif' : '.png';

        for (var i in images) {
            images[i] = new Image();
            images[i].src = imgFolderBase + carouselImgCirclePrefix + i + fileExt;
        }

        return function(color) { return images[color].src; };
    } (),
		loadCarouselPanel = function(index, time) {
		    var fadeTime = (time || 500) / 2,
					color = $content.eq(index).find('[data-CircleColor]').attr('data-CircleColor') || 'black';

		    $paging.find('div').css('background-image', 'url(' + circleLinks(color) + ')');
		    $paging.find('div:nth-child(' + (index + 1) + ')').css('background-image', 'url(' + circleLinks('red') + ')');

		    $textslot.fadeOut(fadeTime, function() {
		        $textslot.empty().append($content[index]);
		        $textslot.fadeIn(fadeTime);
		    });
		};


    var carouselCreated = function() {
        $carousel.find('li').each(function(i) {
            var $this = $(this),
			index = parseInt($this.index());

            //set original index propery as the carousel plugin manipulates the DOM
            $this.data('index', index);

            //add style to attach background image for carousel members 
            $this.css('background-image', 'url(' + imgFolderBase + carouselImgPrefix + (index + 1) + '.jpg)');
        });

        $carouselWrapper = $carousel.parent('.caroufredsel_wrapper').detach();

        isCarouselCreated = true;
    }

    //init and configure carousel
    $carousel.carouFredSel({
        direction: 'left',
        circular: true,
        width: 650,
        items: {
            start: 0,
            visible: 1
        },
        onCreate: function() {
            carouselCreated();
        },
        scroll: {
            items: 1,
            onBefore: function($old, $new, sizes, time) {
                var newIndex = parseInt($new.data('index'));

                $new.show();
                loadCarouselPanel(newIndex, time);
            }
        },
        auto: {
            play: true,
            pauseDuration: 8000,
            duration: 1000,
            pauseOnHover: true
        },
        pagination: {
            container: '.carousel-paging',
            anchorBuilder: function(nr, item) {
                return '<div><span>' + nr + '</span></div>';
            }
        },
        prev: {
            button: '.carousel-scroll.left'
        },
        next: {
            button: '.carousel-scroll.right'
        }
    });

    $carouselWrapper = $carousel.parent('.caroufredsel_wrapper').detach();


    $("#introToTesVideo").fancybox({
        'width': 500,
        'height': 290,
        'padding': 0,
        'centerOnScroll': true,
        'titleShow': false,
        'overlayColor': '#2a2a2a',
        'overlayOpacity': 0.8,

        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe'
    });
});

/**
 * yaa (yet another accordion)
 *
 * http://www.604media.com/jquery
 *
 * Copyright (c) 2008 Tim Kraumanis
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * MODIFIED BY J. FINN 6-Sep-2011
 * Changes the smooth and gradual slide up down action can be replaced with a simple switch for display on & off
 * Also now provides capability for a callback function to be called when the expand-reveal / contract-hide action is complete
 * Version: 2.0a
 */

(function($) {


$.fn.yaa = function(settings) {
		// settings
		settings = $.extend({
		activeClass: "header_highlight",
				headClass: "accordion_heading",
				contentClass: "accordion_content",
				initiallyHidden: true,
				slideActionUsed: false,
		slideTime: 300,
		onSlideCallback: function() { }
		}, settings || {});

		return this.each(function() {

		if (settings.initiallyHidden) {
		  $(this).children('.' + settings.contentClass).hide(); 
		}
		$(this).children('.' + settings.activeClass).next('.' + settings.contentClass).slideDown(settings.slideTime);
		$(this).find('.' + settings.headClass).click(
		   function() {
			  ($(this).next('.' + settings.contentClass)[settings.slideActionUsed ? "slideToggle" : "toggle"])()
			  .siblings('.' + settings.contentClass + ':visible').slideUp(settings.slideTime);
			  setTimeout(settings.onSlideCallback, settings.slideTime * settings.slideActionUsed * 1.005);
		});
		
	});

};


})(jQuery);




