/**
 * @file scripts.js
 */
var car = null;

/**
 *   Fonction de chargement de l'ajax
 */
function ajaxLoadContent(target){
    $.ajax({
        url: target,
        method: 'get',
        data: 'ajax=1',
        dataType: 'text',
        success: function(_msg){
            $('#content').fadeOut(300, function(){
                $('#content').html(_msg);
                $("link, .spip-admin-float", $("#content")).remove();
                $('#content').fadeIn(800);
                initCufon();
                initLightBox();
                initScroll();
                centerImages();
                heightUpdate.update();
                interfaceSite.imagesSpaces();
            });
        }
    });
} 

/**
 * Init de l'ajax
 */
function initAjax(){
    $(".ajax").live("click", function(){
        ajaxLoadContent($(this).attr('href'));
		if ($(this).attr('rel') != null) {
			window.location.hash = $(this).attr('rel');
		}
        return false;
    });
    
}

/**
 * Interface Site
 */
var interfaceSite = {

    /**
     * Gestion du resize de l'image d'arriere plan
     */
    videoIntro: function(){
        var flashvars = {};
        var params = {
            allowFullScreen: 'true',
            allowscriptaccess: 'always'
        };
        var attributes = {/*wmode   : 'transparent'*/};
        swfobject.embedSWF("tpl/swf/loaderIntro.swf", "videoIntro", "100%", "100%", "9.0.0", "tpl/swf/expressInstall.swf", flashvars, params, attributes, introHandler);
        $('.sommaire #content, .sommaire #videos, .sommaire #menu li').hide();
    },
    /**
     * Gestion du resize de l'image d'arriere plan
     */
    resizeBackground: function(){
        $("#background img:eq(0)").css({
            'height': "auto",
            'width': "auto"
        });
        var prop;
        if ($("#background img:eq(0)").height() == 0) {
            $("#background img:eq(0)").height(1080);
        }
        if ($("#background img:eq(0)").width() == 0) {
            $("#background img:eq(0)").width(1920);
        }
        prop = parseInt($("#background img:eq(0)").height()) / parseInt($("#background img:eq(0)").width());// proportions largeur/hauteur
        var wW = $(document).width();// largeur de la fentre
        var wH = $(document).height();// hauteur de la fenetre
        $("#background img:eq(0)").width(wW);
        if (!isNaN(prop)) {
            $("#background img:eq(0)").height(parseInt($("#background img:eq(0)").width()) * prop);
            if ($("#background img:eq(0)").height() < wH) {
                prop = parseInt($("#background img:eq(0)").width()) / parseInt($("#background img:eq(0)").height());
                $("#background img:eq(0)").height(wH);
                $("#background img:eq(0)").width(parseInt($("#background img:eq(0)").height()) * prop);
            }
            $("#background img:eq(0)").center();    
        }
    },
    /**
     * Carrousel videos
     */
    videos: function(){
        car = $("#videos ul").carrouselLite({
            speed: 500,
            dispTimeout: 1000,
            dispNumber: 3,
            api: true
        });
        $('#videos .prev a').click(function(){
            car.prev();
            return false;
        });
        $('#videos .next a').click(function(){
            car.next();
            return false;
        });
    },
    /**
     * Pour mettre a jour l'image
     */
    updateImage: function(){
        $("#background").removeAttr("style").children("img:eq(0)").removeAttr("style");
        interfaceSite.resizeBackground();
    },
    /**
     * Pour mettre a jour l'image
     */
    updateBackground: function(url){
        if (url != "") {
            $.preload([url], {
                base: '/',
                ext: '',
                onFinish: interfaceSite.backgroundLoaded
            });
        }
        else {
            url = 'IMG/moton15.jpg';
            $.preload([url], {
                base: '/',
                ext: '',
                onFinish: interfaceSite.backgroundLoaded
            });
        }
    },
    backgroundLoaded: function(e){
        var image = "<img src=" + e.image + " />";
        $("#background").prepend(image);
        interfaceSite.updateImage();
        $("#background img:eq(1)").fadeOut(500, function(){
            $(this).remove();
        });
    },
    /**
     * du rollOver pour les cufon
     */
    over: function(elem, colorOver, colorNormal){
        if (!colorOver) {
            colorOver = "#faa61a";
        }
        if (!colorNormal) {
            colorNormal = "#FFFFFF";
        }
        $(elem).mouseenter(function(){
            $(this).css("color", colorOver);
            Cufon.replace($(this));
        }).mouseleave(function(){
            $(this).css("color", colorNormal);
            Cufon.replace($(this));
        });
    },
    /**
     * Gestion du sous menu
     */
    ssmenu: function(){
        $(".ssmenu li").hide();
        
        $('.ssmenu li a').click(function(){
            $(this).parent().parent().children(".actif").removeClass("actif");
            $(this).parent().addClass("actif");
            var target = $(this).attr("href");
			if ($(this).attr('rel') != null)
            	window.location.hash = $(this).attr('rel');
            ajaxLoadContent(target);
            return false;
        });
        
        $("#menu ul li a").click(function(){
            var target;
            var linkImg = $(this).parent("li").attr("rel");
            if (linkImg != "") {
                interfaceSite.updateBackground(linkImg);
            }
            $("#menu ul li.actif").removeClass("actif");
            $(this).parent().addClass("actif");
            $('.ssmenu li.actif').removeClass("actif");
            var name = $(this).attr("class");
            var compteur = false;
            $(".ssmenu").hide();
            
            if ($(".ssmenu").hasClass(name)) { //on ouvre le bon sous menu
                var ssmenu = $(".ssmenu." + name);
                var ssmenuChilds = ssmenu.children("li");
                var menuLength = ssmenuChilds.length;
                ssmenu.show();
                ssmenuChilds.hide();
                for (var i = 0; i < menuLength; i++) {
                    ssmenuChilds.eq(i).delay((menuLength - i) * 150).slideDown();
                }
            }
            else {// si il n'y a pas de sous menu, on charge la rubrique en ajax
                target = $(this).attr('href');
                if ($(this).attr('rel') != null)
            		window.location.hash = $(this).attr('rel');
            	ajaxLoadContent(target);
                return false;
            }
            if ($(this).attr('rev') == "article_affiche") {
                target = $(this).attr('href');
                if ($(this).attr('rel') != null)
            		window.location.hash = $(this).attr('rel');
            	ajaxLoadContent(target);
            }
            
            return false;
        });
    },
    
    imagesSpaces: function(){
			$("#article .scroll img").each(function(){
				var elm = $(this);
				var hspace = 0;
				var vspace = 0;
				if(elm.attr("hspace")){
					hspace =  elm.attr("hspace");
					elm.css("margin-left", hspace);
					elm.css("margin-right", hspace);
				}
				if(elm.attr("vspace")){
					vspace =  elm.attr("vspace");
					elm.css("margin-top", vspace);
					elm.css("margin-bottom", vspace);
				}
			});
			$("#article .scroll table").each(function(){
				var elm = $(this);
				var pad = 0;
				if(elm.attr("cellpadding")){
					pad =  elm.attr("cellpadding");
					$("td", this).css("padding", pad+"px");
				}
			});
		}
};
/**
 * Cufon
 */
function initCufon(){
    Cufon.replace('h2, h3, #menu li a, .ssmenu li a, #videos ul li a, p.liens a, #article .back a');
    interfaceSite.over(".ssmenu li a", "#FFFFFF", "#303030");
    interfaceSite.over("#videos ul li a, #intro p.liens a", "#faa61a", "#FFFFFF");
    interfaceSite.over("#news p.liens a, #news-liste p.liens a", "#faa61a", "#303030");
}
/**
 * Caroussel de news
 */
var carrouselIntro = {
    //Variables
    _obj: {},
    _childs: {},
    _length: {},
    _current: {},
    //Initialisation
    init: function(obj){
        var _obj = carrouselIntro._obj = $(obj);
        var _childs = carrouselIntro._childs = _obj.children(".wrapper");
        var _length = carrouselIntro._length = _childs.size();
        var _current = carrouselIntro._current = 0;
        for (var i = 0; i < _length; i++) {
            if (i < _current || i > _current + 2) {
                _childs.eq(i).hide();
            }
        }
        _obj.children(".navigation").children(".prev").click(function(){
            carrouselIntro.move(-1);
            return false;
        });
        _obj.children(".navigation").children(".next").click(function(){
            carrouselIntro.move(1);
            return false;
        });
    },
    //Deplacement
    move: function(_index){
        if (carrouselIntro._current + _index >= 0 && carrouselIntro._current + _index <= carrouselIntro._length - 3) {
            carrouselIntro._current = carrouselIntro._current + _index;
            var _current = carrouselIntro._current;
            for (var i = 0; i < carrouselIntro._length; i++) {
                if (i < _current || i > _current + 2) {
                    carrouselIntro._childs.eq(i).hide();
                    //carrouselIntro._childs.eq(i).slideUp();
                }
                else {
                    carrouselIntro._childs.eq(i).show();
                    //carrouselIntro._childs.eq(i).slideDown();
                }
            }
        }
        
        
    }
};


/**
 * Fonction appelee a la fin de l'intro flash
 */
function flashExitHandler(callback){
    $("#videoIntro").remove();
    $("#background").show();
    interfaceSite.updateImage();
    initScroll();
    $("#videos").delay(500).effect("slide", {
        direction: "down"
    }, 500);
    var menuLength = $("#menu li").length;
    for (var i = 0; i < menuLength; i++) {
        $("#menu li").eq(i).delay(500 + (((menuLength - i)) * 150)).slideDown();
    }
    $("#content").delay(1500).show(500, function(){
        heightUpdate.init();
    });
    $("body").removeClass("flash");
	if ($.isFunction(callback)) {
		callback();
	}
}
/**
 * Est ce qu'on a pose le flash ou pas
 */
function introHandler(e){
    if (!e.success) {
        flashExitHandler();
    }
    else {
        $("body").addClass("flash");
        $("#background").hide();
    }
}
/**
 * Appele au chargement de la page
 */
function moveTo(loc){
    loc = loc.substring(1, loc.length);
    $.ajax({
        url: 'getURL.php',
        method: 'get',
        data: 'loc=' + loc + '&id_parent=' + id_parent,
        success: function(msg){
            ajaxLoadContent(msg);
        }
    });
}
/**
 * Ajustement de la hauteur
 */
var heightUpdate = {
    init: function(){
        heightUpdate.calculTop();
        
    },
    calculTop: function(){
    
        if (!$("body").hasClass("flash")) {
            $('#content > div:first').each(function(){
                var newLeft;
                var elmt = $(this);
                /**
                 ** Redimensionnement horizontal
                 **/
                $("body").width("100%");
                newLeft = parseInt($("#navigation .wrapper").offset().left) + 400;
                var curLeft = newLeft + parseInt($(this).width()) + parseInt($(this).css("padding-left")) + parseInt($(this).css("padding-right"));
                $(this).css("left", newLeft + 'px');
                if (curLeft > $(window).width()) {
                    $("body").width(curLeft + 100);
                    newLeft = parseInt($("#navigation .wrapper").offset().left) + 400;
                    $(this).css("left", newLeft + 'px');
                }
                else {
                    $("body").width("100%");
                }
                /**
                 ** Redimensionnement vertical
                 **/
                $("body").height("100%");
                if ($(this).offset().top <= 20) {
                    $("body").height($(window).height() + Math.abs($(this).offset().top) + 20);
                }
                else {
                    $("body").height("100%");
                }
            });
        }
        else {
            $("body").height("100%");
            $("body").width("100%");
        }
    },
    update: function(){
        var top = heightUpdate.calculTop();
    }
};
/**
 * Lightbox sur les articles
 */
function initLightBox(){
    $("img.fancybox").each(function(){
        var elmt = $(this);
        if (!elmt.attr("align")) {
            elmt.parent("a").fancybox({
                overlayShow: true,
                overlayOpacity: 0.8,
                overlayColor: '#FFF'
            }).css("position", "relative").prepend('<img src="tpl/img/interface/loupe.png" alt="loupe" class="pngbg" style="position:absolute; bottom:10px; right: 10px;" />');
        }
        else {
            elmt.parent("a").fancybox({
                overlayShow: true,
                overlayOpacity: 0.8,
                overlayColor: '#FFF'
            });
        }
    });
}
/**
 * Scroll sur les articles
 */
function initScroll(){
    $("#article .wrapper .scroll").jScrollPane({
        reinitialiseOnImageLoad: true,
        showArrows: true,
        arrowSize: 13
    });
}
/**
 * Centre les images sur les intros de news
 */
function centerImages(){
    $(".visuel").each(function(){
        $("img", this).removeAttr("width").removeAttr("height").removeAttr("style");
        var _h = parseInt($(this).height());
        $("img", this).load(function(){
            var _imgH = parseInt($(this).height());
            $(this).css("top", -(_imgH / 2 - _h / 2));
        });
        var _imgH = parseInt($("img", this).height());
        $("img", this).css("top", -(_imgH / 2 - _h / 2));
    });
    
}
/**
 * Ajax formulaires contact
 */
function initForm(){
    $(".spip_forms form").live('submit', function(){
        var elmt = $(this);
        var target = elmt.attr('action');
        var params = target.split('?')[1];
        
        var serial = elmt.serialize();
        
        target = target.split('?')[0];
        
        $.ajax({
            url: target,
            method: 'post',
            data: serial,
            dataType: 'html',
            success: function(_msg){
                $('#content').fadeOut(300, function(){
                    $('#content').html(_msg);
                    $("link, .spip-admin-float", $("#content")).remove();
                    $('#content').fadeIn(800);
                    interfaceSite.resizeBackground();
                    initCufon();
                    initLightBox();
                    initScroll();
                    centerImages();
                    heightUpdate.update();
                });
            }
        });
        
        return false;
        
    });
}
/**
 * Png fix pour les menus
 */
var pxPath = 'tpl/img/interface/px.gif';
function fixPng(elmt){
    var container;
    if ($.browser.msie && $.browser.version == 6) {
        if (elmt) {
            container = $(elmt);
        }
        else {
            container = $('html');
        }
        var oImage = $('img', container);
        
        if (!oImage.length) {
            return;
        }
        for (var i = 0; i < oImage.length; i++) {
            if (oImage[i].src.indexOf('.png') > -1) {
                $(oImage[i]).css("background", "none");
                $(oImage[i]).css("filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + oImage[i].src + '", sizingMethod="image")');
                $(oImage[i]).attr("src", pxPath);
            }
        }
    }   
}
/**
 * Navigate suivant le hash
 */
function navigate(){
	var u = window.location.hash;
	u = u.substr(1);
	var a = u.split('/');
	var t = "";
	if (a.length > 1) {
		for (var i = 0; i < a.length; i++) {
			t += (t == "" ? "" : "/") + a[i];
			if (i == 0) {
				// affichage du sous menu
				$this = $('a[rel=' + t +']');
				$("#menu ul li.actif").removeClass("actif");
	            $this.parent().addClass("actif");
	            $('.ssmenu li.actif').removeClass("actif");
				var name = $this.attr("class");
	            $(".ssmenu").hide();
	            if ($(".ssmenu").hasClass(name)) { //on ouvre le bon sous menu
	                var ssmenu = $(".ssmenu." + name);
	                var ssmenuChilds = ssmenu.children("li");
	                var menuLength = ssmenuChilds.length;
	                ssmenu.show();
	                ssmenuChilds.hide();
	                for (var j = 0; j < menuLength; j++) {
	                    ssmenuChilds.eq(j).delay((menuLength - j) * 150).slideDown();
	                }
	            }
			}
			else {
				// chargement de la page
				if ($('a[rel=' + t +']').length == 1)
					$('a[rel=' + t +']').trigger('click');
			}
		}
	}
	else {
		if ($('a[rel=' + u +']').length == 1)
			$('a[rel=' + u +']').trigger('click');
	}
}
/**
 * On load
 */
$(window).load(function(){
    interfaceSite.resizeBackground();
    centerImages();
	if (location.hash && location.hash.length > 1) {
		flashExitHandler(navigate);
    }
});

/**
 * On Ready
 */
$(document).ready(function(){
    interfaceSite.videos();
    fixPng("#menu ul li");
    fixPng(".ssmenu li");
    initCufon();
    heightUpdate.calculTop();
    interfaceSite.ssmenu();
    initLightBox();
    interfaceSite.videoIntro();
    initForm();
    // resize
    $(window).resize(function(){
        heightUpdate.update();
        interfaceSite.resizeBackground();
    });
    flashExitHandler();
    initAjax();
    
});

