$(function() {

    function newsletter(){
        $('#open-newsletter').click(function(e){
            e.preventDefault();
            $('#newsletter-layer').fadeIn('fast');
        });

        $('#newsletter-layer div.layer').click(function(){
            $(this).parent().fadeOut('fast');
            $('#rp_newsletter_email').val('');
            $('#newsletter_info').empty('');
        });
    }

    newsletter();

    var theWindow = $(window),
    $bg = $("#mainbg"),
    $top = $('.top'),
    top_margin = 170,
    aspectRatio = null;
    
    loadHash();
    mainbg();
    map(); 
        
	$('article').find('section').each(function(){	 	
		if($(this).find('figure').length){
		  slideImages('#'+$(this).find('figure').attr('id'));				
		}
	})
    
    $('#scrollbar1').tinyscrollbar();        
    $(".infield label").inFieldLabels();

    if($('body').hasClass('o_hidden'))
        $('html').css('overflow','hidden');
    else
        $('#btn-down').fadeIn('fast');
        
    function mainbg(){
        if($bg.length){
            
            $('body').prepend('<div id="spin_mainbg" style="position: absolute; top: 50%; left: 50%;">');
            
            spin('spin_mainbg');
            
            var main_bg = $bg.attr('src');
        

            $('#spin_mainbg').imageLoader({
                images: [ main_bg ],
                enableSplashScreenImage: 0,
                enableSplashScreenText: 0
            }, function(){
                aspectRatio = $bg.width() / $bg.height()
                resizeBg();
                $bg.fadeIn();
                $("#spin_mainbg").remove();
            });
        }
    }
    
    function slideImages(figure){

      $(figure).append('<div class="imgLoader"></div>');
      
      $(figure).prepend('<div id="spin'+figure.replace("#", "_")+'" style="position: absolute; top: 50%; left: 50%;">');
      
      spin('spin'+figure.replace("#", "_"));
      
      var IMGs = new Array();

      $(figure+' ul').find('img').each(function() {
        IMGs.push({src: $(this).attr('src')});
      });

      if(IMGs.length == 0){  
       $(figure+' .imgLoader').remove();
       $('#spin'+figure.replace("#", "_")).remove();
      }

      $(figure+' .imgLoader').imageLoader({
             images: IMGs,
             enableSplashScreenImage: 0,
             enableSplashScreenText: 0
          }, function(){
              
            $(figure+' .imgLoader').remove();
            
            if(IMGs.length > 1)
            {             
                $(figure+' ul')
                .cycle({
                    fx:     'fade',
                    speed:  '600',
                    timeout: 6000, 
                    //after: onAfter,    
                    next:   figure+' nav a.next',
                    prev:   figure+' nav a.prev'                    
                }).prev('nav').find('a').fadeIn();
            }
            else
            {
                $('#spin'+figure.replace("#", "_")).remove();
                $(figure+' ul li').fadeIn();                
            }
            
            

        });
    }
    
    function onAfter(currSlideElement, nextSlideElement, options, forwardFlag) {
     
        if(options.prev == "#figure_vis nav a.prev"){
            $('#figure_vis figcaption').empty();
            $('#figure_vis figcaption').text(this.title);        
        }
    }    
        
    function resizeBg() {

        if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
            $bg
            .removeClass()
            .addClass('bgheight');
                    
        } else {
            $bg
            .removeClass()
            .addClass('bgwidth');
        }
        
        $('#mainbg-top').css('width', $bg.width()+'px'); 
    }
    
    function map() {
        if($('#mapbg').length){
            $('#map, #mapbg').css({
                'position': 'fixed',
                'top': 0,
                'left': 0,
                'width':  theWindow.width(),
                'height': theWindow.height(),
                'z-index': 1
            });
        }
    }

    theWindow.resize(function() {
        map();
        resizeBg();
       
        $('.top-left').css('width', ($(window).width() - $top.width() ) / 2);
        $('.top-right').css('width', ($(window).width() - $top.width() ) / 2 + 1);
        
        $('#main,#contentbg').css('height', $(window).height());
        $('#article-top').css('height', $(window).height());
        
        if(theWindow.width() < $top.width()){
            $('#main-nav').css('right', ($top.width()-theWindow.width())+'px');
        }
        else{
            $('#main-nav').css('right', '0px'); 
        }
        
        if( theWindow.height() > ( 330 + $('article section').last().height())){
            var padding_bottom = theWindow.height()-(200 + $('article section').last().height());
            $('article .article-content').css('padding-bottom',padding_bottom);
        } 
        else{
            $('article .article-content').css('padding-bottom','130');  
        }
    }).trigger('resize');

    $('#btn-down').hover(function(){
        $('.more-tip').stop(true, true).fadeToggle();
    })
    $('#sub-nav').fadeIn('600');

    window.onscroll = function()
    {
        if(!$('#btn-down').hasClass('inactive')){
            resizeBg();  
            var scrollTop = document.documentElement.scrollTop;
		
            if(!scrollTop)
                scrollTop = $('body').scrollTop();
		   
            if (scrollTop > 0) {
                $('#short-info , #btn-down').fadeOut('fast');
               // $('#sub-nav').fadeIn('600');
            } else {
                $('#short-info, #btn-down').fadeIn('fast');
               // $('#sub-nav').fadeOut('600');
            }
        
            /*if (scrollTop > 0 && scrollTop < theWindow.height()){
                if(!$('#btn-down').hasClass('going_up') && !$('#btn-down').hasClass('go_down'))
                    contentGoUp()
            
                if($('#btn-down').hasClass('go_down') && !$('#btn-down').hasClass('going_down') )
                    contentGoDown();
            }
            else{
                $('#btn-down').removeClass('going_up').removeClass('going_down');
            }*/
        
            if (scrollTop > theWindow.height() / 2 && scrollTop < theWindow.height()) 
                $('#mainbg-top').fadeIn('fast');
            else
                $('#mainbg-top').fadeOut('fast');
        
            if (scrollTop >= theWindow.height()) {
                $('#contentbg, #contentbg-top').css('position', 'fixed').fadeIn('slow');
                $('#article-top').css('position', 'fixed');
                $('.couple').fadeIn('fast');
                //$bg.fadeOut('fast');
            } else {
                $('#contentbg, #contentbg-top').css('position', 'absolute').fadeOut('slow');
                $('#article-top').css('position', 'relative');	
                $('.couple').fadeOut('slow');
                //$bg.fadeIn('slow');
            }  

            if (scrollTop >= theWindow.height() + 5) {
                $('.sep').fadeIn('fast');
            } else {
                $('.sep').fadeOut('fast'); 
            }  
        
            $('article').find('section').each(function(e){
            
                var sub_nav_class = $(this).attr('id');
                var sub_nav_li = $('ul#sub-nav>li>a.'+sub_nav_class+'').parent('li');
                
                var section_top = parseInt($(this).offset().top - top_margin - 30);
                var section_height = parseInt($(this).height());
                var section_bottom = section_top+section_height;
                
                //if(e == $(this).siblings().length)
            
                if (scrollTop >= section_top && scrollTop <= section_bottom){ 
                  if(!sub_nav_li.hasClass('active')){
                    sub_nav_li.addClass('active');
                    window.location.hash = '_'+sub_nav_class;
                	}
                }
                else{
                  if(sub_nav_li.hasClass('active')){
                    sub_nav_li.removeClass('active');
                    }
                }			
            });
        }   
    }

    
    function contentGoDown() {  
        $('html,body').stop(true,true).animate({
            scrollTop: 0
        }, 600, 'linear' ,function(){
            $('#btn-down').removeClass('go_down');
        });
            $('#btn-down').addClass('going_down');
              
    }  
    
    function contentGoUp() {  
        $('html,body').stop(true,true).animate({
            scrollTop: theWindow.height()
        }, 1000, 'easeInOutSine' ,function(){
            //$('#btn-down').addClass('go_down');  
        });
            //$('#btn-down').addClass('going_up');        
    }     
    
    $('#btn-down').click(function(){
        contentGoUp();
        return false;        
    });


    
    $('#sub-nav li a').click(function(){
        
        var section_id = $(this).attr('class');
        var section_top = $('#'+section_id).offset().top-top_margin+17;

        $('html,body').animate({
            scrollTop: section_top
        }, 1000, 'easeInOutSine', function(){
            window.location.hash = '_'+section_id;
        });
        return false;
    });  
    
    $('#build li').click(function(){
        $(this).parent('ul').find('a').removeClass('active');
        $(this).find('a').addClass('active');
        return false;
    });  
    
    function loadHash() {
     	$('article , #article-top').fadeIn('fast');
        var $hash = window.location.hash.substr(2);
        if($hash){
            if($('#'+$hash).length){
                var section_top = $('#'+$hash).offset().top+theWindow.height()-top_margin;

                $('html,body').animate({
                    scrollTop: section_top
                }, 1000, 'easeOutSine');               
            }
        }
    }
    

    function spin(element){

        var opts = {
            lines: 12, // The number of lines to draw
            length: 7, // The length of each line
            width: 4, // The line thickness
            radius: 10, // The radius of the inner circle
            color: '#463b4a', // #rgb or #rrggbb
            speed: 1, // Rounds per second
            trail: 60, // Afterglow percentage
            shadow: false // Whether to render a shadow
        };

        var target = document.getElementById(element);
        var spinner = new Spinner(opts).spin(target);

        target.appendChild(spinner.el);

    }    
    
});

