/*
 * Smoothbox v20080623 by Boris Popoff (http://gueschla.com)
 * To be used with mootools 1.2
 *
 * Based on Cody Lindley's Thickbox, MIT License
 *
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

 var Timer;
var Pas = 3;
 var imagePrev=[];
var prodGalerie = "";

 
 		function moveLayer(Sens) {
				Objet=document.getElementById("previewcontenu");
				if(parseInt(Objet.style.top) + (Pas*Sens)>0)  {
					clearTimeout(Timer);
				}
				else if(parseInt(Objet.style.top) + (Pas*Sens)<-(Objet.offsetHeight-document.getElementById("previewsupport").offsetHeight)) {
					clearTimeout(Timer);
				}
				else {
					Objet.style.top = (parseInt(Objet.style.top) + (Pas*Sens)) + "px";
				}
				Timer = setTimeout("moveLayer(" + Sens + ");", 30);
		   }
 
  function PSR_imprimer () {
 var PSR_f1 = null;
 var PSR_content=document.getElementById('PSR_print').parentNode.innerHTML;
 var PSR_title=document.getElementsByTagName('title')[0].innerText;
 if (PSR_f1) {if(!PSR_f1.closed) PSR_f1.close();}
 PSR_f1 = window.open ('',"PSR_f1", "menubar=yes,scrollbars=yes,resizable=yes,,left=10,top=10"); ;
 PSR_f1.document.open();
 PSR_f1.document.write("<html><head><title>" + PSR_title + "</title></head><body bgcolor='#ffffff' >"+PSR_content+"</body></html><script language='JAVASCRIPT'>window.print();</script>");
 }
 
// on page load call TB_init
window.addEvent('domready', TB_init);

// prevent javascript error before the content has loaded
TB_WIDTH = 0;
TB_HEIGHT = 0;
var TB_doneOnce = 0;

// add smoothbox to href elements that have a class of .smoothbox
function TB_init(){
    $$("a.smoothbox").each(function(el){
        el.onclick = TB_bind
    });
	
	$$("a.smoothboxmap").each(function(el){
        el.onclick = TB_bind2
    });
	
}


function TB_bind2(event){
    var event = new Event(event);
    // stop default behaviour
    event.preventDefault();
    // remove click border
    this.blur();
    // get caption: either title or name attribute
    var caption = this.title || this.name || "";
    // get rel attribute for image groups
    var group = this.rel || false;
    // display the box for the elements href
     TB_show("", "", this.href, "");
    this.onclick = TB_bind;
    return false;
}


function TB_bind(event){
    var event = new Event(event);
    // stop default behaviour
    event.preventDefault();
    // remove click border
    this.blur();
    // get caption: either title or name attribute
    var caption = this.title || "";
	
	var copyright = this.name || "";
	
    // get rel attribute for image groups
    var group = this.rel || false;
    // display the box for the elements href
    TB_show(caption, copyright, this.href, group);
    this.onclick = TB_bind;
    return false;
}


function TB_bind_ex(i){
	$("TB_window").dispose();
    new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
	TB_show(imagePrev[i].caption, imagePrev[i].copyright, imagePrev[i].url, "gallery-views")
    return false;
}

// called when the user clicks on a smoothbox link
function TB_show(caption, copyright, url, rel){

    // create iframe, overlay and box if non-existent
    
    if (!$("TB_overlay")) {
        new Element('iframe').setProperty('id', 'TB_HideSelect').injectInside(document.body);
        $('TB_HideSelect').setOpacity(0);
        new Element('div').setProperty('id', 'TB_overlay').injectInside(document.body);
        $('TB_overlay').setOpacity(0);
        TB_overlaySize();
        new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
        $('TB_load').innerHTML = "<img src='img/loading.gif' />";
        TB_load_position();
        
        $('TB_overlay').set('tween', {
            duration: 400
        });
        $('TB_overlay').tween('opacity', 0, 0.6);
        
    }
    
    if (!$("TB_load")) {
        new Element('div').setProperty('id', 'TB_load').injectInside(document.body);
        $('TB_load').innerHTML = "<img src='img/loading.gif' />";
        TB_load_position();
		if(rel == "gallery-views"){
			document.getElementById("TB_window").style.background = "url('img/fond-gal2.jpg') repeat-x";
		}
    }
    
    if (!$("TB_window")) {
        new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
		 $('TB_window').setOpacity(0);
		if(rel == "gallery-views"){
			document.getElementById("TB_window").style.background = "url('img/fond-gal2.jpg') repeat-x";
		}

    }
    
    $("TB_overlay").onclick = TB_remove;
    window.onscroll = TB_position;
    
    // check if a query string is involved
    var baseURL = url.match(/(.+)?/)[1] || url;
    
    // regex to check if a href refers to an image
    var imageURL = /\.(jpe?g|png|gif|bmp)/gi;
    
    // check for images
    if (baseURL.match(imageURL)) {
        var dummy = {
            caption: "",
            url: "",
            html: "",
			copyright:""
        };
        
        var prev = dummy, next = dummy, imageCount = "";
        
        // if an image group is given
        if (rel) {
            function getInfo(image, id, label){
                return {
                    caption: image.title,
                    url: image.href,
                    html: "<span id='TB_" + id + "'>&nbsp;&nbsp;<a href='#'>" + label + "</a></span>",
					copyright : image.name
                }
            }
            
            // find the anchors that point to the group
            var imageGroup = [];
            $$("a.smoothbox").each(function(el){
                if (el.rel == rel) {
                    imageGroup[imageGroup.length] = el;
                }
            })
            var galerie = "";
            var foundSelf = false;
            // loop through the anchors, looking for ourself, saving information about previous and next image
		
			
            for (var i = 0; i < imageGroup.length; i++) {
                var image = imageGroup[i];
                var urlTypeTemp = image.href.match(imageURL);

                // look for ourself
                if (image.href == url) {
                    foundSelf = true;
                    imageCount = "Image " + (i + 1) + " sur " + (imageGroup.length);
                }
                else {
                    // when we found ourself, the current is the next image
                    if (foundSelf) {
                        next = getInfo(image, "next", "Suivante &gt;");
                        // stop searching
                        break;
                    }
                    else {
                        // didn't find ourself yet, so this may be the one before ourself
                        prev = getInfo(image, "prev", "&lt; Précédente");
                    }
                }
            }
			if(next.url==""){
				next = getInfo(imageGroup[0], "next", "Suivante &gt;");
			}     
			if(prev.url==""){
				prev = getInfo(imageGroup[imageGroup.length-1], "prev", "&lt; Précédente");
			}   
		}
        
        imgPreloader = new Image();
        imgPreloader.onload = function(){
            imgPreloader.onload = null;
            
            // Resizing large images
            var x = window.getWidth() - 50;
            var y = window.getHeight() - 50;
            var imageWidth = imgPreloader.width;
            var imageHeight = imgPreloader.height;
            // if (imageWidth > x) {
                // imageHeight = imageHeight * (x / imageWidth);
                // imageWidth = x;
                // if (imageHeight > y) {
                    // imageWidth = imageWidth * (y / imageHeight);
                    // imageHeight = y;
                // }
            // }
            // else{ 
                // if (imageHeight > y) {
                    // imageWidth = imageWidth * (y / imageHeight);
                    // imageHeight = y;
                    // if (imageWidth > x) {
                        // imageHeight = imageHeight * (x / imageWidth);
                        // imageWidth = x;
                    // }
                // }
			// }
            // End Resizing
            
            // End Resizing
            
	
			if (rel) {  
				for (var i = 0; i < imageGroup.length; i++) {
				
					imagePrev[i] = getInfo(imageGroup[i], "preview" + i , "");
					if(i==0){
						galerie += "<div style='float:left;width:80px;'>"
						galerie +="<div  onmouseover='moveLayer(1);' onmouseout='clearTimeout(Timer);' style='cursor:pointer;margin-left:4px;border:solid 1px black;position:relative;width:70px;;margin-top:5px;text-align:center;border-bottom:0px;'><img src='img/upGal.png' style='margin:0 auto;'></div>"
						galerie += "<div id='previewsupport' style='position:relative;width:70px;border:solid 1px black;margin:4px;margin-top:0px;margin-bottom:0px;overflow:hidden;height:" + (imageHeight - 27) + "px;'><div id='previewcontenu' style='position:absolute; top:0;'>"
						
					}
					var imageGal = [];	
					imageGal = getInfo(imageGroup[i], "prev", "&lt; Précédente").url.split("/");
					galerie += "<a href='#' onClick=\"TB_bind_ex("+ i +")\"><img style='margin-bottom:4px;' src='Galerie/thumb/" + imageGal[imageGal.length-1] + "'></a>";
					
					if(i==imageGroup.length-1){
						galerie += "</div></div>"
						galerie += "<div onmouseover='moveLayer(-1);' onmouseout='clearTimeout(Timer);' style='margin-left:4px;position:relative;width:70px;border:solid 1px black;margin-top:0px;text-align:center;border-top:0px;cursor:pointer;'><img src='img/downGal.png' style='margin:0 auto;'></div>"
						galerie += "</div>"
					}
					
						
				}
			}
            // TODO don't use globals
            
			TB_WIDTH = imageWidth + 10;
            if(rel=="gallery-views"){
				TB_WIDTH += 80;
			}
			TB_HEIGHT = imageHeight + 30;

			
			var uriCourant = url
			var indiceDepart = uriCourant.lastIndexOf('/')+1; // Plus 1 car on ne veut pas le '/'.
			var indiceArrivee = uriCourant.length-4; // Moins les 4 caractères de l'extension.

			var nomPage = uriCourant.substring(indiceDepart, indiceArrivee);
			
            // TODO empty window content instead
     
			
			  $("TB_window").innerHTML += "<div style='position:relative;padding:0px;'>";
			  
			  if(rel=="gallery-views"){
				 $("TB_window").innerHTML +="<div style=\"height:16px;margin:0px;font-size:14px;font-weight:bold;color:white;background:url('img/fond-gal.jpg') repeat-x;\"><div style=\"margin-top:2px;\">&nbsp;" + prodGalerie + "</div></div>"
				 $("TB_window").innerHTML += galerie;
			}
			  
			  $("TB_window").innerHTML +="<a style='cursor:pointer;' id='TB_ImageOff' title='" + caption + "'><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='" + caption + "'/></a>";
			$("TB_window").innerHTML += "<div style='position:absolute;top:25px;right:20px;'>" + copyright + "</div>";
			$("TB_window").innerHTML +="</div>" ;
			$("TB_window").innerHTML +="<div id='TB_caption'>" + caption + "<div id='TB_secondLine' style='font-size:12px;'>" + imageCount + prev.html + next.html + "</div></div>"
			if(url.indexOf("tarif", 0)>0){
				$("TB_window").innerHTML += "<span id='PSR_print'><a href=\"tarifs/tarif.asp?tarif="+nomPage.replace("tarif","")+"\" target=\"_blank\" style='font-family:arial; font-size:12px;' >Version Imprimable</a></span>"
			}
			$("TB_window").innerHTML += "<div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>Fermer</a></div>";
			$("TB_closeWindowButton").onclick = TB_remove;
            
            function buildClickHandler(image){
                return function(){
                    $("TB_window").dispose();
                    new Element('div').setProperty('id', 'TB_window').injectInside(document.body);
                    
                    TB_show(image.caption, image.copyright, image.url, rel);
                    return false;
                };
            }
            var goPrev = buildClickHandler(prev);
            var goNext = buildClickHandler(next);
            if ($('TB_prev')) {
                $("TB_prev").onclick = goPrev;
            }
            
            if ($('TB_next')) {
                $("TB_next").onclick = goNext;
            }
            
            document.onkeydown = function(event){
                var event = new Event(event);
                switch (event.code) {
                    case 27:
                        TB_remove();
                        break;
                    case 190:
                        if ($('TB_next')) {
                            document.onkeydown = null;
                            goNext();
                        }
                        break;
                    case 188:
                        if ($('TB_prev')) {
                            document.onkeydown = null;
                            goPrev();
                        }
                        break;
                }
            }
            
            // TODO don't remove loader etc., just hide and show later
			$("TB_ImageOff").onclick = goNext;
            TB_position();
            TB_showWindow();
        }
        imgPreloader.src = url;
        
    }
    
    window.onresize = function(){
        TB_position();
        TB_load_position();
        TB_overlaySize();
    }
    
    document.onkeyup = function(event){
        var event = new Event(event);
        if (event.code == 27) { // close
            TB_remove();
        }
    }
    
}

//helper functions below

function TB_showWindow(){
    //$("TB_load").dispose();
    //$("TB_window").setStyles({display:"block",opacity:'0'});
    
    if (TB_doneOnce == 0) {
        TB_doneOnce = 1;
        
        $('TB_window').set('tween', {
            duration: 250,
            onComplete: function(){
                if ($('TB_load')) {
                    $('TB_load').dispose();
                }
            }
        });
        $('TB_window').tween('opacity', 0, 1);
        
    }
    else {
        $('TB_window').setStyle('opacity', 1);
        if ($('TB_load')) {
            $('TB_load').dispose();
        }
    }
}

function TB_remove(){
    $("TB_overlay").onclick = null;
    document.onkeyup = null;
    document.onkeydown = null;
    
    if ($('TB_imageOff')) 
        $("TB_imageOff").onclick = null;
    if ($('TB_closeWindowButton')) 
        $("TB_closeWindowButton").onclick = null;
    if ($('TB_prev')) {
        $("TB_prev").onclick = null;
    }
    if ($('TB_next')) {
        $("TB_next").onclick = null;
    }
    
    
    $('TB_window').set('tween', {
        duration: 250,
        onComplete: function(){
            $('TB_window').dispose();
        }
    });
    $('TB_window').tween('opacity', 1, 0);
    
    
    
    $('TB_overlay').set('tween', {
        duration: 400,
        onComplete: function(){
            $('TB_overlay').dispose();
        }
    });
    $('TB_overlay').tween('opacity', 0.6, 0);
    
    window.onscroll = null;
    window.onresize = null;
    
    $('TB_HideSelect').dispose();
    TB_init();
    TB_doneOnce = 0;
    return false;
}

function TB_position(){
    $('TB_window').set('morph', {
        duration: 75
    });
    $('TB_window').morph({
		width: TB_WIDTH + 'px',
		left: (window.getScrollLeft() + (window.getWidth() - TB_WIDTH) / 2) + 'px',
		top: (window.getScrollTop() + (window.getHeight() - TB_HEIGHT) / 2) + 'px'
	});	
}

function TB_overlaySize(){
    // we have to set this to 0px before so we can reduce the size / width of the overflow onresize 
    $("TB_overlay").setStyles({
        "height": '0px',
        "width": '0px'
    });
    $("TB_HideSelect").setStyles({
        "height": '0px',
        "width": '0px'
    });
    $("TB_overlay").setStyles({
        "height": window.getScrollHeight() + 'px',
        "width": window.getScrollWidth() + 'px'
    });
    $("TB_HideSelect").setStyles({
        "height": window.getScrollHeight() + 'px',
        "width": window.getScrollWidth() + 'px'
    });
}

function TB_load_position(){
    if ($("TB_load")) {
        $("TB_load").setStyles({
            left: (window.getScrollLeft() + (window.getWidth() - 56) / 2) + 'px',
            top: (window.getScrollTop() + ((window.getHeight() - 20) / 2)) + 'px',
            display: "block"
        });
    }
}

function TB_parseQuery(query){
    // return empty object
    if (!query) 
        return {};
    var params = {};
    
    // parse query
    var pairs = query.split(/[;&]/);
    for (var i = 0; i < pairs.length; i++) {
        var pair = pairs[i].split('=');
        if (!pair || pair.length != 2) 
            continue;
        // unescape both key and value, replace "+" with spaces in value
        params[unescape(pair[0])] = unescape(pair[1]).replace(/\+/g, ' ');
    }
    return params;
}

