var FLOW_COUNT;
var CURRENT_MOVIE;
var CURRENT_POSTER;
var MOVIE_QUEUE = [];
var MOVIE_RUNNING = false;
var TOTAL_BODY_HEIGHT = 0;

var $introSlideShow = null;
var intro = null;

var lightBoxShows = {};
var isIOS = false;
var isIPhone = false;


/**
 * Remove the Flash based player and add an HTML5 version video player instead.
 * Also bind the play and end event listeners so we can implement the play-all thing.
 */
function removeFlashPlayer() {
    var $video = $('#flash-video').empty();
    var movie_width = $video.width();
    var movie_height = $video.height();

    $video.append('<video class="video-js" width="' + movie_width + 'px" height="' + movie_height + 'px" autoplay="true" controls="controls" poster="' + CURRENT_POSTER + '"><source src="' + CURRENT_MOVIE + '" type="video/mp4"/></video>');

    var $movie = $('video', $video);

    $movie[0].addEventListener('play', function() {
        movieStarted();
        this.play();
    });
    $movie[0].addEventListener('pause', function() {
        this.pause();
        // MOVIE_RUNNING = false;
    });
    $movie[0].addEventListener('ended', function() {
        this.pause();
        movieEnded();
    }, false);

    if (! isIPhone) {
        $movie[0].load();
        $movie[0].play();
    }
}

/**
 * The movie has been started
 */
function movieStarted() {
    MOVIE_RUNNING = true;
}

/**
 * The current movie is finished.  If the current movie queue is not empty, start the next movie.
 */
function movieEnded() {
    if (! MOVIE_RUNNING) {
        return;
    }

    MOVIE_RUNNING = false;
    if (MOVIE_QUEUE.length) {
        showMovie();
    }
}

/**
 * Convert an rgb color definition into it's hex counterpart
 *
 * @param rgb  The color definition
 * @return String  the hex definition
 */
function rgb2hex(rgb) {
    if (rgb.search("rgb") == -1) {
        return rgb;
    } else {
        rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }

        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
}

/**
 * Start a movie using the FlowPlayer
 */
function startFlowPlayer() {
    var $node = $('#flash-video');
    if (! $node.length) {
        if (FLOW_COUNT++ < 100) {
            setTimeout(startFlowPlayer, 10);

        } else {
            $('#content-box .content').empty().append('<div class="error">Cannot embed given content item</div>');
        }
        return;
    }
    $node.addClass('isFlash');

    var backColor = '';
    try {
        backColor = rgb2hex($('body').css('background-color'));

    } catch(Exception) {
        backColor = '#ffffff';
    }

    try {
        flowplayer('flash-video', {
            src: 'flowplayer/flowplayer.commercial-3.2.7.swf',
            version: [9],
            onFail: removeFlashPlayer
        }, {
            canvas: {
                backgroundColor: backColor,
                backgroundGradient: 'none'
            },
            clip: {
                url: CURRENT_MOVIE,
                autoPlay: true,
                autoBuffering: true,
                onFinish: movieEnded,
                onCuepoint: [100, movieStarted],
                scaling: 'orig'
            },
            play: null,
            key: FLOWPLAYER_KEY,
            logo: {
                url: FLOWPLAYER_LOGO,
                fullscreenOnly: FLOWPLAYER_LOGO_FULLSCREEN_ONLY,
                displayTime: FLOWPLAYER_LOGO_DISPLAYTIME
            }
        });

    } catch(Exception) {
    }
}

/**
 * Show the next movie in the queue
 */
function showMovie() {
    var $content = $('#content-box div.content');

    if ($content.length) {
        unloadMovie();
        $content.empty();

        var $next = MOVIE_QUEUE.shift();
        if ($next != null && $next != undefined && $next.length) {
            CURRENT_MOVIE = $next.find('a').attr('href');
            CURRENT_POSTER = $next.find('img.poster').attr('src');
            MOVIE_RUNNING = false;
            var $poster = $next.find('img.poster');

            $content.append('<div id="flash-video"></div>');
            var ch = $content.height();

            $('#flash-video').css({width: $poster.width(), height: $poster.height(), paddingTop: (ch - $poster.height()) / 2});
            FLOW_COUNT = 0;
            startFlowPlayer();
        }
    }

    return false;
}

/**
 * Make sure to get rid of the movie in a way IE* can handle it as well!
 */
function unloadMovie() {
    if ($('#flash-video').length) {
        if ($f()) {
            $f('flash-video').unload();
        }

        $("#flash-video").text(' ');
        $('#content-box .content').empty();
    }
}

/**
 * Show and start the intro slide show if one is available. Also hide all the reels at the bottom.
 */
function startIntroSlideShow() {
    unloadMovie();
    var $content = $('#content-box .content');
    $content.empty();

    if ($introSlideShow != null) {
        $introSlideShow.remove();
        $content.append($introSlideShow);
        $('div.slide-content', $introSlideShow).show();
        intro.play();

        hideAllReels();

        $('#copyright').fadeIn('slow');
    }
}

/**
 * Hide the thumbnails in the current footer box
 */
function hideAllReels() {
    var $reelsContainer = $('#footer-box .footer-reels');
    $reelsContainer.children().hide();
    $reelsContainer.hide();

    $('#play-all').unbind('click').hide();
    $('#footer-box .current-caption').empty().hide();
    $('#copyright').fadeOut('fast');
}

/**
 * Show the given reel and bind a 'play-all' function
 *
 * @param reel  Name of the reel which is in fact the ID attribute of the corresponding UL
 */
function showReel(reel) {
    hideAllReels();

    var $reelsContainer = $('#footer-box .footer-reels');
    var $reel = $('#footer-box .footer-reels').find('.reel-' + reel);

    $('#footer-box .current-caption').show();

    $('#play-all').unbind('click').show();

    // TODO: this is only a movie *play all*
    MOVIE_QUEUE = new Array();
    var $links = $('ul#' + reel + ' > li', $reel);

    $links.each(function() {
        MOVIE_QUEUE.push($(this));
    });

    showMovie();

    $('#play-all').click(function(evt) {
        evt.preventDefault();

        MOVIE_QUEUE = new Array();

        var $links = $('ul#' + reel + ' > li', $reel);
        $links.each(function() {
            MOVIE_QUEUE.push($(this));
        });

        showMovie();
    });

    $reel.show();
    $reelsContainer.show();

    var total = 50;
    $links.each(function() {
        var itemWidth = $(this).width();
        total += itemWidth;
    });
    $('ul#' + reel).css('width', total + 'px');
}

function showSlideShow(name) {
    hideAllReels();

    var $reelsContainer = $('#footer-box .footer-reels');
    $reelsContainer.show();

    var $reel = $('#footer-box .footer-reels').find('.still-reel-' + name);
    $('#footer-box .current-caption').show();
    $reel.show();

    var total = 0;
    $('li', $reel).each(function() {
        total += $(this).outerWidth(true);
    });
    $('ul', $reel).css('width', (total + 100) + 'px');

    $('#content-box div.content').append(lightBoxShows[name].jquery);
    $('#content-box div.content #gallery').show();
    lightBoxShows[name].show.play();
}

/**
 * Center the body vertically
 */
function center_window_content() {
    if (! isIOS) {
        if (TOTAL_BODY_HEIGHT == 0) {
            var header = $('#header-box').height();
            var content = $('#content-box').height();

            var footer = 0;
            $('#footer-box').children().each(function() {
                if (! $(this).hasClass('footer-reels')) {
                    footer += $(this).height();
                } else {
                    var maxCar = 0;
                    $(this).find('.jcarousel-clip').each(function() {
                        if (maxCar < $(this).height()) {
                            maxCar = $(this).height();
                        }
                    });
                    footer += maxCar;
                }
            });

            TOTAL_BODY_HEIGHT = header + content + footer;
        }

        var diff = $(window).height() - TOTAL_BODY_HEIGHT;
        if (diff > 0) {
            $('#main-box').css('margin-top', diff / 2 + 'px');
        }
    }
}


$(document).ready(function() {
    // Detect whether the page runs on iOS or not
    var deviceAgent = navigator.userAgent.toLowerCase();
    isIOS = (deviceAgent.match(/(iphone|ipod|ipad)/));
    if (isIOS) {
        if (deviceAgent.match(/(ipad)/)) {
            $('body').addClass('ios');
        } else {
            isIPhone = true;
            $('body').addClass('iphone');
        }
    }

    var $curCaption = $('#footer-box div.current-caption');

    $('#fooger-box .footer-reels').children().hide();

    // bind all menu actions linking to an iFrame
    $('#content-box div.menu a.iframe').click(function() {
        unloadMovie();
        hideAllReels();

        var $content = $('#content-box div.content');
        if ($content.length) {
            $content.empty();
            $content.append('<iframe src="' + $(this).attr('href') + '" frameBorder="0"></iframe>');
            if (isIOS) {
                $content.append('<div class="cover left"></div><div class="cover right"></div><div class="cover top"></div><div class="cover bottom"></div>');
            }
        }
        return false;
    });

    // Check out if we do have an intro slide-show
    $slides = $('#content-box div.intro-slides');
    if ($slides.length) {
        $('a', $slides).each(function () {
            if (! $(this).attr('title')) {
                $(this).attr('title', '');
            }
        });

        $slides.prepend('<div id="gallery" class="slide-content"><div id="controls" class="controls"></div><div class="slideshow-container"><div id="loading" class="loader"></div><div id="slideshow" class="slideshow"></div></div></div>');
        intro = $slides.galleriffic({
            imageContainerSel:      '#slideshow',
            delay:                     INTRO_SLIDE_DELAY,
            numThumbs:                 20,
            preloadAhead:              40, // Set to -1 to preload all images
            enableTopPager:            false,
            enableBottomPager:         false,
            maxPagesToShow:            10,
            controlsContainerSel:      '#controls',
            renderSSControls:          true,
            renderNavControls:         true,
            nextOnClick:               false,
            playLinkText:              'Play',
            pauseLinkText:             'Pause',
            prevLinkText:              'Previous',
            nextLinkText:              'Next',
            nextPageLinkText:          'Next &rsaquo;',
            prevPageLinkText:          '&lsaquo; Prev',
            enableHistory:             false,
            enableKeyboardNavigation:  false,
            autoStart:                 false,
            syncTransitions:           INTRO_CROSS_FADE,
            defaultTransitionDuration: INTRO_TRANSITION_SPEED
        });

        $introSlideShow = $('#content-box div.intro-slides');
        $introSlideShow.remove();

        // Bind the logo click
        var $logo = $('#header-box .logo').css({cursor: 'pointer'});
        $logo.click(function() {
            startIntroSlideShow();
        });
    }

    // Setup all video reels in the footer section
    $('#footer-box .footer-reels ul.reel').each(function() {
        var reel = $(this).attr('id');
        var $thumbs = $(this);

        $thumbs.addClass('jcarousel-skin-postnbeam')
        $thumbs.removeClass('hidden');
        $thumbs.jcarousel();
        // $thumbs.css('width', '20000px');

        var $carousel = $thumbs.closest('div.jcarousel-skin-postnbeam');
        $carousel.addClass('reel-' + reel);
        $carousel.hide();

        $thumbs.find('li > a').each(function() {
            var $listItem = $(this).closest('li');
            var $cap = $listItem.find('.caption').remove();

            if ($listItem.hasClass('video')) {
                $(this).click(function(evt) {
                    MOVIE_QUEUE = [$listItem];
                    evt.preventDefault();
                    showMovie();
                    if (isIOS) {
                        $curCaption.empty().append($cap);
                    }
                });

            } else {
                $(this).click(function(event) {
                    return false;
                });
            }

            // The following would break showing the movie instantly on a "click" on iOS devices!
            if (! isIOS) {
                $(this).mouseenter(function() {
                    $curCaption.empty().append($cap);
                });
                $(this).mouseleave(function() {
                    $curCaption.empty();
                });
            }
        });
    });

    // Setup all still reels
    $('#footer-box .footer-reels ul.still-reel').each(function() {
        var reelId = $(this).attr('id');
        var boxId = 'still-reel-' + reelId;

        var $parent = $(this).parent();
        $parent.append('<ul rel="carul" class="still-reel" id="' + boxId + '"></ul>');

        var $carousel = $('#' + boxId);

        $(this).find('li').each(function() {
            $carousel.append('<li>' + $(this).html() + '</li>');
            var $lastLi = $carousel.find('li').last();
            var $full = $('a.fullsize', $lastLi);
            var $thumb = $('a.thumb', $lastLi);

            if ($full.length && $thumb.length) {
                $thumb.attr('href', $full.attr('href'));
                $full.remove();
            }
        });
        $carousel.find('div.caption').hide();

        // The following would break showing the movie instantly on a "click" on iOS devices!
        $('a', $carousel).each(function() {
            $(this).attr('rel', reelId);
            var $cap = $(this).parent().find('div.caption');

            if (! isIOS) {
                $(this).mouseenter(function() {
                    $curCaption.empty().append($cap.html());
                });
                $(this).mouseleave(function() {
                    $curCaption.empty();
                });
            }
        });

        $carousel.addClass('jcarousel-skin-postnbeam');
        $carousel.jcarousel();
        $carousel.css('width', 'auto');

        var $carousel = $carousel.closest('div.jcarousel-skin-postnbeam');
        $carousel.addClass('still-reel-' + reelId);

        $("a[rel=" + reelId + "]").fancybox({
            cyclic: true,
            'transitionIn'        : 'none',
            'transitionOut'        : 'none',
            'titlePosition'     : 'over',
            'overlayColor'      : LIGHTBOX_BACKGROUND_COLOR,
            'overlayOpacity'    : LIGHTBOX_BACKGROUND_OPACITY,
            'titleFormat'        : function(title, currentArray, currentIndex, currentOpts) {
                var $item = $carousel.find('li').eq(currentIndex);
                var $cap = $item.find('div.caption');
                var caption = $cap.length ? $cap.html() : '';
                var content = (caption != null && caption.length) ? caption : title;
                if (! content.length) {
                    return '';
                }
                return '<span id="fancybox-title-over">' + content + '</span>';
            },
            onStart: function() {
                lightBoxShows[reelId].show.pause();
            },
            onClosed: function() {
                lightBoxShows[reelId].show.play();
            }
        });

        $(this).wrap('<div class="intro-slides"></div>');
        $(this).removeClass('still-reel').hide();
        $(this).parent().prepend('<div id="gallery" class="slide-content"><div id="controls" class="controls"></div><div class="slideshow-container"><div id="loading" class="loader"></div><div id="slideshow" class="slideshow"></div></div></div>');

        var currentSlide = $(this).parent().galleriffic({
            imageContainerSel:      '#slideshow',
            delay:                     3000,
            numThumbs:                 20,
            preloadAhead:              40, // Set to -1 to preload all images
            enableTopPager:            false,
            enableBottomPager:         false,
            maxPagesToShow:            10,
            controlsContainerSel:      '#controls',
            renderSSControls:          false,
            renderNavControls:         false,
            playLinkText:              'Play',
            pauseLinkText:             'Pause',
            prevLinkText:              'Previous',
            nextLinkText:              'Next',
            nextPageLinkText:          'Next &rsaquo;',
            prevPageLinkText:          '&lsaquo; Prev',
            enableHistory:             false,
            enableKeyboardNavigation:  true,
            autoStart:                 false,
            syncTransitions:           false,
            defaultTransitionDuration: 1000
        });

        var $nodes = $(this).parent();
        lightBoxShows[reelId] = {'show': currentSlide, 'jquery': $nodes};
        $nodes.remove();
    });


    // bind all menu actions linking to a show reel
    $('#content-box div.menu a.reel').each(function() {
        var $content = $('#content-box div.content');
        var reel = $(this).attr('href');

        if ($content.length) {
            var $thumbs = $('#footer-box ul#' + reel);
            if ($thumbs.length) {
                $(this).click(function(evt) {
                    evt.preventDefault();
                    unloadMovie();
                    $content.empty();
                    showReel(reel);
                });
            }
        }
    });

    $('#content-box div.menu a.still-reel').each(function() {
        var reel = $(this).attr('href');
        $(this).click(function(evt) {
            evt.preventDefault();
            unloadMovie();
            $('#content-box div.content').empty();
            showSlideShow(reel);
        })
    });

    $('#footer-box').show();

    if ($introSlideShow != null) {
        startIntroSlideShow();
    }

    $('a.email').each(function() {
        var href = $(this).attr('href').split(/\//);
        if (href.length == 2) {
            var address = href[0] + '@' + href[1];
            $(this).attr('href', 'mailto:' + address).text(address);
        }
    });

    if (! isIOS) {
        $(window).resize(function() {
            center_window_content();
        });
        center_window_content();
    }
});
