// simplification du débug...
function _d( log ) {
	Debug.log( log );
}

// optimisation, mise en cache des $("elem") 
var e = []; //tableau contenant le cache des éléments

function ce(id) { 
    //Retourne l'objet (du cache, et s'il n'existe pas, va la chercher...)

    if ( !e[id] ) {
        e[id] = $(id);
    }

    return e[id];
}

function isset(variable){

	if ( typeof( window[variable] ) != "undefined" ) {
		return true;
	} 

	return false;
}

// Creating custom :external selector
$.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
            && (obj.hostname != location.hostname);
};


var App = {

	timerResize: null,
	isIe6: null,

	init: function() {
		//alert("app.init");
		Chrono.start("main");
        Debug.init();

		Debug.log("Main init");
        Debug.mouseTracking();

		//Détection d'IE6
		if($.browser.msie && $.browser.version=="6.0") { //Désactivé
			//alert("Ce site ne fontionne pas avec Internet Explorer 6... Veuillez utiliser un autre navigateur.");	
			this.isIe6 = true;
		} else {
			this.isIe6 = false;
		}

		if (this.isIe6) {
			//return;
		}

		Background.init();			
		ce(window).resize(function() {
			App.resized();
		});	   


		Tooltip.init();
		Popup.init();
		
		//Formulaire de contact...
		Ctc.init();

		//Configuration d'éventuels onglets
		ce("ul.tabs").tabs("div.panes > div");
		//on colle les onglets au dessus du box de contenu
		App.placeTabs();

		// Add 'external' CSS class to all external links
		$('a:external').addClass('external');
		
		//overlay sans flowplayer
		$(".row2 img[rel]").overlay({

			expose: '#369',
			
			onLoad: function(content) {
				// find the player contained inside this overlay and load it
				//this.getOverlay().find("a.player").flowplayer(0).load();
			},
			
			onClose: function(content) {
				//$f().unload();
			}
			
		});

		//Configuration des vidéos overlay
		$(".row img[rel]").overlay({

			expose: '#369',
			
			onLoad: function(content) {
				// find the player contained inside this overlay and load it
				this.getOverlay().find("a.player").flowplayer(0).load();
			},
			
			onClose: function(content) {
				$f().unload();
			}
			
		});

		//Initialisation des players vidéo	
		$f("a.player", "/assets/swf/flowplayer-3.2.0.swf");
		$f("playerAlone", "/assets/swf/flowplayer-3.2.0.swf", {
			clip: {
				//autoPlay: false
			}
		});
		
		//ajout de l'effet sur le bouton close
		$(".overlay .close").live("mouseover", function() {
			$(this).addClass("hover");
		});
		$(".overlay .close").live("mouseout", function() {
			$(this).removeClass("hover");
		});
		$(".overlay .close").live("mousedown", function() {
			$(this).addClass("down");
		});
		$(".overlay .close").live("mouseup", function() {
			$(this).removeClass("down");
		});

		
		Chrono.sr("main");
	
	},

	resized: function() {
		_d("RESIZED");
		clearTimeout(this.timerResize);
		this.timerResize = setTimeout("App.resizeEnd()", 100);
		
	},
	
	resizeEnd: function() {
		_d("Resize End");
		Background.refresh();	
	},

	placeTabs: function() {
		_d( "XXXXX " + ce("ul.tabs").height());
		ce("ul.tabs").css("top", "-" + ce("ul.tabs").height() + "px");
	},
	
	bgDisplayed: function(id) {
		_d("bgDisplayed " + id);
		var popup = $("[data-key=" + id + "]").attr("data-popup");
		_d("popup: " + popup);
		if( popup != undefined) {
			Popup.display(popup);
		} else {
			_d("clear Popup");
			Popup.hide();
		}
		
		var popupLink = $("[data-key=" + id + "]").attr("data-popupLink");
		_d("popupLink: " + popupLink);
		if( popupLink != undefined) {
			Popup.setHref(popupLink);
		} else {
			_d("clear PopupLink");
			Popup.clearHref();
		}
		
		
	}

};

var Ctc = {

	init: function() {
		_d("Initialisation contact Form");
		
		//on met js à on... pour l'antispam
		$("#js").attr("value","on");
		
		
		//A tester une autre fois...
		//$("#ctcForm").validator();
	}

};

var Popup = {

	href: null,
	
	init: function() {
		ce('body').append('<div id="popup" style="display:none;"><div class="top"></div><div class="content"></div></div>');
		this.hide();
		var me = this;
		ce("#popup").click( function(event) {
			event.stopPropagation();
			me.clicked()
		});
	},
	
	setContent: function(html) {
		//_d("ToolTip.setContent" + html);
		ce("#popup .content").html(html);
	},
	
	setHref: function(href) {
		this.href = href;
		ce("#popup").css("cursor", "pointer");
	},
	
	clearHref: function() {
		this.href = null;
		ce("#popup").css("cursor", "auto");
	},
	
	display: function(html) {
	
		ce("#popup").hide();
		this.setContent(html);
		ce("#popup").fadeIn('fast');

	},

	hide: function() {
		ce("#popup").fadeOut("fast");
	},
	
	clicked: function() {
		if( this.href != null ) {
			window.location.href = this.href;
		}
	}
	
};

var Tooltip = {

	timer: null,
	
	init: function() {
		ce('body').append('<div id="galTip"><div class="content"></div></div>');
		ce("#galTip").hide();
		var me = this;
		ce("#galTip").hover(function() {
			clearTimeout(me.timer);	
		}, function() {
			me.hide();
		});
	},
	
	setContent: function(html) {
		//_d("ToolTip.setContent" + html);
		ce("#galTip .content").html(html);
	},

	display: function(html) {
	
		//on tue le timer de fermeture
		clearTimeout(this.timer);
		ce("#galTip").hide();
		this.setContent(html);
		//on commence par l'afficher
		ce("#galTip").fadeIn('fast');

	},

	hide: function() {
		this.timer = setTimeout("Tooltip.reallyHide()", 500);	
	},

	reallyHide: function() {
		ce("#galTip").fadeOut("slow");
	}

};

var Background = {

	list: new Array(),
	galRoot: null,
	galPath: null,
	q: 85,
	current: null,
	timer: null,
	timer2: null, //timer pour le masquage de la galerie
	stopped: false,
	delay: 1000,
	bottomHeight: null,
	galHeight: null,
	active: false,
	
	init: function() {
		_d("background.init");
		var me = this;
		this.galRoot = ce("#gal .items").attr("data-galRoot");
		this.galPath = ce("#gal .items").attr("data-galPath");
		this.bottomHeight = ce("#bottom").css("height");
		this.galHeight = ce("#gal").css("height");
		this.getList();
		if( this.list.length > 0 ) {
			this.createHtml();
			this.load( 0 );
		}

		if( this.list.length == 1 ) { //pas la peine d'afficher les miniatures si on en a qu'une
			$("#gal").hide();
		}

		ce("#gal").hover(function() {
			me.galHover();
		}, function() {
			me.galHoverEnd();
		});

        
        $(".btn").live('mousedown', function() {
            $(this).addClass("down");
        });

        $(".btn").live('mouseup', function() {
            $(this).removeClass("down");
        });

	},
	
	galHover: function() {
		_d("GALHOVER");
		if( this.active ) {
			this.galEnlarge();
		}
	},

	galHoverEnd: function() {
		_d("GalHoverEnd");	
		if( this.active ) {
			this.galReduce();
		}
	},

	galReduce: function() {
		if( App.isIe6 ){
			return;
		}

		_d("reduce");
		ce("#gal .scrollable").delay(300).animate({
			"height": "0px"
		});
		
	},

	galEnlarge: function() {
		ce("#gal .scrollable").stop(true,true).animate({
			"height": "70px"
		});		
	},

	getList: function() {
		
		var me = this;
		$("#gal .items img").each(function() {
			me.list.push( $(this).attr('data-imgName') );
			//_d( $(this).attr('data-imgName') );
		}).hover(function() {
			me.miniHover( $(this).attr('data-key') );
		}, function() {
			me.miniHoverEnd( $(this).attr('data-key') );
		}).click( function() {
			me.miniClick( $(this).attr('data-key') );
			return false;
		});
		
	},
	
	bgClicked: function() {

		if( App.isIe6 ){
			return;
		}

		//si la galerie est activé... on désactive!! 
		if( this.active ) {
			this.closeGal();
		} else {
			this.activateGal();
			this.galReduce();
		}
	},
	
	miniClick: function( key) {
		_d("click on: " + key );
		//on masque le contenu normal
		this.activateGal();
		this.stop();
		//on met le loader
		ce("#MAINBGBACK").fadeOut(200);
		this.load(key);
		
		//on charge l'image
	},

	miniHover: function( key ) {
	
		//on change le contenu du Tooltip
		_d("MINIHOVER" + ce(".mini-" + key + " img").attr("data-tooltip") );
		
		//Génération du contenu du Tooltip
		
		var ttContent = "";
		
		//Contenu
		if( ce(".mini-" + key + " img").attr("data-tooltip") ) {
			ttContent = "<p>" + ( ce(".mini-" + key + " img").attr("data-tooltip") ) + "</p>";
		}
		
		//Données Auteur
		//data-authName="toto grougnou"
		//data-authWebSite="http://www.totogrougnou.com"
		
		if( ce(".mini-" + key + " img").attr("data-authName") ) {
			ttContent += "<p>Auteur: " +  " <a href=\"" + ce(".mini-" + key + " img").attr("data-authWebSite") + "\">" + ce(".mini-" + key + " img").attr("data-authName") + "</a></p>";
		}
		
		//Données Exif
		ttContent += "<p class=\"exif\">Données EXIF: <br>" + ce(".mini-" + key + " img").attr("data-exif-Model") + "<br>";
		if(ce(".mini-" + key + " img").attr("data-exif-ISO") != "") {
			ttContent += ce(".mini-" + key + " img").attr("data-exif-ISO") + "iso "; 
		}
		
		ttContent += ce(".mini-" + key + " img").attr("data-exif-aperture") + " " + ce(".mini-" + key + " img").attr("data-exif-exposureTime") + "</p>";
		
		if( ttContent != "" ) {
			Tooltip.display( ttContent );	
		}
						
		//this.delay = 100;
		//this.stop();
		//this.load( key );

	},

	miniHoverEnd: function( key ) {
		_d("hoverEnd");
		Tooltip.hide();
	},

	activateGal: function() {

		_d("ActivateGal");
		this.active = true;
		var me = this;
		ce("#middle, #footer, #menu1, #lang-switch").fadeOut(500);
		ce("#top1").animate({
			height: "0"
		});
		ce("#bottomXXX").animate({
			height: "90px"
		}, 1500);

	},

	closeGal: function() {

		this.active = false;
		ce("#middle, #footer, #menu1, #lang-switch").fadeIn(500);
		ce("#top1").animate({
			height: "100px"
		});
		ce("#GALTOOLS").fadeOut(500);
		//on réagrandit la galerie
		this.galEnlarge();
		this.restart();

	},
	
	createHtml: function() {
		var me = this;

		ce("body").prepend("<div id='MAINBG'><img src='/images2/trans.gif' alt='cache Image'><div id='MAINBGBACK'></div><div id='MAINBGFRONT'></div></div>");

		ce('#MAINBG img').hide().load( function() {
			me.cacheLoaded();
		});
		//ajout des fonctions pour réagir au click sur l'image
		//les clicks sur les zones $menu3 .subMainBox .tabs #top #bottom ne doivent pas réagir... stopper la propagation

		$("#menu3, .subMainBox, .tabs, #top, #bottom, .videos").click(function(event){
			_d("stop Propagation");
			event.stopImmediatePropagation();
		});
		$("body").live('click', function() {
			//alert("click on background image");
			_d("click on main image");
			me.bgClicked();
		});
		
	},

	
	cacheLoaded: function() {
		this.display();
	},
	
	loadNext: function() {
		this.load( this.next() );	
	},
	
	load: function( num ) {
		_d( "loading: " + this.list[ num ] );

		//on tue tout éventuel timer (pour le cas ou c'est appellé via un hover)
		clearTimeout(this.timer); 
		
		this.current = num;
		
		//on mesure la taille actuelle de l'écran (arrondie à la centaine de px)
		
		var w = Math.ceil( ce(window).width()/100 ) * 100;
		var h = Math.ceil( ce(window).height()/100 ) * 100;
		
		ce('#MAINBG img').attr("src", "/" + this.galRoot + w + "/" + h + "/crop/" + this.galPath + this.list[ num ]);


	},
	
	refresh: function() {
		_d("Refreshing...");
		this.load(this.current);
	},

	display: function() {
		//affiche l'image mise dans le cache
		_d("DISPLAY");
		

		var me = this;
		
		//on masque le div front (au cas ou... normalement pas besoin)
		ce("#MAINBGFRONT").hide();
		//on charge le nouveau fond dans le div front
		ce("#MAINBGFRONT").css("background-image", 'url(' + ce('#MAINBG img').attr("src") + ')') ;
		//on affiche en fade le div front
		ce("#MAINBGFRONT").fadeIn(this.delay, function() {
			//quand c'est fini, on met l'image aussi dans le div back
			ce("#MAINBGBACK").css("background-image", 'url(' + ce('#MAINBG img').attr("src") + ')') ;
			//on remasque le div de front
			ce("#MAINBGBACK").show(); //juste au cas ou il était par hasard masqué...
			ce("#MAINBGFRONT").hide();
			me.backgroundDisplayed();
		});
		
	},
	
	backgroundDisplayed: function() {
		//quand l'image est affichée, on repart sur la suivante...
	
		_d("BackgroundDisplayed");
		//this.loadNext();
		if( !this.stopped ) {
			this.timer = setTimeout("Background.loadNext()", 6000);
		}

		App.bgDisplayed(this.current);
	},
	
	next: function() {
		//renvoie le numéro de la prochaine image
		
		var next = this.current + 1 ;
		
		if( next >= this.list.length ) {
			next = 0;
		}
		
		return next;
		_d(next);
	},
	
	stop: function() {
		this.stopped = true;
		clearTimeout(this.timer); 
	},
	
	restart: function() {
		this.stopped = false;
		this.loadNext();
	}
	
	
};

var Tools = {

    getBasePath: function() {
    	return window.location.protocol + '//' + window.location.host;
    }
    
};

var Chrono = {
    //Chronomère de l'application et les fonctions qui lui sont associées.
    //Attention, pour ne pas trop fausser les mesures, on ne vérifie pas si les compteurs existent!!! donc il faut les lancer avant de les stopper ou de les lire...

    data: new Array(), //Liste des timestamps de départ
    
    start: function( counter ) {
        //Démarrage d'un compteur
        var d = new Date();
        this.data[counter] = new Array();
        this.data[counter]['start'] = d;
    },
    
    stop: function( counter ) {
        this.data[counter]['stop'] = new Date();
    },
    
    inter: function( counter ) {
        //Retourne un temps intermédiaire

        var s = new Date();
        var d = s - this.data[counter]['start'] ;
        //Debug.log("chrono : " + counter + " : " + d );
        return d;
    },
    
    read: function( counter ) {
        var d = this.data[counter]['stop'] - this.data[counter]['start'] ;
        Debug.log("chrono : " + counter + " : " + d );
    },
    
    sr: function( counter ) {
        //stop and read
        
        this.stop( counter );
        this.read( counter );
    }
};

var Debug = {
    
    level: null, //Niveau de débug
    
    init: function() {
        this.level = ce("body").attr("data-debug");
        //alert(this.level);
        ce('#log').click(function() {
            //alert("reset");
            Debug.clear();
        });
        
    },
    
    mouseTracking: function() {

        if( this.level > 0 ) {
            //on traque la souris
            Debug.log("Mouse Tracking ON");
            $("html").mousemove( function(e) {
                var x = e.pageX;
                var y = e.pageY;
                var html = "x:" + x + " y:" + y;
                ce("#mousePos").html(html);
            });
        }
        
    },
    
    log: function( msg ) {

        if( this.level > 0 ) {
            var t = Chrono.inter("main");
            ce('#log').prepend("<p>@" + t + "ms : <br>" + msg + "</p>");       
        }
        
    },
    
    clear: function() {
        ce('#log').empty();
    },
    
    stop: function() {
        //onFaitToutPlanter();
        throw "exit";
    }

    
    
    
};

/////////
// INIT
////////
$(document).ready(App.init);
