var myZoom;
var accordion;

var debug = function(msg) {

  if(typeof console !='undefined' ) { console.warn(msg); } else { alert(msg.message); }
 
}
	
//------------------------------------------------------------------------------------------------------------------------------------------------

function init(o) {
	
	// -------- ZOOM PHOTOS --------
	
	if(document.getElementById("zoom")) {
		$('zoom').style.display = 'block';
		myZoom = new Fx.Slide('zoom', {height: true, opacity: true, duration: 500});
		myZoom.hide();
	}
	
	if(document.getElementById("select")) {
		zoom = document.getElementsByClassName('zoom');
		for(i=0; i<zoom.length; i++) {
			zoom[i].onmouseover = function() { document.getElementById("galerie").style.backgroundImage = "url('"+this.href+"')"; }
			zoom[i].onclick = function() { return false; }
		}
	}
	
	accordion = new Accordion('h2.menutitre', 'ul.stretcher', { opacity: false,duration: 300 }, $('accordion'));
	( o==-1 ) ? accordion.display () : accordion.display (o);
	
	// -------- FLASH INFOS --------
	
	try {
		
		$('flash_infos').innerHTML = '<marquee behavior="scroll" direction="up" scrollamount="1" scrolldelay="1" '
	                                 +'onMouseOver="this.stop()" onMouseOut="this.start()">'
								     +($('flash_infos').innerHTML)+'</marquee>';
									 
	} catch(e) { /* Pas de flash infos... */}
	
	// -------- PROMO --------
	
	try {
		
		$('promo').innerHTML = '<marquee id="promo" behavior="scroll" direction="up" scrollamount="1" scrolldelay="1" '
	                          +'onMouseOver="this.stop()" onMouseOut="this.start()">'
				               +($('flash_infos').innerHTML)+'</marquee>';
							   
	} catch(e) { /* Pas de promos... */ }

	// -------- FIN INIT --------
	
}
	
//------------------------------------------------------------------------------------------------------------------------------------------------

function zoom() {
	myZoom.toggle();
}
	
//------------------------------------------------------------------------------------------------------------------------------------------------

function open_next(id) {
	document.getElementById(id).style.display = '';
    accordion.display(-1);
	setTimeout(function(){ accordion.display(parentId); }, 10);	
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function addToFavorites() {
	if (document.all) { window.external.AddFavorite(location.href, document.title); }
	else { alert("Votre navigateur n'autorise pas l'ajout direct de signets.\n"
	            +"Pour ce faire, faites 'Control + D' pour l'ajouter ou utilisez le menu marque-pages.") }
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function retour() {
	history.go(-1);	
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function OpenWin(URL,width,height,nom) {
	window.open(URL,nom,"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizable=no");
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function OpenWin2(URL,width,height,nom) {
	window.open(URL,nom,"toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizable=yes");
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function DisplayZoomPopUp(url) {
	window.open(url,'Zoom','height=500,width=500,left=0,top=0,scrollbars=yes');
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function qte_moins(champ) {
	champ2 = champ + "_2";
	qte = document.getElementById(champ).value;
	document.getElementById(champ).value = Number(qte) - 1;
	document.getElementById(champ2).value = Number(qte) - 1;
	frmsubmit('recalc');
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function qte_plus(champ) {
	champ2 = champ + "_2";
	qte = document.getElementById(champ).value;
	document.getElementById(champ).value = Number(qte) + 1;
	document.getElementById(champ2).value = Number(qte) + 1;
	frmsubmit('recalc');
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function frmsubmit(func) {
	frm = document.caddieform;
	frm.func.value = func;
	frm.submit();
}

var requete = null;

//------------------------------------------------------------------------------------------------------------------------------------------------

function creerRequete() {
    try {
        requete = new XMLHttpRequest();
    } catch (microsoft) {
        try {
            requete = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(autremicrosoft) {
            try {
                requete = new ActiveXObject('Microsoft.XMLHTTP');
            } catch(echec) {
                requete = null;
            }
        }
    }
    if(requete == null) {
        alert('Impossible de créer l\'objet requête,\nVotre navigateur ne semble pas supporter les object XMLHttpRequest.');
    }
}
	
//------------------------------------------------------------------------------------------------------------------------------------------------

function page(catid) {
	creerRequete();
	var url = 'scripts/page.php?id='+catid;
	requete.open('GET', url, true);
	
	requete.onreadystatechange = function() {
		if(requete.readyState == 4) {
			if(requete.status == 200) {
				document.getElementById('contenu').innerHTML = requete.responseText;
			}
		}
	};
	
	requete.send(null);
}
	
//------------------------------------------------------------------------------------------------------------------------------------------------

function addCartLine() {

	fullLine = 1;
	nextLine = 0;
	$$('.listeProdID').each(function(myEl){
		if (myEl.value == 0){
			fullLine = 0;
		}
		nextLine++;
	});
	
	if (fullLine){
		//var tr = document.createElement('div');
		//tr.setAttribute('id', 'line_'+nextLine);
		//$('cartLine').lastChild.appendChild(tr);
		$('cartLine').innerHTML = $('cartLine').innerHTML+'<div id="line_'+nextLine+'"></div>';
		
		creerRequete();
		var url = 'scripts/panier.php?mode=newLine&line='+nextLine;
		requete.open('GET', url, true);
		
		requete.onreadystatechange = function() {
			if(requete.readyState == 4) {
				if(requete.status == 200) {
					$('line_'+nextLine).innerHTML = requete.responseText;
					//actuCart();
				}
			}
		};
	
		requete.send(null);
	}
}

function updateFormat(i){
	updateLine(i, $('id_'+i).value, 0, 0);
}

function updateQte(i){
	updateLine(i, $('id_'+i).value, $('format_'+i).value, 0);
}

function updateLine(i, prodID, format, qte){
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		'method' : 'post', 
		onSuccess: function (responseText, responseXML){
			$('line_'+i).innerHTML = responseText;
			addCartLine();
			recalcTotal();
		}
	});
	
	Opli = ($('opt_pli_'+i).checked) ? 1 : 0;
	Orai = ($('opt_rai_'+i).checked) ? 1 : 0;
	Oper = ($('opt_per_'+i).checked) ? 1 : 0;
	Oca = ($('opt_ca_'+i).checked) ? 1 : 0;
	Oij = ($('opt_vnp_'+i).checked) ? 1 : 0;
	opt = Opli.toString()+Orai.toString()+Oper.toString()+Oca.toString()+Oij.toString();
	
	myAjax.send('mode=majLine&line='+i+'&id='+prodID+'&format='+format+'&qte='+qte+'&opt='+opt);
}

function changeQte(move, line, valeur){
	$('quantite_'+line).value = valeur.toInt();
	updateLine(line, $('id_'+line).value, $('format_'+line).value, $('quantite_'+line).value);
}

function addOption(line){
	updateLine(line, $('id_'+line).value, $('format_'+line).value, $('quantite_'+line).value);
}

function actuCart(){
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			$('panierDetail').innerHTML = responseText;
		}
	});
	
	myAjax.send('mode=detail');
}

function recalcTotal(){
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			$('cartTotal').innerHTML = responseText;
			initOnePrintCaddieTotal();
			refreshFinalPrice();
		}
	});
	
	myAjax.send('mode=totaux');
}

function updateShip(){
	paysZone = $('pays_zone').value;
	typeTransport = $('transport').value;
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			$('cartShip').innerHTML = responseText;
			//$('allDistrib').setStyle('display', 'none');
			//showAllDistrib();
			recalcTotal();
		}
	});
	
	myAjax.send('mode=transport&paysZone='+paysZone+'&typeTransport='+typeTransport);
}

/*
function showAllDistrib(){
	if ($('transport').value != 0){
		myAjax = new Request({
			'url' : 'scripts/panier.php', 
			onSuccess: function (responseText, responseXML){
				$('allDistrib').innerHTML = responseText;
				$('allDistrib').setStyle('display', 'block');
				initOnePrintCaddieTotal();
			}
		});
		
		myAjax.send('mode=allDistrib');
	} else {
		$('allDistrib').innerHTML = '';
	}
}
*/

function initOnePrintCaddieTotal(){
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			OnePrint.caddieTotal = parseFloat(responseText);
		}
	});
	
	myAjax.send('mode=initOnePrintCaddieTotal');
}

function refreshFinalPrice(){
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			$('finalPrice').innerHTML = responseText;
		}
	});
	
	myAjax.send('mode=final');
}

function majPromo(){
	code = $('code_promo').value;
	myAjax = new Request({
		'url' : 'scripts/panier.php', 
		onSuccess: function (responseText, responseXML){
			recalcTotal();
			document.location.href=wwwroot+"panier.html";
		}
	});
	
	myAjax.send('mode=promo&code='+code);
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function vide(vdefault, champ){
	if(champ.value==vdefault){
		champ.value='';
	}
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function zoomGalerie(src, width, height, texte){
    var div = $('div_zoom_galerie');
    var div2 = $('div_zoom_galerie_contenu');
    var img = div2.getElementsByTagName('canvas')[0];
    
    if(div!=null){
        
        div.style.width=document.width+'px'; 
        div.style.height=document.height+'px';
        div.style.visibility='visible';
        div.style.backgroundColor='#000';
        div.style.zIndex = '999';
        change_opacity('div_zoom_galerie', 0.1, 0.6, '+');
        
        div2.style.visibility='visible';
        div2.style.zIndex = '1000';
        change_opacity('div_zoom_galerie_contenu', 0.1, 1, '+');
        div2.style.top = Math.ceil(parseInt(window.innerHeight)/2) + 'px';
        div2.style.left= Math.ceil(parseInt(window.innerWidth)/2)-Math.ceil(width/2) + 'px';
        
        if(texte!=''){
            div2.innerHTML = '<p style="width:'+width+'px">'+texte+'</p>' + div2.innerHTML;
        }
        div2.innerHTML = '<img src="' + src + '" />' + div2.innerHTML;
    }
    return true;
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function change_opacity(id, depart, arriver, sens){
  if(sens == '-' || sens == '-1')
    var arriver_test = depart>parseFloat(arriver)-0.1
  else
    var arriver_test = depart<parseFloat(arriver)+0.1
      
  if(arriver_test){
    $(id).style.opacity = depart;
    if(sens == '-' || sens == '-1')
      suivant = parseFloat(depart-0.1);
    else
      suivant = parseFloat(depart+0.1);
        
    setTimeout('change_opacity("'+id+'", '+suivant+', '+arriver+', "'+sens+'")', 10)
  }
  else{
    if(arriver==0){
      $(id).style.visibility='hidden';
    }
  }
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function fermer_zoom_galerie(){
  var div = $('div_zoom_galerie_contenu');
  var img = div.getElementsByTagName('img')[0];
  var p = div.getElementsByTagName('p')[0];
  div.style.visibility='hidden';
  
  change_opacity('div_zoom_galerie_contenu', 1, 0, '-');
  
  var anciennoeud = div.removeChild(img);
  
  if(p!=null){
      var anciennoeud = div.removeChild(p);
  }
  
  change_opacity('div_zoom_galerie', 0.6, 0, '-');   
  
  return true;
}

// ------------------------------------------------------------------------------------------------
     
var univers;

window.addEvent('domready',function(){
  univers = [$('menu-impression'),$('menu-lettrage'),$('menu-pub'),$('menu-plv'),$('menu-emballage')];
  univers.each(function(ctn){ new Fx.Slide(ctn).hide(); });
});

var UniversOpenMenu = function(menu,lien,noEffect,uid,noAjax) {
  menu = $(menu);
  lien = $(lien);
  univers.each(function(myEl){
	if(myEl.id==this.menu.id) {
	  ( this.noEffect != true ) ? new Fx.Slide(myEl).slideIn() : new Fx.Slide(myEl).show();
	  if((typeof noAjax == 'undefined' || noAjax==null) && (typeof uid != 'undefined' || uid!=null)) { 
	    //page(uid);
	  }
	} else {
      ( this.noEffect != true ) ? new Fx.Slide(myEl).slideOut() : new Fx.Slide(myEl).hide();		
	}
  }.bind({menu:menu,lien:lien,noEffect:noEffect}));
}

//------------------------------------------------------------------------------------------------------------------------------------------------

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

//------------------------------------------------------------------------------------------------------------------------------------------------

var OnePrint = {
	
  // -------------------------------------------------------
	
  prix : 0,
  caddieTotal : 0,
  Villes : {},
	
  // -------------------------------------------------------
  
  SwitchService : function(chkBox) {
	  
	setTimeout(function(){
		
    var obj = $('optionPrix'); 
	  OnePrint.DecocheCheckboxes();
      switch(this.chkBox.checked) {
	    
        case true: 
          $('srvDistrib').setStyle('display','block'); 
          obj.innerHTML = '<i>Choisissez une ou plusieurs communes pour votre option</i>';
          break;
        
        default: 
          $('srvDistrib').setStyle('display','none'); 
          obj.innerHTML = '<i>Aucun suppl&eacute;ment appliqu&eacute;</i>';
          break;   
        
      }
      
      this.chkBox.blur();
      
    }.bind({'chkBox':chkBox}), 100);

  },
  
  // -------------------------------------------------------
  
  GetCheckboxes : function() {
    return $$('input[type="checkbox"].commune');	  
  },
  
  // -------------------------------------------------------
  
  ActiveCheckboxes : function(active) {
    OnePrint.GetCheckboxes().each(function(myEl){
	  myEl.disabled=(this.active==true)?false:true;
	}.bind({'active':active}));	  
  },
  
  // -------------------------------------------------------
  
  DecocheCheckboxes : function() {
    OnePrint.GetCheckboxes().each(function(myEl){
		  myEl.checked=false;
		});	  
    OnePrint.prix = 0;
    $('caddieTotal').innerHTML = '<b>'+ number_format(parseFloat(OnePrint.caddieTotal),2,',')+' &euro; T.T.C.</b>';
  },
  
  // -------------------------------------------------------

  UpdatePrix : function(vId,cId, act) {
		OnePrint.ActiveCheckboxes(false);
		new Ajax('oneprint/calcul.php', {
	    url : 'oneprint/calcul.php', 
	    onSuccess : function(prix) {
	      try {
			  	OnePrint.Villes[vId].Communes[cId].selection = true;
				} catch(e) {}
		      
		    // Mise à jour du prix de l'option
		    prix = parseFloat(prix);
		    if(this.act=='remove') {
		    	OnePrint.prix -= prix;
		    } else {
		    	OnePrint.prix += prix;
		    };
				$('optionPrix').innerHTML = '<b>'+ number_format(parseFloat(OnePrint.prix),2,',')+' &euro; T.T.C.</b>';
				
				// Mise à jour du prix du caddie
				caddieTotal = parseFloat(OnePrint.caddieTotal+OnePrint.prix);
				$('caddieTotal').innerHTML = '<b>'+ number_format(parseFloat(caddieTotal),2,',')+' &euro; T.T.C.</b>';
				
				OnePrint.ActiveCheckboxes(true);
			
	    }.bind({'vId':vId,'cId':cId,'act':act})
	    
	    ,onFailure:function(){
		    OnePrint.ActiveCheckboxes(true);   
	    } 
		}).request('cid='+cId+'&vid='+vId+'');
  },
  
  // -------------------------------------------------------
    
  ChoixCommune : function(chkBox, vId, cId) {
	setTimeout(function(){
	  var act = this.chkBox.checked ? 'add' : 'remove';
	  OnePrint.UpdatePrix(this.vId, this.cId, act);
    }.bind({'chkBox':chkBox,'vId':vId,'cId':cId}),50);
  }

  // -------------------------------------------------------
  
}

// ------------------------------------------------------------------------------------------------

var qtemoin = function(el){
	var input = eval(el);
	
	if(parseInt(input.value)>1){
		input.value = parseInt(input.value) - 1;
	}
}

var qteplus = function(el){
    var input = eval(el);
    
	input.value = parseInt(input.value) + 1;
}

// ------------------------------------------------------------------------------------------------

  var QtePlus = function() {
	window.document.forms['produit'].qte.value = parseInt(window.document.forms['produit'].qte.value)+1;
  }
  
  var QteMoins = function() {
	if( parseInt(window.document.forms['produit'].qte.value) > 1 ) { 
	  window.document.forms['produit'].qte.value = parseInt(window.document.forms['produit'].qte.value)-1;
	}
  }
  
  var PanierAjout = function() {
	window.document.forms['produit'].submit();
  }
  
  var Upload = function() {
    //$('recto').disabled=true;
    //$('verso').disabled=true;
    $('uploadProgress').setStyles({'display':'block'});
    $('ajoutPanier').setStyles({'display':'none'});
    window.document.forms['produit'].submit();
  }
  
  var UploadComplete = function() {
    //$('upload').remove();
    self.location = self.location+'?upload=ok';
  }