(function($) {

    window.app = {

        init: function() {

            var doc_location = window.location.pathname.toString();
            
            if (doc_location.substring(doc_location.length-1)!='/') {
                window.location.replace(doc_location+'/');
            }

            $('#laurels_container').cycle({
                fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
                timeout: 5000,
                speedIn: 3500
            })


            $('body.section-home div#films_container').cycle({
                fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
                timeout: 5000,
                speedIn: 3500
            });

            $('img.close_button').click(function(event){
                $.fancybox.close()
                event.preventDefault();
            });

            // center div#header on the homepage
            $(window).resize(function(){
                
                if (window.location.pathname.toString() == '/' || window.location.pathname.toString() == '/s/') {
                    var $sublogline = $('body.section-home div.sublogline');
                    var $header = $('body.section-home div#header');
                    var window_half = $(window).width() / 2;
                    var header_half = $header.width() / 2;
                    var el_left_pos = window_half - header_half;
                    $header.css({
                        'left': el_left_pos + 'px'
                    });
                    $sublogline.css({
                        'left': el_left_pos + 'px'
                    });
                    var header_offset_right = $header.offset().left + $header.outerWidth();
                    var button_width = $('a.on_home').width()
                    $('a.on_home').css({
                        'left': (header_offset_right - button_width) + 'px',
                        'position': 'absolute',
                        'bottom': '10px'
                    });
                }
            }).resize();

            this.videos.load();

            // set scroll position and top position of wrapper to 0 for credits popup
            $('a.full_credits_link').click(function(){
                $(document).scrollTop(0);
                $("#fancybox-wrap").css({'top':'0', 'bottom':'auto'});
            });

            $('a.full_credits_link').fancybox({
                'type': 'inline',
                'hideOnContentClick': false,
                'hideOnOverlayClick': false,
                'overlayColor': '#fff',
                'overlayOpacity': 1,
                'centerOnScroll': false,
                 onComplete: function(){
                    $('a#fancybox-close').css({
                        'position':'absolute',
                        'right':'245px',
                        'top':'16px',
                        'background': 'url("/images/fancy_close.png") no-repeat scroll 0 0 transparent',
                        'width':'13px',
                        'height':'13px'
                    });
                 }
            });

            $('ul#section-items li:first').addClass('active');

            var div_height = $('div#sections_container_inner > div:first').height();

            var credits_height;

            $('div#sections_container').height(div_height);

            $('div#sections_container_inner > div:first').css('display','block');


            $('ul#section-items li').click(function(){

               if ($(this).attr('id') == 'credits') {
                   credits_height = $('div#section-credits').height();
               }
               if ( $(this).attr('id') != 'other' || $(this).attr('id') != 'trailer') {

                   $(this).addClass('active').siblings().removeClass('active');

                   clicked_item = 'section-'+$(this).attr('id');

                   div_height = $('div#sections_container_inner div#'+clicked_item).height();

                   $('div#sections_container_inner div#'+clicked_item).parent().parent().height(div_height);
                   $('div#sections_container_inner div#'+clicked_item).fadeIn('slow').siblings().fadeOut('slow');
               };
            });

            if (window.location.pathname.toString() == '/films/1/axis-of-light/' || window.location.pathname.toString() == '/s/films/1/axis-of-light/') {

                $('a.person-link').click(function(event){
                    $('div#section-synopsis,div#section-credits,div#section-quotes').fadeOut('slow');
                    event.preventDefault();
                    var person_id = $(this).attr('href');
                    // pause the slideshow
                    $('div#pg_slide_'+person_id.split('#')[1]).fadeTo(250,1).siblings().fadeTo(250,0);
                    $('#media_gallery_home .slideshow').cycle('pause');
                });

            }

            $('a.person-link').click(function(event){
                var person_id = $(this).attr('href');
                $('div#section-credits').fadeOut('slow',function(){
                    $.post('/profiles/', {person_id: person_id}, function(data) {
                    $('div#biography').fadeIn().html(data);
                    div_height = $('div#biography').height()+25;
                    $('div#sections_container').height(div_height);
                    $('span.back').click(function(){
                        $('div#biography').fadeOut('slow',function(){
                            $('div#section-credits').fadeIn();
                            $('div#sections_container').height(credits_height); 
                        });
                    });
                });




                
                });
            });

            

        },

        videos: {

            load: function() {

                // popu-up windows may no longer use fancybox as we're using
                // html5 video tag to place videos on the page...

                $('#main_container')
                    .append('<div style="clear: both;"></div>')
                    .css({'position': 'relative'});

                $('a.video').click(function() {
                    var l = 0;
                    var content_w = $('#main_content').width();
                    var content_h = $('#main_content').height();
                    var w = (window.siteview == 'large') ? 1180 : 990;
                    var h = (window.siteview == 'large') ? 673 : 576;
                    var t = $('#slideshow_container').offset().top - $('#main_content').offset().top - 8;
                    var href = $(this).attr('data-href') || $(this).attr('href');
                    $(this).attr('data-href', href);
                    $(this).attr('href', '#');
                    if (!$('#movie_mask').length) {
                        $('#main_content').append('<div id="movie_mask" class="close_movie"></div>');
                    }
                    if (!$('#movie_close_btn').length) {
                        $('#main_content').append('<div id="movie_close_btn" class="close_movie"></div>');
                    }
                    if (!$('#movie_player').length) {
                        $('#main_content').append('<iframe id="movie_player" src="/blank.html" frameborder="no"></iframe>');
                    }

                    //$('#movie_mask').css({
                    //    'position': 'absolute',
                    //    'display': 'none',
                    //    'top': '0px',
                    //    'left': l + 'px',
                    //    'width': content_w + 'px',
                    //    'height': content_h + 'px',
                    //    'background': 'rgba(255, 255, 255, 0.8)',
                    //    'border': 0,
                    //    'overflow': 'hidden',
                    //    'z-index': 99
                    //});

                    $('#movie_player').css({
                        'position': 'absolute',
                        'display': 'none',
                        'top': 123 + 'px',
                        'left': l + 'px',
                        'width': w + 'px',
                        'height': h + 'px',
                        'background': '#000',
                        'border': 0,
                        'overflow': 'hidden',
                        'z-index': 100
                    }).attr('src', href);
                    $('#movie_close_btn').css({
                        'position': 'absolute',
                        'display': 'none',
                        'top': (t - 30) + 'px',
                        'left': (l + w - 15) + 'px',
                        'width': '35px',
                        'height': '35px',
                        'border': 0,
                        'overflow': 'hidden',
                        'z-index': 101
                    }).html('<img src="/lib/archimedes/images/archimedes_closebox.png" style="border: 0;" />');
                    //window.scrollTo(0, t - 30);
                    $('#movie_mask, #movie_player, #movie_close_btn').fadeIn(1000);
                    $('.close_movie').click(function() {
                        $('#movie_mask, #movie_player, #movie_close_btn').fadeOut(1000);
                        $('#movie_player').attr('src', '/blank.html');
                    });
                    return false;
                });


                // check if parameter in query string exists
                var query_string = document.location.search;
                if (query_string.indexOf('playtrailer') != -1) {
                    $('a.video').trigger('click');
                }

            }

        },

        quicksearch: {

            init: function() {

                $('#quicksearch_field').click(function() {
                    if ($(this).attr('value') == 'Search...') {
                        $(this).val('');
                    }
                    $(this).addClass('active');
                });

                $('#quicksearch_btn').click(function() {
                    $('#quicksearch_form')[0].submit();
                });
            }

        },

        media_gallery: {
                init: function() {
                    if (h.element_exists('#media_gallery_home')) {
                        $('#media_gallery_home .slideshow')
                            .cycle({
                                fx:         'fade',
                                speed:      1200,
                                timeout:    5000,
                                pause:      0,
                                before:     function(currSlideElement, nextSlideElement, options) {
                                    $('#slideshow_caption').html($(this).attr('rel'));
                                    $('#media_gallery_home #slideshow_thumbnails li a').removeClass('active');
                                    $('#media_gallery_home #slideshow_thumbnails li a span').stop().hide(0).fadeTo(0, 0);

                                    next_slide_id = $(nextSlideElement).attr('id').split('pg_slide_')[1];
                                    next_slide_thumb_id = '#pg_thumb_' + next_slide_id;
                                    $(next_slide_thumb_id + ' a', '#media_gallery_home #slideshow_thumbnails').addClass('active');
                                    $(next_slide_thumb_id + ' a span', '#media_gallery_home #slideshow_thumbnails').show(0).fadeTo(200, 0.92);

                                    next_slide_thumb_container = $(next_slide_thumb_id + ' a span').closest('ul').attr('rel');
                                }
                            });

                        $('#media_gallery_home #slideshow_thumbnails a')
                            .click(function () {
                                $(this).fadeTo(0, 1);
                                $('#media_gallery_home .slideshow').cycle('pause');
                                if ($(this).attr('rel')) {
                                    $('#media_gallery_home .slideshow').cycle(parseInt($(this).attr('rel')));
                                }
                                return false;
                            })
                            .mouseover(function () {
                                $(this).fadeTo(100, 1);
                            })
                            .mouseout(function () {
                                $(this).fadeTo(250, 1);
                            })
                        ;

                        $('#media_gallery_home #slideshow_thumbnails').cycle({
                            fx:      'scrollHorz',
                            speed:    2000,
                            timeout:  0
                        });
                        

                        $('#media_gallery_home #slideshow_thumbnails_prev a').click(function () {
                            $('#media_gallery_home .slideshow').cycle('pause');
                            $('#media_gallery_home #slideshow_thumbnails').cycle('prev');
                            return false;
                        });

                        $('#media_gallery_home #slideshow_thumbnails_next a').click(function () {
                            $('#media_gallery_home .slideshow').cycle('pause');
                            $('#media_gallery_home #slideshow_thumbnails').cycle('next');
                            return false;
                        });

                        var t;

                        if ($('#media_gallery_home #slideshow_thumbnails ul li').length < 8 ) {
                            $('#media_gallery_home #slideshow_thumbnails_prev a, #media_gallery_home #slideshow_thumbnails_next a').remove();
                        }

                        var top = 58;
                        $(window).resize(function(){
                            var current_path = window.location.pathname.toString();
                            if (current_path.slice(0,3) != '/s/') {
                                top = 69;
                            }
                        }).trigger('resize');

                            $('div#slideshow_container').hover(
                            function(event){
                                event.stopPropagation();
                                $('#slideshow_thumbnails_container').stop().animate({'top': - top}, 'slow');
                                // clear timeout when hovering over
                                window.clearTimeout(t);
                            },
                            function(event){
                                t = window.setTimeout(function() {
                                    $('#slideshow_thumbnails_container').stop().animate({'top': 0}, 'slow', function(){
                                    });
                                }, 1500);

                            });
                    }
                }
            },

            add_proxy_dir: {
                init: function() {
                    $(window).resize(function(){
                        var window_width = $(window).width();
                        var window_threshold = 1280;
                        var current_path = window.location.pathname.toString();
                        var new_path;
                        if (window_width < window_threshold) {
                            if (current_path.slice(0,3) != '/s/') {
                                new_path = '/s' + current_path;
                                window.location.replace(new_path);
                            }
                        }
                        else {
                            if (current_path.slice(0,3) == '/s/') {
                                new_path = current_path.slice(2);
                            window.location.replace(new_path);
                            }
                        }
                    }).trigger('resize');
                }
            }
            
    };

    $(document).ready(function() {
            window.app.init();
            window.app.quicksearch.init();
            window.app.add_proxy_dir.init();
            window.app.media_gallery.init();
            //$(window).trigger('resize');
        });

})(jQuery);

function resize_img(img_el, container) {
    img_el.each(function(){
        var $img = $(this),
            aspect_ratio = container.width() / container.height() ;
            if (isNaN(aspect_ratio)) {
                aspect_ratio = 0;
            }
        if ( (container.width() / container.height()) != aspect_ratio ) {
            $(this).removeClass().addClass('bgheight');
        } else {
            $(this).removeClass().addClass('bgwidth');
        }
    });
}

$(window).load(function(){
    $window = $(window)
    $window.resize(function(){
        var window_path = window.location.pathname.toString();
        switch( window_path ) {
            case '/':
               //resize_img($('.film_img'),$(window));
            break;
            default:
               resize_img($('span.film > img'),$('span.film'));
            break;
        }
    }).resize();
});
