var resize_timeout;

var youtube_iframe = $('#welcome iframe');
var youtube_src = youtube_iframe.attr('src');
var youtube_id = youtube_src.split('/')[4];
var youtube_thumb = '<a id="youtube_thumb" href="#"><img src="http://i3.ytimg.com/vi/'+ youtube_id +'/0.jpg" /></a>';


$( function() {
    
    // cycle through banners (if more than one)
    if ($('#banners aside').length > 1) {
        $('#banners').cycle({
            delay: 2000,
            timeout: 10000,
            speed: 2000,
            after: onAfter
        });
    }
    
    // set (real) youtube iframe size
    youtube_iframe.attr({
       'width': '320px',
       'height': '214px' 
    });
    
    // create youtube popup (clone the 'real' iframe) and hide it ready for use later
    var youtube_iframe_clone = youtube_iframe.clone()
    $('body').append(youtube_iframe_clone);
    youtube_iframe_clone.wrap('<div id="youtube_popup"/>');
    $('#youtube_popup').append('<div id="youtube_popup_close"><a href="#">Close</a></div>');
    $('#youtube_popup iframe').attr({ /* override iframe attrs for the real iframe defined above */
        'width': '640px',
        'height': '390px'
    });
    $('#youtube_popup').hide();
    
    // when clicking 'close' in popup, hide the popup
    $('#youtube_popup_close a').live('click', function() {
        $('#youtube_popup').hide();
    });
    
    // add youtube thumbnail img to document and hide ready for use later
    $('#welcome h2').after(youtube_thumb);
    $('#youtube_thumb').hide();
    
    // when the thumbnail img is clicked show the popup (if not already showing) 
    $('#youtube_thumb').live('click', function() {
        if ( ! $('#youtube_popup').is(':visible')) {
            $('#youtube_popup').show();
        }
    });
    
    // when window is resized call the toggle_youtube function
    $(window).resize( function() {
        //use time delay to stop IE (and possibly other browsers) firing event after every pixel moved
        clearTimeout(resize_timeout);
        resize_timeout = setTimeout('toggle_youtube()', 100 );
    });
    toggle_youtube();
    
});


// jQuery Cycle fix
function onAfter(out)
{
    // Dyamically set the greater z-index for the current slide.
    // Works with any number of slides.

    $(this).css('z-index', Number($(out).css('z-index'))+1);
    $(out).css('z-index', Number($(out).css('z-index'))-1);
};


function toggle_youtube() {
    /* If window < 768px wide show video, else show thumbnail */
    if (document.documentElement.clientWidth > 767) {
        youtube_iframe.hide();
        $('#youtube_thumb').show();
    }
    else {
        $('#youtube_thumb').hide();
        youtube_iframe.show();
    }
}

