var images = new Array();
var currentIndex = 0;

function PopupImageOLd(monImage)
{
        titre="images";
        l = (screen.width-100)/2;
        t = (screen.height-100)/2;
	w = window.open('','chargement','top='+t+',left='+l+',width=10,height=10,resizable=1,');
	w.document.write( "<html><head><title>"+titre+"</title>\n" );
	w.document.write( "<script language='JavaScript'>\n");
	w.document.write( "IE5=NN4=NN6=false;\n");
	w.document.write( "if(document.all)IE5=true;\n");
	w.document.write( "else if(document.getElementById)NN6=true;\n");
	w.document.write( "else if(document.layers)NN4=true;\n");
	w.document.write( "function autoSize() {\n");
	w.document.write( "if(IE5) self.resizeTo(document.images[0].width+10,document.images[0].height+31);\n");
	w.document.write( "else if(NN6) self.resizeTo(document.images[0].width+30,document.images[0].height+70);\n");
	w.document.write( "else window.resizeTo(document.images[0].width+10,document.images[0].height+31);\n");
	w.document.write( "self.focus();\n");
	w.document.write( "}\n</scri");
	w.document.write( "pt>\n");
	w.document.write( "</head><body leftmargin=0 topmargin=0 marginwidth=0 marginheight=0 onLoad='javascript:autoSize();'>" );
	w.document.write( "<a href='javascript:window.close();'><img src='"+monImage+"' border=0'></a>" );
	w.document.write( "</body></html>" );
	w.document.close();
}

function chargement(){
    $('<h2 id="loadMessage" style="margin: 0; padding: 10px;">Chargement....</h2>').appendTo('body');
    $('div.blockMsg').css({width: '300px', top:($(window).height()-$('#loadMessage').height())/2+'px', left:($(window).width()-300)/2+'px'});
    $('div.blockMsg').html($('#loadMessage'));
}

function imagerevu(src,currentIndex,nbimages){
    var maxWidth = 470;
    var minWidth = 270;
    var maxHeight = 460;
    var imgLoader = new Image();
    imgLoader.onerror = function(){
        alert("Erreur lors du chargement de l'image");
        $.unblockUI();
    }
    imgLoader.onabort = function(){
        alert("Chargement interrompu");
        $.unblockUI();
    }
    // une fois l'image chargée :
    imgLoader.onload = function(){
        var height = imgLoader.height;
        var width = imgLoader.width;
        
        // si l'image doit être redimensionnée
        var reduction = 1;
        if(imgLoader.width > maxWidth || imgLoader.height > maxHeight){
            reduction = Math.max(imgLoader.width/maxWidth, imgLoader.height/maxHeight);
            height = Math.round(imgLoader.height / reduction);
            width = Math.round(imgLoader.width / reduction);
        }
        var widthContent = 40;
        if(width<minWidth){
            widthContent+= minWidth;
        }else{
            widthContent+= width;
        }
        var heightContent = height+50;
        
        var content = '<div id="images_revu" style="width: '+widthContent+'px; height: '+heightContent+'px; display:none; cursor: default;">';
        content+= '<a href="" style="display: block;" ><img style="margin: 15px 15px 0px; border-width: 1px; border-style: solid; border-color: #666666 #CCCCCC #CCCCCC #666666;"  height="'+height+'" width="'+width+'" alt="" src="'+imgLoader.src+'"  /></a>';
        content+= '<div style="float: left; padding: 15px 15px 10px 15px;" ><div style="font-size: 12px;">Image '+eval(currentIndex+1)+' sur  '+eval(nbimages+1);
        if(nbimages>0){
            if(currentIndex>0){
                content+= '&nbsp;&nbsp;<a href="#" title="Précedent" id="previous" style="text-decoration:none;" >&lt; Précedent</a>';
            }
            if(currentIndex<nbimages){
                content+= '&nbsp;&nbsp;<a style="text-decoration:none;" id="next" href="#" title="Suivant">Suivant &gt;</a>';
            }
        }
        content+= '</div></div>';
        content+= '<div style="float: right; padding: 15px 15px 10px 0px; font-size: 12px;"><a id="close" style="text-decoration:none;" title="Fermer" href="#">Fermer</a></div>';
        content+= '</div>';
        $(content).appendTo('body');
        
        $('div.blockMsg').css({width: widthContent+'px', top:($(window).height()-heightContent)/2+'px', left:($(window).width()-widthContent)/2+'px'});
        $('div.blockMsg').html($('#images_revu'));
        $('#images_revu').show();
        
        $('a#close').click(function(){
            $.unblockUI();
        });
        $("#previous").click(function(){
            if(eval(currentIndex-1)>=0){
                currentIndex = currentIndex-1;
                chargement();
                imagerevu(images[currentIndex],currentIndex,$(images).length-1);
            }
        });
        
        $("#next").click(function(){
            if(eval(currentIndex+1)<=$(images).length-1){
                currentIndex = currentIndex+1;
                chargement();
                imagerevu(images[currentIndex],currentIndex,$(images).length-1);
            }
        });
    }
    imgLoader.src = src;
}

function PopupImage(elt){
    jQuery.blockUI({
        message: '<h2 style="margin: 0; padding: 10px;">Chargement....</h2>'
    });
    
    images = new Array();
    var parent = $(elt).parent();
    if(parent.is("li")){
        var tmp = new Array();
        
        //Récupération de l'image principal
        var page_infos_content = parent.parents("div.page_infos_content");
        page_infos_content.find("div.img_pdt > a[imgrevu]").each(function(){
            images.push($(this).attr('imgrevu'))
        });
        page_infos_content.find("div.images > a[imgrevu]").each(function(){
            images.push($(this).attr('imgrevu'))
        });
        
        var prevParent = parent.prev('li');
        //Récupération des previw images
        while(prevParent[0]!=undefined){
            tmp.push($('a', prevParent).attr('imgrevu'));
            prevParent = prevParent.prev('li');
        }
        tmp.reverse();
        if($(tmp).length>0){
            for(var i=0; i<$(tmp).length; i++){
                images.push(tmp[i])
            }
            images.push($(elt).attr('imgrevu'));
        }else{
            images.push($(elt).attr('imgrevu'));
        }
        currentIndex = $(images).length-1;
        
        //Récupération des next images
        var nextParent = parent.next('li');
        while(nextParent[0]!=undefined){
            images.push($('a', nextParent).attr('imgrevu'));
            nextParent = nextParent.next('li');
        }
        imagerevu(images[currentIndex],currentIndex,$(images).length-1);
        
    }else{
        images.push($(elt).attr('imgrevu'));
        currentIndex = $(images).length-1;
        
        //Récupération des images associées
        var page_infos_content = parent.parents("div.page_infos_content");
        var zoom = $('a.zoom', page_infos_content);
        if(zoom[0]!=undefined){
            var href = zoom.attr('href').split("=");
            var produitId = href[1];
            $.getJSON("produitImages.php?id="+produitId, function(json){
                $.each(json, function(i, data){
                    images.push(data.image);
                });
                imagerevu(images[currentIndex],currentIndex,$(images).length-1);
            });
        }else{
            page_infos_content.find("li > a[imgrevu]").each(function(){
                images.push($(this).attr('imgrevu'));
            });
            imagerevu(images[currentIndex],currentIndex,$(images).length-1);
        }
    }
    
    return false;
}

function _gid(eid){
	return document.getElementById(eid);
}
function scrollToId(tg) {
	mBlock = _gid(tg);
	var x = mBlock.x ? mBlock.x : mBlock.offsetLeft
	var y = mBlock.y ? mBlock.y : mBlock.offsetTop;
	window.scrollTo(x, y-20);
}
function initAjax(){
	if (window.XMLHttpRequest){
		return new XMLHttpRequest();     // Firefox, Safari, ...
	}
	else if (window.ActiveXObject){
		return new ActiveXObject('Microsoft.XMLHTTP');    // Internet Explorer 
	}
	else{
		return false;
	}
}
function getAjax(p,xhr){
	xhr.open("GET",p,true);
	xhr.send(null);
}
function getHTML(pg,tg,spin,reg,noscroll){
	var mBlock = _gid(tg);
	if(mBlock){
		if(spin == true){
			showSpinner(mBlock);
		}
		var re = /.+/;
		var mText = '';
		var xhr = initAjax();
		var url = pg;
		getAjax(url,xhr);
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 1){
				mBlock.innerHTML = "Loading...";
				document.body.style.cursor='wait';
			}
			if(xhr.readyState == 4){
				mText = xhr.responseText;
				if(mText.match(re)){
					if(tg == 'header' && url != 'header.php'){
						if(mText == 'stock_empty'){
							alert("Ce produit n'est pas disponible ou votre quantité dépasse la limite disponible en stock");
                        }else if(mText=='produit_media_max_quantite'){
                                alert("Ce produit est déjà présent dans votre panier");
                        }
						getHTML('header.php','header',false,false,false);
					}else{
						mBlock.innerHTML = mText;
					}
					if(reg){
						//mBlock.className='hidden';
						//register(reg);
					}
					if(!noscroll){
						scrollToId(tg);
					}
				}
				document.body.style.cursor='normal';
			}
		}
	}
}
function showSpinner(el){
	el.innerHTML = '<img src="common/gfx/spinner.gif" class="spinner" />';
}
function getKeynum(e){
	if(window.event){
		return e.keyCode;
	}
	else if(e.which){
		return e.which;
	}
}

function getHTML2(pg,tg,spin,reg,noscroll){
    //Affichage de fomulaire de vente d'objet personalisé s'il est activé
    var infosPanier = pg.split('?');
    var url = 'genform.php?action=formPanier&'+infosPanier[1];
	var re = /.+/;
	var mText = '';
	var mBlock = _gid(tg);
	if(mBlock){
		$.get(url, function(data){
			if(data.length>0){
				$('#formPanier').html(data); //Modification de data
				var formPanier = $('form', $('#formPanier')).get(0);
                if(formPanier==undefined){
                    alert("Le formulaire qui permet la vente d'objet personalisé n'existe pas !!!");
                }
                $('<input type="hidden" name="infopanier" value="'+infosPanier[1]+'" />').appendTo($(formPanier));
                
                doOnload($('#formPanier'));
                
				$("input#annulerCommande",$('#formPanier')).click(function(){
					//getHTML(pg,tg,spin,reg,noscroll);
					$.unblockUI();
                    $('#formPanier').html("");
                    $('#formPanier').removeAttr("style");
                    
				});
				
				$("form[genform='panier']",$('#formPanier')).each(function(i){
					var myForm = this;
					$(myForm).ajaxForm({
						beforeSubmit:function(formData,jform){
							//$.merge(formData,[{name: 'infopanier','value': infosPanier[1]}]);
							return tmt_validateForm(myForm);
						},
						success:function(data){
							if(data!=null && data.errorSimpleMessage){
								alert(data.errorSimpleMessage);
							}else{
								getHTML('header.php','header',false,false,false);
								$.unblockUI();
								document.body.style.cursor='normal';
                                $('#formPanier').html("");
                                $('#formPanier').removeAttr("style");
							}
						},
						dataType:'json'
					});
				});
				var height = $(window).height()-40;
                if($('#formPanier').height()>height){
                    $('#formPanier').height(height);
                    $('#formPanier').css('min-height','250px');
                }else{
                    $('#formPanier').css('min-height',$('#formPanier').height()+'px');
                    height = $('#formPanier').height()+15;
                    $('#formPanier').height(height);
                }
				$.blockUI({ 
					message: $('#formPanier'), 
					css: { 
						top:  ($(window).height() - height) /2 + 'px', 
						left: ($(window).width() - 600) /2 + 'px', 
						width: '610px'
					},
                    overlayCSS:{
                        opacity: 0.4
                    }
				});
			}else{
				getHTML(pg,tg,spin,reg,noscroll);
			}
		});
	}
}
