(function (a) {
    a.backstretch = function (k, i, l) {
        function m(c) {
            try {
                f = {
                    left: 0,
                    top: 0
                };
                d = e.width();
                b = d / j;
                if (b >= e.height()) {
                    g = (b - e.height()) / 2;
                    h.centeredY && a.extend(f, {
                        top: "-" + g + "px"
                    })
                } else {
                    b = e.height();
                    d = b * j;
                    g = (d - e.width()) / 2;
                    h.centeredX && a.extend(f, {
                        left: "-" + g + "px"
                    })
                }
                a("#backstretch img").width(d).height(b).css(f)
            } catch (n) {}
            typeof c == "function" && c()
        }
        var h = {
            centeredX: true,
            centeredY: true,
            speed: 0
        },
            e = "onorientationchange" in window ? a(document) : a(window),
            j, d, b, g, f;
        i && typeof i == "object" && a.extend(h, i);
        a(document).ready(function () {
            if (k) {
                var c = a("<div />").attr("id", "backstretch").css({
                    left: 0,
                    top: 0,
                    position: "fixed",
                    overflow: "hidden",
                    zIndex: -9999
                }),
                    n = a("<img />").css({
                        position: "relative",
                        display: "none"
                    }).bind("load", function (o) {
                        var p = a(this);
                        j = a(o.target).width() / a(o.target).height();
                        m(function () {
                            typeof l == "function" && l()                        
                        })
                    }).appendTo(c);
                a("body").prepend(c);
                n.attr("src", k);
                a(window).resize(m)
            }
        });
        return this
    }
})(jQuery);

(function($) { 
        
        document.body.style.opacity = 0;      
        
        // Event handler for the click event on the data-mag-stub links
        $('a[data-mag-set]', "#main").live('click', function(e) {
		e.preventDefault(); 			
		_initGallery(this);              
		return false;
	});        

        $('a[rel=external]').live('click', function(e) {
		e.preventDefault(); 			
		if ( !this.href ) return;
                window.open(this.href);
                return false;
	});
	
	// Global variables
	var windowHeight = $(window).height(), 
            windowWidth  = $(window).width(),
            imageList    = [],
            title        = "",
            current      = 1,
            max          = 1,
            imgStub      = "",
            inAction     = false,
            cW           = 0,
            cH           = 0,
            iW           = 0,
            iH           = 0,
            timer        = false,
            g,                     
            gImg,
            gTmb,
            gTit,
            gPre,
            gOvl,
            gNum,
            gErr;
		 			
        function _initGallery(caller) {
	     _buildOverlay(caller); 
        
              // Remove & reattach the keyboard and resize event handlers                                                      
              $(window).unbind('resize', _setResizeTimer).resize(_setResizeTimer);
              $(document).unbind('keydown', _magKeyDown).keydown(_magKeyDown);		        	
	};
        	
	// Keydown handler 
        function _magKeyDown(e){
		if(typeof g != 'undefined' && g.is(':visible')) {				
                        switch(e.keyCode){
				case 37:
					_prevImage();
					break;
				case 38:
				        if(max > 1) {
				                  current = max;
				                  _loadImage();						                  
                                        };
				        break;
				case 39:
					_nextImage();
					break;
			
				case 40:
                                        if(max > 1) {
				                  current = 1;
				                  _loadImage();						                  
                                        };
				        break;
				
				case 27:  							
					_hideOverlay();
					break;
			};
			return false;
		};  		
	};
 
	// Throttle the resize event 
	function _setResizeTimer() {                	      
	        clearTimeout(timer);
	        if($("#mag-gallery").length) {
	               timer = setTimeout(_resizeOverlay, 400);
                };
	};
	
	// Resize the overlay and image
	function _resizeOverlay() {
                if(!$("#mag-gallery").length) {  return; };
	
                windowHeight = $(window).height();
                windowWidth  = $(window).width();
                
                var w = cW,
                    h = cH;
                                      
                if(w + 40 > windowWidth) {
                        w = windowWidth - 40;
                        h = (h / cW) * w;        
                };
                
                if(h + 60 > windowHeight) {
                        h = windowHeight - 60;
                        w = (w / cH) * h;        
                };                          
                
               
                iW = w;
                iH = h;
                                                
                gImg.css("width", w);
                gImg.css("height", h);
        
                g.stop().css({
                        width:w + 20,
                        height:h + 40,
                        left:Math.max(0, parseInt((windowWidth - (w + 20)) / 2, 10)),
                        top:Math.max(0, parseInt((windowHeight - (h + 40)) / 2, 10))
                        });                                                       						
	};

	function _nextImage() {	
                if(max == 1) return false;                                      
                if(!inAction) {
                        current++;
	               if(current > max) current = 1;
	               _loadImage();
	        };
	        return false;        
	};

	function _prevImage() {
                if(max == 1) return false;                                       	
	        if(!inAction) {
                        current--;
	               if(current < 1) current = max;
	               _loadImage();
	        };
	        return false;
	};
        	
	function _preloadImage() {
        	var imgPreloader = new Image();
        	
                imgPreloader.onload = function() {
                        
                        gPre.fadeOut();
                        
                        var w = this.width,
                            h = this.height;
                        
                        cW = w;
                        cH = h;
                                                    
                        if(w > (windowWidth - 40)) {
                                w = windowWidth - 40;
                                h = (h / this.width) * w;        
                        };
                        
                        if(h > (windowHeight - 60)) {
                                h = windowHeight - 60;
                                w = (w / this.height) * h;        
                        };                          
                        
                        iW = w;
                        iH = h;
                        
                        gImg.css("width", w);
                        gImg.css("height", h);
                        
                        gImg.attr("src", this.src);
                        
                        inAction = true;
                        
                        g.animate({
                                width:w + 20,
                                height:h + 40,
                                left:Math.max(0, parseInt((windowWidth - (w + 20)) / 2, 10)),
                                top:Math.max(0, parseInt((windowHeight - (h + 40)) / 2, 10))
                                },
                                500,
                                function() {                                                                	
                                        gImg.fadeIn(300, function(){inAction = false;});
                                        if($("#mag-controls").is(":hidden")) {                	       
                                                $("#mag-controls").fadeIn();
        	                        };
                                });
                        
                };
                
                imgPreloader.onerror = function() {
                        inAction = false;
                        gErr.html("Sorry, I couldn&#8217;t load the " + current + _daySuffix(current) + " image&#8230;");
                        gErr.fadeIn(150);
                        gPre.fadeOut(150);
                        if($("#mag-controls").is(":hidden")) {                	       
                                $("#mag-controls").fadeIn();
        	        };                                                             
                };
                
                imgPreloader.src = "/" + imgStub + "/" + imageList[current - 1] + ".jpg";
                
                // Preload next & prev images if needs be
                if(max > 1) {
                        var imgN = new Image();
                        imgN.src = "/" + imgStub + "/" + imageList[(current >= max ? 1 : current)] + ".jpg";                        
                };
                
                if(max > 2) {
                        var imgP = new Image();
                        imgP.src = "/" + imgStub + "/" + imageList[(current - 2 < 0 ? max - 1 : current - 2)] + ".jpg";                       
                };
	};

	function _daySuffix(d) {
                d = String(d);
                return d.substr(-(Math.min(d.length, 2))) > 3 && d.substr(-(Math.min(d.length, 2))) < 21 ? "th" : ["th", "st", "nd", "rd", "th"][Math.min(Number(d)%10, 4)];
        };

        function _showPreloader() {
	       if(gPre.is(":hidden")) gPre.fadeIn(150);
	};

        function _loadImage() {                                     
                gTit.stop(true).fadeOut();
                gNum.html(current + "<span>/</span>" + max);
                gErr.stop(true).fadeOut();
                _showPreloader();
                
                if(gImg.not(":hidden")) {
                        inAction = true;                 
                        gImg.fadeOut(150, _preloadImage);
                        return;
                };
                
                _preloadImage();
        };
        
        function _hideOverlay() {
                $(document).unbind('keydown', _magKeyDown);
                $(window).unbind('resize', _resizeOverlay);                         
                g.stop(true).fadeOut(150);
                gOvl.delay(150).fadeOut(150);
                $("#mag-controls").hide(); 
                inAction = false;                       
        };

        function _enableDisableNavigation() {
                if(max <= 1) {
                       $("#mag-controls ul:first li:first a").addClass("disabled");
        	       $("#mag-controls ul:first li:eq(1) a").addClass("disabled"); 
                       gNum.hide();       
                } else {
                       $("#mag-controls ul:first li:first a").removeClass("disabled");
        	       $("#mag-controls ul:first li:eq(1) a").removeClass("disabled");  
                       gNum.show(); 
                };
        };
        	
        function _buildOverlay(caller) {                         
                imageList = $(caller).attr("data-mag-set").split(",");                
                max       = imageList.length || 1;
                imgStub   = "images";
                current   = $(caller).attr("data-mag-pos") ? $(caller).attr("data-mag-pos") : 1;
                
                //console.log(imageList);
                
                var thumbData  = "",                            
                    title      = $(caller).next("h3") ? $("h3:first", $(caller).parent()).text() : $("h2:first").text() || "";
                
                if(!$("#mag-gallery").length) {                                 
        	       $('body').append('<div id="mag-gallery"><div id="mag-content"><h2></h2><img src="" alt="" /><div id="mag-error"></div><div id="mag-preload"></div><div id="mag-thumbs"></div></div><div id="mag-controls"><div id="mag-num"></div><ul><li><a href="#" id="mag-p">previous image</a></li><li><a href="#" id="mag-n">next image</a></li><li><a href="#" id="mag-c">close overlay</a></li></ul></div></div><div id="mag-overlay"></div>');     
        	       g    = $("#mag-gallery");
        	       gWrp = $("#mag-content");
        	       gImg = $("#mag-content img:first");
        	       gTmb = $("#mag-thumbs");
        	       gTit = $("#mag-content h2:first");
        	       gPre = $("#mag-preload");
        	       gOvl = $("#mag-overlay");
        	       gNum = $("#mag-num");
        	       gErr = $("#mag-error");
        	       $("#mag-controls ul:first li:first a").click(_prevImage);
        	       $("#mag-controls ul:first li:eq(1) a").click(_nextImage);
        	       $("#mag-controls ul:first li:eq(2) a").click(_hideOverlay);
        	       
        	       gWrp.hover(
        	               function() {                	                       
        	                       if(inAction || gErr.is(":visible")) return;         	                                       	                       
        	                       gTit.stop(true).fadeIn();
        	               },
        	               function() {
        	                       
        	                       if(inAction || gErr.is(":visible")) return;                	                                       	                       
        	                       gTit.fadeOut();
        	               });
        	               
        	       gWrp.click(_nextImage);                               
                       gOvl.click(_hideOverlay);
                       $("#mag-controls").hide(); 
                };
        	
        	windowHeight = $(window).height();
                windowWidth  = $(window).width();
                       	
        	gErr.hide();
        	
        	g.css("top","-2000px");                	
        	g.css("width", 120);
                g.css("height", 140);
                                             
        	g.css("left",Math.max(0, parseInt((windowWidth - g.width()) / 2, 10)));
                g.css("top",Math.max(0, parseInt((windowHeight - g.height()) / 2, 10)));
                
        	gImg.hide();                          
                gTmb.hide();
             	
             	gTit.hide();
        	gTit.html("<span>" + title + "</span>");
              	
                gOvl.show(150);                        	                       	                               
                g.delay(150).show(150);
               	
                _enableDisableNavigation();                          
        	_loadImage();
        };                

        //----------------------------------------------------
        // Default gallery JS
        //----------------------------------------------------
        	
	// Resizes the header & main content containers
        function _resizeContainers() {

                var windowWidth = $(window).width(),
                    n = Math.floor(windowWidth / a);
                                 
                t = Math.max(720, n * a);                    
                
                // Resize containers
                $("#main").css("width", t);
                $("#unfortunate-wrapper").css("width", t - 20);
                
                $("#main").css("marginLeft", Math.ceil((windowWidth - t) / 2));
                $("#unfortunate-wrapper").css("marginLeft", Math.ceil((windowWidth - t) / 2) + 10);
                
                // Position background
                var nw = 1530 - (Math.ceil((windowWidth - t) / 2) + 10);
                
                $("header:first").css("backgroundPosition", -nw + "px 100%");
                
                $('#main').masonry({
                        columnWidth:  20, 
                        itemSelector: '.ovl',
                        resizeable:   false 
                }, showhideBTT);                
        };
        
        function showHideBTT() 
                var offsets = $("#backtotop").offset();
                
                if(offsets.top && offsets.top > $("window").height()) {
                        $("#backtotop").fadeOut();
                } else if($("#backtotop").is(":hidden")) {
                        $("#backtotop").fadeIn();
                };
        };
        
        // Throttle the resize event 
        function _setMasonryResizeTimer() {
        	clearTimeout(resizeTimer);
        	resizeTimer = setTimeout(_resizeContainers, 400);
        };
        
        var onetimeKeyEvt = false,
            contactShown  = false,
            mailShown     = false,
            a             = 240,
            header        = $("header:first"),
            uWrapper      = $("#unfortunate-wrapper"),
            contact       = $("#ctnt"),
            resizeTimer   = false,
            t;          
       
        // Remove logo from footer
        $("a.logo", contact).remove();
        
        // Append footer contents to header
        uWrapper.append(contact);
        
        // Remove footer
        $("footer:first").remove();         
        
        // Position and size header
        header.css("height", "348px");
        header.css("top", "-250px");        
        uWrapper.css("height", "348px");
        
        // Hack height of ovl's in case font hasn't loaded
        $("#main .ovl > div").each(function() { $(this).height($(this).height()); });
        
        // Window resize event 
        $(window).resize(_setMasonryResizeTimer);
        
        // Masonry
        _resizeContainers();
             
        // "Close" button in header
        $("#header-main").append('<a href="#contact" id="close" class="b-close">Open/Close</a>');
                      
        // "Contact" link in menu
        $("#nav-contact, #close").click(function() {                
                if(!contactShown) {
                        header.animate({
                                top:'0px'
                        }, 1000);                        
                        
                        $("#close").removeClass("b-close").addClass("b-open");
                } else {
                        header.animate({
                                top: '-250px'
                        }, 1000);                        
                        //$("#close").fadeOut("fast");
                        $("#close").removeClass("b-open").addClass("b-close");
                };
                
                contactShown = !contactShown;
                
                if(!mailShown && $("#david")) {
                        mailShown = true;                           
                        //$("#alex-email").html('<a href="mailto:alexandre@modernartgalerie.fr">alexandre@modernartgalerie.fr</a>');
                        $("#david-email").html('<a href="mailto:david@modernartgalerie.fr">david@modernartgalerie.fr</a>');
                };
                return false;
        });  

        // Email address holders 
        if($("#david")) {
                //$("#alex").append('<span class="email" id="alex-email"></span>');
                $("#david").append('<span class="email" id="david-email"></span>');
                
                //$("#alex-email").append('&#160;');
                $("#david-email").append('&#160;');
        }; 
        
         // ALT - g Grid control easter egg
         $(document).keydown(function(e) {                      
                if(onetimeKeyEvt 
                   || 
                   /input|textarea|select/.test(e.target.tagName.toLowerCase()) 
                   ||       
                   !(e.altKey && String.fromCharCode(e.keyCode ? e.keyCode : e.which).toLowerCase() == 'g')) {
                        return true;
                };
                
                onetimeKeyEvt = true;                 
                $(document.body).addClass("gridified");
        });         
        
        $(document).keyup(function(e) { 
                onetimeKeyEvt = false;                     
                $(document.body).removeClass("gridified");
        }); 
        
        // Use JS to plug holes in background size support
        if(!Modernizr.backgroundsize) {
                var bgImage = $("html").css("backgroundImage"); 
                $("html").css("backgroundImage", "");                
                $.backstretch(String(bgImage).replace(/^url\(\"/, "").replace(/\"\)$/,""), {speed: 150});
        };
                
        // Show content
        document.body.style.opacity = 1;       
})(jQuery);        


