var animating = false;
var loader_timer;
var border_interval;
var resize_timer;

// IE detect
var ieversion = 100;
var ie;
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
    ieversion = Number(RegExp.$1);
    if (ieversion == 100) {
        ie = false;
    }
    else {
        ie = true;
    }
}

function showLoader(area) {
    loader_timer = setTimeout(function() {
        area.append('<div id=\"loader\"></div>');
        $('#loader', area).stop().animate({'opacity':'1'}, 200);
    }, 300);
}

function hideLoader(area) {
    clearTimeout(loader_timer);
    loader_timer = null;
    $('#loader', area).stop().animate({'opacity':'0'}, 200, function() {
        $(this).remove();
    });
}

function accordiGrid(home) {
    // Count panels, calculate width %
    var article = $('#article');
    var accordigrid = $('.accordigrid');
    var panel = $('.panel');
    var panel_inner = $('.inner', panel);
    var panel_border = $('.panel_border', panel);
    var arrow_wrapper = $('.arrow_wrapper');
    var image_obj = $('.image_wrapper, .embedded, .home_image');
    var panel_count = panel.length;
    var panel_active_w;
    var init = true;
    var fixed_columns = accordigrid.parent().hasClass('fixed_columns');

    if (ieversion==6) {
        panel_border.hide();
    }

    var main_max = 748;
    var collapsed_max = 204;
    var accordigrid_max = main_max + ((panel_count - 1) * collapsed_max);
    var panel_active_w = (main_max / accordigrid_max) * 100;
    var panel_collapsed_w = (100-panel_active_w)/(panel_count-1)-0.05; // 0.005 for safety
    var reset_active_w = panel_active_w;
    var reset_collapsed_w = panel_collapsed_w;
    var equal_w = 100 / panel_count;

    var active_panel_n = 0;
    var active_panel = $('.panel').eq(active_panel_n);

    var inactive_panel = $('.inactive_panel');
    var min_panel_height;
    var inactive_panel_count = inactive_panel.length;
    
    $('.carousel_wrapper', active_panel).display = 'block';

    //Deal with multiple images
    accordionGroup();

    // Set panel widths
    if (home) {
        panel_active_w = (panel_active_w + panel_collapsed_w) / 2 - 0.05;
        active_panel = $('.active_panel');
        $('.arrow_wrapper', '.active_panel').hide();
    }
    else {
        accordigrid.css({'max-width':accordigrid_max+"px"});
    }

    if (fixed_columns) {
        panel.css('width', equal_w+'%');
    }
    else {
        panel.not(active_panel).css({'width':panel_collapsed_w+'%'});
        active_panel.css({'width':panel_active_w+'%'});
    }

    if (fixed_columns) {
        $('.inactive_panel', accordigrid).removeClass('inactive_panel').addClass('active_panel');
        $('.arrow_wrapper', accordigrid).remove();
        equalise();
    }
    else {
        // Reset values
        panel_active_w = reset_active_w;
        panel_collapsed_w = reset_collapsed_w;
        
        if (ieversion < 9) {
            $('.image_wrapper', '.inactive_panel').css({'opacity':'0.2'});
        }

        // Accordion panel click
        $('.inactive_panel', accordigrid).live('click', function() {
            if (!animating) {
                var active_panel = $('.active_panel', accordigrid);
                var new_panel = $(this);
                changePanel(active_panel, new_panel);
            }
            return false;
        }).live('mouseover', function() {
            $(this).addClass('hover');
            $('.image_wrapper, .home_image, .embedded', this).stop().animate({'opacity':'0.5'}, 200);
        }).live('mouseout', function() {
            $(this).removeClass('hover');
            $('.image_wrapper, .home_image, .embedded', this).stop().animate({'opacity':'0.2'}, 200);
        });

        $('.home_panel').click(function() {
            if (init) {
                var active_panel = $('.home_panel').not(this);
                var new_panel = $(this);
                changePanel(active_panel, new_panel);
            }
        });

        $('.active_panel .arrow_wrapper', accordigrid).live('click', function() {
            var active_panel = $('.active_panel', accordigrid);
            new_panel = $('#default');
            changePanel(active_panel, new_panel);
            return false;
        });

        $('.active_panel .home_image').live('click', function() {
            if (init) {
                return false;
            }

            var clickthrough_location = $(this).attr('clickthrough');
            if (clickthrough_location != undefined && clickthrough_location != '')
            {
                window.location = $(this).attr('clickthrough');
            }
            else
            {
                var this_panel = $(this).parentsUntil('.panel');
                var this_clickthrough = $('.clickthrough', this_panel).attr('href');
                if (this_clickthrough) {
                    window.location = this_clickthrough;
                }
            }
        });

        function forceWidth(ie_panel) {
            $('.image_wrapper img', ie_panel).each(function() {
                var native_width = $(this).attr('hint_width');
                if (native_width < active_panel.width()) {
                    $(this).css({'width':native_width+"px"});
                }
            });
        }

        if (ieversion==6) {
            forceWidth(active_panel);
        }

        function changePanel(active_panel, new_panel) {
            animating = true;
            var panel_fade_active = $('.panel_fade', active_panel);
            var panel_fade_new = $('.panel_fade', new_panel);
            var footer = $('.page_footer');
            if ($('body').scrollTop()>0) {
                $('body').animate({scrollTop: 0}, 300, 'easeInOutQuad');
            }
            arrow_wrapper.animate({'opacity':'0'}, 300);
            panel_fade_active.animate({'opacity':'0'}, 300, resetPanels);
            new_panel.addClass('new_panel');
            if (ieversion < 9) {
                panel_fade_active.toggleVisibility();
                panel_fade_new.toggleVisibility();
            }
            panel_fade_new.animate({'opacity':'0'}, 300, function() {
                $('.hide_this', panel_fade_active).show();
                $('.embedded', panel_fade_active).hide();
                //border_interval = setInterval(equalise, 25);
                var panel_w = $('.inactive_panel').width();
                var i = 0;
                $('.new_panel ~ .panel').each(function() {
                    if ($(this).index() > active_panel.index()) {
                        var this_pos = $(this).position();
                        var this_offset_x = this_pos.left + (i*panel_w);
                        $(this).css({'position':'absolute','left':this_offset_x+"px"});
                        i++;
                    }
                });
                if (ieversion==6) {
                    $('.image_wrapper img', active_panel).css({'height':'','width':''});
                    forceWidth(new_panel);
                }
                active_panel.css({'height':article.height()-60+"px"});
                new_panel.css({'height':article.height()-60+"px"});
                active_panel.animate({'width':panel_collapsed_w+"%"}, 500, function() {
                    active_panel.css({'height':''});
                    new_panel.css({'height':''});
                });
                active_panel.removeClass('active_panel');
                active_panel.addClass('inactive_panel');
                $('.image_wrapper, .home_image, .embedded', active_panel).not('.active').css({'opacity':'0.2'});
                new_panel.addClass('active_panel');
                new_panel.removeClass('inactive_panel');
                
                $('.carousel_wrapper', $('.active_panel')).show();
                $('.carousel_wrapper', $('.inactive_panel')).hide();
                
                $(arrow_wrapper, new_panel).removeClass('hover');
                new_panel.animate({'width':panel_active_w+"%"}, 500, function() {
                    $('.hide_this', new_panel).hide();
                    $('.embedded', new_panel).show();
                    $('.hover').removeClass('hover');
                    $('.image_wrapper, .home_image, .embedded', '.active_panel').css({'opacity':'1'});
                    var new_article_height = new_panel.height();
                    //clearTimeout(border_interval);
                    //border_interval = null;
                    animateBorders();
                    equalise();
                    panel_fade_active.animate({'opacity':'1'}, 300);
                    panel_fade_new.animate({'opacity':'1'}, 300);
                    if (ieversion < 9) {
                        panel_fade_active.toggleVisibility();
                        panel_fade_new.toggleVisibility();
                    }
                    $('.inactive_panel').css({'position':'','left':''});
                    $('.new_panel').removeClass('new_panel');
                    panel.each(function() {
                        if ($(this).index()<=$(new_panel).index()) {
                            $('.arrow', this).removeClass('arrow-left').addClass('arrow-right');
                        }
                        else {
                            $('.arrow', this).removeClass('arrow-right').addClass('arrow-left');
                        }
                    });
                    arrow_wrapper.show();
                    arrow_wrapper.delay(500).animate({'opacity':'1'}, 300, function() {
                        animating = false;
                        init = false;
                    });
                });
            });
        }
        
        $(window).resize(function() {
            clearTimeout(resize_timer);
            resize_timer = setTimeout(refreshBorders, 500);
        }).load(refreshBorders);
        
        
    }


    function refreshBorders() {
        min_panel_height = 0;
        inactive_panel.each(function() {
            var this_height = $(this).css('height').replace("px","");
            if (this_height > min_panel_height) {
                min_panel_height = this_height;
            }
            if ($(this).index() == inactive_panel_count+1) {
                panel_border.css({'min-height':min_panel_height+"px"});
                equalise();
            }
        });
        if (!inactive_panel.length) {
            equalise();
        }
    }
    
    function equalise() {
        var current_height = article.height() - 60;
        panel_border.css({'height':current_height+"px"});
    }

}

function animateBorders(callback) {
    var current_height = $('#article').height() - 60;
    var panel_border = $('.panel_border');
    panel_border.animate({'height':current_height+"px"}, 500, 'easeInOutQuad', callback);
}

function imageViewer(panel) {
    // Define elements
    var carousel = $('.carousel', panel);
    var carousel_wrapper = $('.carousel_wrapper', panel);
    var carousel_nav = $('.carousel_nav', panel);
    var image_blocks = $('.image_block', panel);
    var first_thumb = $('img', carousel).filter(':eq(0)');
    var first_block = image_blocks.first();
    var image_area = $('.image_area', panel);
    var panel_inner = $('.inner', panel);

    // Hide all image blocks from DOM
    $(image_blocks).not(first_block).css('display', 'none');
    
    
    carousel_wrapper.show();

    var item_count = image_blocks.length;
    var thumb_padding = 8;
    var first_thumb = $('img', carousel).filter(':eq(0)');
    var thumb_width;
    var carousel_width;
    
    thumb_width = 96 + thumb_padding;
    carousel_width = (thumb_width * item_count) - thumb_padding;
    carousel.css({'width':carousel_width+"px"});
    
    //Init
    first_thumb.load(function() {
        /*thumb_width = first_thumb.width() + thumb_padding;
        carousel_width = (thumb_width * item_count) - thumb_padding;
        carousel.css({'width':carousel_width+"px"});*/
        carouselCheck();
    });
    first_thumb.addClass('active').css({'opacity':'1'});
    $('img', carousel).not('.active').addClass('inactive').css({'opacity':'0.5'});

    $('.image_block', image_area).click(function(){
        if (!animating && panel.hasClass('active_panel'))
        {
            animating = true;
            var position = $(this).index(); 
            var length = $(this).siblings().length + 1;
            var target = ((position + 1) % length);
            changeThumbnail(target);
            changeImage(target);
        }
    });

    // Thumbnails
    $('.inactive', panel).live('click', function() {
        if (!animating) {
            animating = true;
            var thumb_index = $(this).index();
            $('.active', carousel).removeClass('active').addClass('inactive').animate({'opacity':'0.5'}, 200);
            $(this).removeClass('inactive').addClass('active');
            changeImage(thumb_index);
        }
        return false;
    }).live('mouseenter', function() {
        $(this).stop().animate({'opacity':'1'}, 200);
    }).live('mouseleave', function() {
        $(this).stop().animate({'opacity':'0.5'}, 200);
    });

    // Thumbnail navigation
    carousel_nav.click(function() {
        var carousel_offset = +carousel.css('margin-left').replace("px","");
        // Left
        if ($(this).hasClass('carousel_nav_left')) {
            if (carousel_offset >= 0) {
                return false;
            }
            var offset = 104;
        }
        // Right
        else {
            if (carousel.width() + carousel_offset < panel.width()-28) {
                return false;
            }
            var offset = -104;
        }
        animating = true;
        carousel.animate({'margin-left':(carousel_offset+offset)+"px"}, 100, 'easeInOutQuad', function() {
            animating = false;
        });
        return false;
    });

    function changeImage(image_num) {
        console.log(carousel_wrapper);
        var carousel_position = carousel_wrapper.position();
        var carousel_init_position = carousel_position.top;
        var new_block = image_blocks.filter(':eq(' + image_num + ')');
        var active_panel = $('.active_panel');
        image_area.animate({'opacity':'0'}, 300, function() {

            var old_panel_height = panel_inner.height();
            panel_inner.css({'height':old_panel_height+"px"});

            $(image_blocks).each(function() {
                var this_block = $(this);
                if (this_block.css('display') != 'none')
                {
                    old_block_height = this_block.height();
                }
                this_block.css('display', 'none');
            });

            new_block.css('display', '');

            new_panel_height = old_panel_height - old_block_height + new_block.height();

            var range = old_panel_height - new_panel_height;
            if (range == 0) {
                duration = 0;
            }
            else {
                var duration = Math.max(Math.abs(range)*2.5, 300);
            }

            if (ieversion < 9) duration = 0;

            panel_inner.animate({'height':(new_panel_height)+"px"}, duration, 'easeInOutQuad', function() {
                $(image_area).animate({'opacity':'1'}, 300);
                panel_inner.css({'height':''});
                animateBorders();
                animating = false;
            });
        });
    }

    function changeThumbnail(image_num) {
        $('.active', carousel).removeClass('active').addClass('inactive').animate({'opacity':'0.5'}, 200);
        $('img:eq('+image_num+')', carousel).removeClass('inactive').addClass('active').stop().animate({'opacity':'1'}, 200);
    }

    function carouselCheck() {
        if (carousel.width() < $('.active_panel').width()-28) {
            carousel_nav.css({'display':'none'});
            carousel.css({'margin-left':'0'});
        }
        else {
            carousel_nav.css({'display':'block'});
        }
    }

    carouselCheck();

    $(window).resize(function() {
        carouselCheck();
    });
}

function thumbGrid(panel) {
    if (ieversion > 7)
    {
        $('.image_wrapper', panel).each(function() {
            $(this).append('<div class=\"overlay\"><div class=\"overlay_middle\"><div class=\"overlay_symbol\"></div></div></div>');
            $('.overlay').css({'opacity':'0'});
        });
    }

    $('.active_panel .grid_thumb, .hover_overlay, .product_item').live('mouseenter', function() {
        $('.overlay', this).stop().animate({'opacity':'1'}, 200);
    }).live('mouseleave', function() {
        $('.overlay', this).stop().animate({'opacity':'0'}, 200);
    }).live('click', function() {
        window.location = $('a', this).attr('href');
    });

}

function resetPanels() {
    $('.grid_thumb .overlay').css({'opacity':'0'});
}

function searchInit() {
    $('#search_input').focus(function() {
        $(this).stop().animate({'width':'200px'}, 300, 'easeInOutQuad');
    }).blur(function() {
        $(this).stop().animate({'width':'120px'}, 300, 'easeInOutQuad');
    });
}

function secretContacts(section) {
    var section_id = section.attr('id');
    var main = $('.main');
    main.css({'visibility':'hidden'});
    $.get('contact/get_contact/'+section_id, function(return_data) {
        section.append(return_data);
        // Flicker fix
        setTimeout(showMain, 50);
        function showMain() {
            main.css({'visibility':'visible'});
        }
    });
}

function navAccordion(nav) {
    var nav = $('.nav_accordion');
    var active_year = $('.active.year', nav);
    var years = $('.year', nav);
    var year_height = 16;
    var animating = false;
    var padding = 0;

    $(window).load(function() {
        years.each(function() {
            var inner_height = $(this).outerHeight();
            $(this).data('inner_height', inner_height);
            if ($(this).index()==years.length-1) {
                years.not(active_year).css({'height':year_height+"px"});
            }
        });
    });

    $('.inactive', nav).live('click', function() {
        if (animating) {
            return false;
        }
        animating = true;

        var this_inner_height = $(this).data('inner_height');

        var active = $('.active.year', nav);
        active.animate({'height':year_height+"px"}).removeClass('active').addClass('inactive');

        $(this).removeClass('inactive').addClass('active');
        $(this).animate({'height':this_inner_height+"px"}, 500, 'easeInOutQuad', function() {
            animating = false;
        });
    });
}

function ieFilmViewer() {
    var film_roller = $('.film_roller', film_viewer);
    var film = $('.film', film_viewer);
    var symbol = $('.video_symbol', film_viewer);
    var film_count = film.length;
}

function filmRoller(film_viewer) {

    var film_roller = $('.film_roller', film_viewer);
    var film = $('.film', film_viewer);
    var symbol = $('.video_symbol', film_viewer);
    var film_count = film.length;
    var original_count = film_count;
    var last_film = film.last();

    if (ieversion == 6) {
        symbol.hide();
    }

    // Clone elements for seamlessnessability
    function newFilm(source) {
        var new_film = document.createElement('figure');
        new_film = $(new_film);
        new_film.addClass('film left inactive replicant');
        new_film.html(source.html());
        return new_film;
    }

    var source = film.eq(film_count-1);
    newFilm(source).prependTo(film_roller);
    source = film.eq(film_count-2);
    newFilm(source).prependTo(film_roller);
    source = film.eq(0);
    newFilm(source).appendTo(film_roller);
    source = film.eq(1);
    newFilm(source).appendTo(film_roller);
    film.not('.replicant').addClass('original');

    film_count = film.length + 4;
    var film_width = 540;
    var film_roller_width = film_width*film_count;
    var start_pos = -film_width*2.5;
    var caption_height = 54;

    film_roller.css({'width':film_roller_width+"px",'left':start_pos+"px"});

    $('.original', film_viewer).each(function() {
        var info = $('.slide_indicator', this);
        var this_number = $(this).index() - 1;
        $('.slide_number', info).text(this_number+"");
        $('.slide_count', info).text(original_count+"");
    });

    var end_position = last_film.position();
    var end_pos = end_position.left + (film_width/2);

    var first_film = $('.original').eq(0);
    first_film.addClass('active');
    $('.film').not('.active').addClass('inactive');
    $('img', '.active').css({'opacity':'1'});
    $('.inactive figcaption', film_viewer).css({'bottom':-caption_height+"px"});

    var slide_timer;
    var slide_duration = 4000;
    // Slideshow timer
    slide_timer = setTimeout(function() {
        changeSlide(true);
    }, slide_duration);

    function changeSlide(forwards, double_time) {
        animating = true;
        var duration;
        if (forwards) {
            var shift_val = -film_width;
        }
        else {
            var shift_val = film_width;
        }
        if (double_time) {
            duration = 40;
        }
        else {
            duration = 100;
        }
        var position = +film_roller.css('left').replace("px","");
        var active = $('.active', film_viewer);
        var image = $('img', active);
        var caption = $('figcaption', active);
        symbol.animate({'opacity':'0'}, 3*duration);
        caption.animate({'bottom':-caption_height+"px"}, 5*duration, 'easeInQuad', function() {
            image.animate({'opacity':'0.4'}, 5*duration, function() {
                film_roller.animate({'left':position+shift_val+"px"}, 15*duration, 'easeInOutQuad', function() {
                    var current = active;
                    current.removeClass('active').addClass('inactive');
                    // If moving forwards
                    if (forwards) {
                        current.next().removeClass('inactive').addClass('active');
                        active = $('.active', film_viewer);
                        // If beyond the end of loop
                        if (active.hasClass('replicant')) {
                            film_roller.css({'left':start_pos+"px"});
                            active.removeClass('active').addClass('inactive');
                            first_film.removeClass('inactive').addClass('active');
                        }
                    }
                    // If moving backwards
                    else {
                        current.prev().removeClass('inactive').addClass('active');
                        active = $('.active', film_viewer);
                        // If beyond the start of loop
                        if (active.hasClass('replicant')) {
                            film_roller.css({'left':-end_pos+"px"});
                            active.removeClass('active').addClass('inactive');
                            last_film.removeClass('inactive').addClass('active');
                        }
                    }
                    active = $('.active', film_viewer);
                    image = $('img', active);
                    caption = $('figcaption', active);
                    var slide_number = active.index() - 1;
                    image.animate({'opacity':'1'}, 5*duration, function() {
                        caption.animate({'bottom':'0'}, 5*duration, 'easeOutQuad', function() {
                            symbol.delay(200).animate({'opacity':'1'}, 8*duration, function() {
                                animating = false;
                                // Slideshow timer
                                slide_timer = setTimeout(function() {
                                    changeSlide(true, false);
                                }, slide_duration);
                            });
                        });
                    });
                });
            });
        });
    }

    $('.active, .video_symbol').live('click', function() {
        var redirect = $('.active h1 a', film_viewer).attr('href');
        window.location = redirect;
    });

    // User override
    $('.inactive', film_viewer).live('mouseenter', function() {
        $('img', this).stop().animate({'opacity':'0.75'}, 200);
    }).live('mouseleave', function() {
        $('img', this).stop().animate({'opacity':'0.4'}, 200);
    }).live('click', function() {
        if (!animating) {
            clearTimeout(slide_timer);
            slide_timer = null;
            if ($(this).index() > $('.active', film_viewer).index()) {
                changeSlide(true, true);
            }
            else {
                changeSlide(false, true);
            }
        }
    });
}

function equalBorders() {
    $('.border').css({'border-color':'#ffffff'});
    $(window).load(function() {
        $('.border').equalHeights(500);
        $('.border').css({'border-color':''});
    });
}

function accordionGroup() {
    $('.accordion_group').each(function(){
        if ($(this).find('.home_image').length > 1)
        {
            $(this).find('.home_image').not(':first').hide();
            $(this).find('section.indent').not(':first').hide();
            accordionGroupNavigation($(this).find('.accordion_group_navigation'));
        }
        else
        {
            $(this).find('.accordion_group_navigation').remove();
        }
    });
}

function accordionGroupNavigation(group) {
    var images,
        texts,
        left_arrow, right_arrow,
        index = 0, old_index, page_indicator;

    left_arrow = group.children('.arrow_left');
    right_arrow = group.children('.arrow_right');
    //page_indicator = group.children('.page_indicator');
    images = group.parent().children('.home_image, .image_wrapper');
    texts = group.parent().children('section.indent');

    function switchImage(old_index, new_index) {
        console.log("switchy switch")

        /*page_indicator.filter(':eq('+old_index+')').removeClass('selected').addClass('deselected');
        page_indicator.filter(':eq('+new_index+')').removeClass('deselected').addClass('selected');*/

        images.filter(':eq('+old_index+')')
            .add(texts.filter(':eq('+old_index+')')).fadeOut(300, function(){
                images.filter(':eq('+new_index+')').add(texts.filter(':eq('+new_index+')')).fadeIn(300, function(){
                    animateBorders(function(){animating = false});
                });
            });
    }

    left_arrow.click(function(){
        console.log("left");
        if (!animating)
        {
            animating = true;
            old_index = index;
            index = ((index + (images.length - 1)) % images.length);
            switchImage(old_index, index);
        }
    });

    right_arrow.click(function(){
        console.log("right");
        if (!animating)
        {
            animating = true;
            old_index = index;
            index = ((index + 1) % images.length);
            switchImage(old_index, index);
        }
    });

}

$('document').ready(function() {

    if ($('.accordigrid').length && !ie) {
        $('.accordigrid').fadeLoad(1000);
    }

    // Empty P tag failsafe
    $('p').filter(function() {
        return $.trim($(this).html()) == '';
    }).remove();

    var template = $('.main').attr('id');
    switch(template) {
        case "home":
            accordiGrid(true);
            $('.image_viewer').each(function() {
                imageViewer($(this));
            });
            //if (ieversion>8) {
                $('.thumb_grid').each(function() {
                    thumbGrid($(this));
                });
            //}
            break;
        case "detail":
            accordiGrid(false);
            $('.image_viewer').each(function() {
                imageViewer($(this));
            });
            //if (ieversion>8) {
                $('.thumb_grid').each(function() {
                    thumbGrid($(this));
                });
            //}
            break;
        case "contact":
            $('.no_spiders').each(function() {
                secretContacts($(this));
            });
            break;
        case "films_landing":
            filmRoller($('.film_viewer'));
            if (!ie) {
                $('.film_viewer').fadeLoad(1000);
            }
            $('.hover_overlay').each(function() {
                thumbGrid($(this));
            });
            break;
        case "film_detail":
            accordiGrid(false);
            break;
        case "exbtn_archive":
            equalBorders();
            break;
        case "news":
            navAccordion();
            equalBorders();
            break;
        case "product":
            $('.image_viewer').each(function() {
                imageViewer($(this));
            });
            equalBorders();
            break;
        case "filter":
            $('.product_grid').each(function() {
                thumbGrid($(this));
            });
            equalBorders();
            break;
    }

    searchInit();

});

