jQuery(function() {
	var $ = jQuery;
	var sections = $('.section');
	var menu_items = $('.menu-item > a');
	var loadedSectionsCount = 0;
	
	//
	// jQuery plugins
	//
	
	$.fn.launchSearch = function(){
        return $(this).each(function(){
            hs.htmlExpand(this, {
                src:$('#search').parent('form').attr('action')+'?s='+$(this).val(), 
                objectType: 'ajax', 
                width: 830,
                allowWidthReduction: false,
                align: 'center',
                contentId: 'search-popup',
                preserveContent: false,
                cacheAjax: false
            });
        });
    };
    
    $.fn.labeledInput = function(){
        return $(this).each(function(){
            var me = $(this);
            me.data('caption', me.val());
            me.focus(function(){
                if(me.val() == me.data('caption')) me.val('');
            }).blur(function(){
                if(me.val() == '') me.val(me.data('caption'));
            });
        });
    };
    
    String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)};
    
    //
    // Highslide plugins
    //
	
	hs.Expander.prototype.onAfterExpand = function (sender)
    {
        var search_popup = $(sender.content);
        search_popup.find('a.read_more').click(function(){
            scroll_to_hash($(this).attr('rel'), true);
            hs.close();
            return false;
        });
        search_popup.find('input').keypress(function(e){
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                hs.close();
                $(this).launchSearch();
                return false;
            }
        });
        
    };
    
    hs.Expander.prototype.onBeforeExpand = function (sender)
    {
        var search_popup = $(sender.content);
        search_popup.find('.highslide-body').attr('class', 'highslide-body highslide-'+$('body').attr('id'));
    };

	
	//
	// methods
	//
	
	function scroll_to_section(section, updateHash, callback) {
		if(!section.hasClass('active-section')) {
			
			var menu_link = $('a[rel="'+section.attr('id')+'"]');
			
			// ruban
			$('#menu_ribbon').stop().animate({
				top: (menu_link.prev('.menu_item_bg').offset().top-$(window).scrollTop())+'px',
				height: menu_link.prev('.menu_item_bg').height()+'px'
			});
			
			// maj de l'Ã©tat du menu
			$('.active-menu-item').removeClass('active-menu-item').prev('.menu_item_bg').animate({opacity:0.25});
			menu_link.addClass('active-menu-item').prev('.menu_item_bg').animate({opacity:0.75});
			
			// maj de l'Ã©tat des sections
			$('.active-section').removeClass('active-section');
			section.addClass('active-section');
			
			// scroll
			$('html,body').stop().animate({ scrollTop: section.offset().top+'px' }, callback);
			
			// hash
			if(updateHash) {
				window.location.href = '#'+section.attr('id').replace('section-', 'section_');
				$('#print_link').attr('href', section.attr('source')+'?print=1');
			}
			
		}
		
	}
	
	function scroll_to_post(section, post, forceScrollToSection, updateHash)
	{	
		if(forceScrollToSection && !section.hasClass('active-section')) {
			scroll_to_section(section, false, function(){
				scroll_to_post(section, post, false, updateHash);
			});
		} else if(!post.hasClass('active-post')) {
		
			// maj des posts
            section.find('.posts_wrapper').stop().animate({left: (-1*post.position().left)+'px'});
			section.find('.active-post').removeClass('active-post').animate({opacity: 0.5});
            post.addClass('active-post').animate({opacity: 1});
            
            // maj des fleches de navigation
            var next_btn = section.find('.next_entry');
        	var prev_btn = section.find('.prev_entry');
            var posts = section.find('.post_wrapper');
            var index = posts.index(section.find('.active-post'));
        	if(index<1) prev_btn.fadeOut();
        	else prev_btn.fadeIn();
        	if(index==(posts.length-1)) next_btn.fadeOut();
        	else next_btn.fadeIn();
        	
        	// maj du sous-menu
        	var sub_menu = section.find('.sub_menu');
        	if(sub_menu.length>0) {
        		var sub_bg = section.find('.sub_menu_item_bg');
        		var active_item = $(sub_menu.find('.sub_menu_item').get(index));
        		sub_menu.find('.active-item').removeClass('active-item');
        		active_item.addClass('active-item');
        		sub_bg.stop().animate({
		            left: (active_item.position().left-2),
		            top: (active_item.position().top-1),
		            width: (active_item.outerWidth()+6)+'px'
		        }).fadeIn();
        	}
        	
        	// hash
			if(updateHash) {
				window.location.href = '#'+post.find(':first-child').attr('id').replace('post-', 'post_');
				$('#print_link').attr('href', section.find('.active-item').attr('href')+'?print=1');
			}
        }
	}
	
	function scroll_to_hash(hash, updateHash)
	{
		hash = hash.replace('#', '');
		if(hash.startsWith('section')) scroll_to_section($('#'+hash.replace('_', '-')));
		else if(hash.startsWith('post')) {
			var post = $('#'+hash.replace('_', '-'));
			scroll_to_post(post.parents('.section'), post.parent(), true, updateHash);
		}
	}
	
	function scroll_to_preview(preview, item)
	{
		if(item) {
			preview.find('.preview_items').stop().animate({left: (-1*item.position().left)+'px'});
			preview.find('.active-preview').removeClass('active-preview').animate({opacity: 0.5});
			item.addClass('active-preview').animate({opacity: 1});
		}
		 // maj des fleches de navigation
        var next_btn = preview.find('.next_preview');
    	var prev_btn = preview.find('.prev_preview');
        var items = preview.find('.preview_item');
        if(items.length>0) {
        	var index = items.index(preview.find('.active-preview'));
    		if(index<1) prev_btn.fadeOut();
    		else prev_btn.fadeIn();
    		if(index==(items.length-1)) next_btn.fadeOut();
    		else next_btn.fadeIn();
        } else {
        	prev_btn.hide();
        	next_btn.hide();
        }
	}
	
	function section_loaded(section)
	{        
		section.find('.posts_wrapper').width('20000px');
		section.find('h1').click(function(){
			scroll_to_section(section, true, true);
		});
		section.find('.next_entry').click(function() {
            scroll_to_post(section, section.find('.active-post').next('.post_wrapper'), true, true);
            return false;
        });
        section.find('.prev_entry').click(function() {
            scroll_to_post(section, section.find('.active-post').prev('.post_wrapper'), true, true);
            return false;
		});
		section.find('.post_wrapper').click(function(e){
			if(!$(this).hasClass('active-post')) {
				scroll_to_post(section, $(this), true, true);
				return false;
			}
		});
		
		section.find('.sub_menu_item').click(function(){
			scroll_to_post(section, $('#'+$(this).attr('rel')).parent(), true, true);
			return false;
		});
		section.find('a.preview-link').find('img').load(function(){
            $(this).parent().fadeIn();
        });
        section.find('a.preview-nav-link').click(function(e){
        	if($(this).hasClass('preview_item')||$(this).parents('.preview_item').hasClass('active-preview')) {
        		var post = $('#'+$(this).attr('rel'));
				scroll_to_post(post.parents('.section'), post.parent(), true, true);
        	} else {
        		scroll_to_preview($(this).parents('.preview_wrapper'), $(this).parents('.preview_item'));
        	}
            return false;
        });
        setTimeout(function(){
			scroll_to_post(section, $(section.find('.post_wrapper').get(0)));
        }, 500);
        // preview
		section.find('.preview_wrapper').each(function(){
			var preview = $(this);
			var items = preview.find('.preview_item');
			if(items.length>0) scroll_to_preview(preview, $(items.get(0)));
			else scroll_to_preview(preview);
        	preview.find('.next_preview').click(function() {
		        scroll_to_preview(preview, preview.find('.active-preview').next('.preview_item'));
		        return false;
		    });
		    preview.find('.prev_preview').click(function() {
		        scroll_to_preview(preview, preview.find('.active-preview').prev('.preview_item'));
		        return false;
			});
			preview.find('.preview_box').click(function(event){
				scroll_to_preview(preview, $(this));
			});
        });
	}
	
	function all_sections_loaded()
	{
		$('.tag_link').click(function() {
            hs.htmlExpand(this, {
                src:$(this).attr('source'), 
                objectType: 'ajax', 
                width: 830,
                align: 'center',
                contentId: 'search-popup',
                preserveContent: false
            });
            return false;
        });
		
		$('.section:last').append('<div class="bottom_filler"></div>');
		
		// scroll to element onload
		setTimeout(function() {
			scroll_to_hash(window.location.hash);
		}, 750);
		
		// tags
		$('.tag_link').click(function() {
            hs.htmlExpand(this, {
                src:$(this).attr('href'), 
                objectType: 'ajax', 
                width: 830,
                align: 'center',
                contentId: 'search-popup',
                preserveContent: false
            });
            return false;
        });
		
		// gallery
		$('img.size-thumbnail, img.size-medium').each(function(){
            $(this).parent().click(function(){return hs.expand(this, {align: 'center'});});
        });
        
        // fixes
        $('.content').find('a').each(function(){
            if($(this).find(':first-child').is('img')) $(this).addClass('image-link');
        });
		
	}
	
	//
	// menu
	//
	
	$('.menu-item').find('a').hover(function(){
		if(!$(this).hasClass('active-menu-item')) $(this).prev('span.menu_item_bg').stop().animate({opacity:0.75});
	}, function(){
		if(!$(this).hasClass('active-menu-item')) $(this).prev('span.menu_item_bg').stop().animate({opacity:0.25});
	}).click(function(){
		scroll_to_section($('#'+$(this).attr('rel')), true);
		return false;
	});
	
	$('#logo').click(function(){
		$('#menu_ribbon').stop().animate({top: '0px', height: '30px'});
		$('.active-menu-item').removeClass('active-menu-item').prev('.menu_item_bg').animate({opacity:0.25});
		$('.active-section').removeClass('active-section');
		$('#main').stop().animate({top: '0px'});
		$('html,body').stop().animate({ scrollTop: '0px' });
		window.location.href = '#home';
		
		return false;
	});
	
	//
	// chargement du contenu
	//
	
	$('#main').css('overflow', 'hidden');
	sections.each(function(){
		var section = $(this);
		section.append($('<img src="'+theme_path+'/images/axel-loader.gif" />'));
		section.load(section.attr('source')+'?ajax=1', function() {
			loadedSectionsCount++;
			section_loaded(section);
			if(loadedSectionsCount==sections.length) all_sections_loaded();
		});
	});

	//
	// sÃ©lection de la couleur de fond
	//
	
    $('#bg_color_selector a').click(function() {
        var nclass = $(this).attr('class');
        var oclass = $('body').attr('id');
        $('body').removeClass(oclass).addClass(nclass).attr('id', nclass);
        $('#bg_color_selector > a.active').removeClass('active');
        $(this).addClass('active');
        return false;
    });
    
    //
    // champs libellÃ©s
    //
    
    $('#search').labeledInput();
    
    //
    // redimensionnement du texte
    //
    
    var font_step = 0;
    var font_max = 3;
    $('#font_resizer').click(function(){
        if(font_step < font_max) {
            $('.resizable_text').each(function(){
                var $t = $(this);
                var currentFontSize = $t.css('font-size');
                if(!$t.data('font-size')) $t.data('font-size', currentFontSize);
                var currentFontSizeNum = parseFloat(currentFontSize, 10);
                var newFontSize = currentFontSizeNum*1.1;
                $t.css('font-size', newFontSize);
            });
            font_step++;
        } else {
            $('.resizable_text').each(function(){
                $(this).css('font-size', $(this).data('font-size'));
            });
            font_step = 0;
        }
        return false;
    });
    
    //
    // recherche
    //
    
	var searchInput = $('#search');
    searchInput.data('oHeight', searchInput.height());
    searchInput.data('oWidth', searchInput.width());
    searchInput.keypress(function(e){
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).launchSearch();
            return false;
        }
    }).focus(function(){
        $(this).stop().animate({
            width: '285px',
            height: '41px'
        }).css('fontSize', '14pt');
    }).blur(function(){
        $(this).stop().animate({
            width: searchInput.data('oWidth'),
            height: searchInput.data('oHeight')
        }).css('fontSize', '11pt');    
    });
    
    //
    // copyright popup
    //
    
	$('#copyright-trigger').click(function(){
        hs.htmlExpand(this, {
            src:$('#copyright-trigger').attr('href')+'?ajax=1', 
            objectType: 'ajax', 
            width: 830,
            allowWidthReduction: false,
            align: 'center',
            contentId: 'copyright-popup',
            preserveContent: false,
            cacheAjax: false
        });
        return false;
	});
});
