/*
 Librairie de fonction JavaScript
*/

// compte le nombre de caractère d'un type texte
function count_chars(obj,max_chars,obj_cpt)
{
  var value = obj.value;
	var current_length = value.length;

	reste_chars = max_chars - current_length;

	obj_cpt.value = reste_chars;

	if( current_length >= max_chars )
	  alert(max_chars + " caractères dépasser !!!\nTous les caractères au delà du " + max_chars + "ème seront tronqués !!!");
}

// transfert une option d'une liste à choix simple ou multiple vers une autres liste similaire
function add(obj_org,obj_dest)
{
  for(k=0; k < obj_org.length; k++)
  {
		if(obj_org.options[k].selected)
		{
		  var myOption = document.createElement("OPTION");

		  myOption.text  = obj_org.options[k].text;
		  myOption.value = obj_org.options[k].value;

		  obj_dest.options[obj_dest.length] = myOption;
		  obj_org.options[k] = null;
			k--;

			delete myOption;
		}
  }
}

/**
* Supprime les options sélectionnés
*/
function remove(obj)
{
  for(k=0; k < obj.length; k++)
  {
		if(obj.options[k].selected)
		{
		  obj.options[k] = null;
			k--;
		}
  }
}

/**
* Supprime une option par valeur
*/
function remove_value(obj, val)
{
  for(k=0; k < obj.length; k++)
  {
		if(obj.options[k].value == val)
		{
		  obj.options[k] = null;
			k--;
		}
  }
}

/**
* Selectionne toutes les options d'une liste à choix multiple
*/
function select_all(obj)
{
  for(var k=0; k < obj.length; k++)
  {
	  obj.options[k].selected = true;
	}
}

/**
* Déselectionne tous les éléments d'une liste
*/
function select_none(obj)
{
  for(var k=0; k < obj.length; k++)
  {
	  obj.options[k].selected = false;
	}
}

/**
* Supprime la totalité des éléments options d'un select
*
* Effectue une suppression des éléments options d'un select list.
* A chaque suppression, toute la liste remonte d'un cran.
* L'élément à supprimer à donc toujours l'index 0.
*/
function remove_all(obj)
{
	var count = obj.length;

  for(var k=0; k < count; k++)
  {
	  obj.options[0] = null;
	}
}

// selectionne une option d'une liste à choix simple, ou la première correspondance d'une liste à choix multiple
function selectValue(obj,val)
{
  for(var k=0; k < obj.length; k++)
  {
    if(obj.options[k].value == val)
    {
	    obj.options[k].selected = true;
	    break;
	  }
	}
}

// copie une ou des valeurs d'un select list vers une autre
function copy(obj_src, obj_dest)
{
  for(var k=0; k < obj_src.length; k++)
  {
	  if(obj_src.options[k].selected)
	  {
	    var opt = new Option();
	    opt.value = obj_src.options[k].value;
	    opt.text = obj_src.options[k].text;

	    obj_dest.options[obj_dest.length] = opt;
	    //obj_src.options[k] = opt;
	  }
	}
}

// équivalent de la foncion str_pad de PHP
function strPad(str,pad_length,pad_string,pad_type)
{
  if( (str == null) || (pad_length == undefined) )
    return str;

  if(pad_string == null)
    pad_string = " ";

  if(pad_type == null)
    pad_type = "RIGHT";

  var add_string = "";

  for(var k=str.length; k < pad_length; k++)
    add_string += pad_string;

  switch(pad_type)
  {
    case "LEFT":
      return add_string + str;
      break;
    case "RIGHT":
      return str + add_string;
      break;
    default:
      break;
  }
}

// vérifie si l'URL d'appel d'un popup est une page précise
function check_parent_url(string_url)
{
  var url_parent = opener.location.href;

  if( url_parent.substring( url_parent.lastIndexOf('/')+1 , url_parent.indexOf('?') ) == string_url)
    return true;

  return false;
}

function check_email(email)
{
  return true;
}

function get_date_for_popup(select_date)
{
  var day   = eval("document.getElementById('"+ select_date + "[day]').options[document.getElementById('"+ select_date + "[day]').selectedIndex].value");
  var month = eval("document.getElementById('"+ select_date + "[month]').options[document.getElementById('"+ select_date + "[month]').selectedIndex].value");
  var year  = eval("document.getElementById('"+ select_date + "[year]').options[document.getElementById('"+ select_date + "[year]').selectedIndex].value");

  //alert("d=" + day + "&m=" + month + "&y=" + year);

  return "d=" + day + "&m=" + month + "&y=" + year;
}

/**
* monte ou descend une valeur dans une select list
*/
function move(obj, sens)
{
	for(var k=0; k < obj.options.length; k++)
	{
		if( obj.options[k].selected && (obj.options[k] != "") )
		{
			switch(sens)
      {
        case "up":
          var i = k-1;
          break;

        case "down":
          var i = k+1;
          break;

        default:
          return true;
          break;
      }

      if( (i < 0) || (i >= obj.options.length) )
      {
        //alert("Bornes atteintes");
        return false;
      }

      // k : objet à remplacer par i
      // i : objet à remplacer par k

			var tmpval 	= obj.options[k].value;
			var tmptxt 	= obj.options[k].text;

			obj.options[k].value 	= obj.options[i].value;
			obj.options[k].text 	= obj.options[i].text
			obj.options[i].value 	= tmpval;
			obj.options[i].text 	= tmptxt;

			obj.options[k].selected = false;
			obj.options[i].selected = true;

			if( (k+1) == i )
				k+=1;
  	}
	}

	return true;
}

/**
* Remplace une ou des options par les valeurs passées
*/
function replace_option(obj,new_val,new_txt)
{
	for(var k=0; k < obj.options.length; k++)
	{
		if( obj.options[k].selected)
		{
			if( new_val != null )
				obj.options[k].value = new_val;

			if( new_txt != null )
				obj.options[k].text = new_txt;
		}
	}

	return true;
}

/**
* Ajoute une ou des options à une list
*/
function add_option(obj,val,txt,sel)
{
	var myOption = document.createElement("OPTION");

	myOption.text  = txt;
	myOption.value = val;

	obj.options[obj.options.length] = myOption;
	obj.options[obj.options.length-1].selected = sel;
}

//Fonction pour insérer des balises dans le textarea
function countInstances(open,closed)
{
	var opening = document.getElementById('description').value.split(open);
	var closing = document.getElementById('description').value.split(closed);
	return opening.length + closing.length - 2;
}

function TAinsert(text1, text2, textarea)
{
	var ta = document.getElementById(textarea);
	if (document.selection)
	{
		var str = document.selection.createRange().text;
		ta.focus();
		var sel = document.selection.createRange();
		if (text2 != "")
		{
			if (str == "")
			{
				var instances = countInstances(text1,text2);
				if (instances%2 != 0) sel.text = sel.text + text2;
				else sel.text = sel.text + text1;
			}
			else sel.text = text1 + sel.text + text2;
		}
		else sel.text = sel.text + text1;
	}
	else if (ta.selectionStart || ta.selectionStart == 0)
	{
		if (ta.selectionEnd > ta.value.length) ta.selectionEnd = ta.value.length;
		var firstPos = ta.selectionStart;
		var secondPos = ta.selectionEnd+text1.length;
		var contenuScrollTop = ta.scrollTop;

		ta.value=ta.value.slice(0,firstPos)+text1+ta.value.slice(firstPos);
		ta.value=ta.value.slice(0,secondPos)+text2+ta.value.slice(secondPos);

		ta.selectionStart = firstPos+text1.length;
		ta.selectionEnd = secondPos;
		ta.focus();
		ta.scrollTop = contenuScrollTop;
	}
	else
	{ // Opera
		var sel = document.hop.contenu;
		var instances = countInstances(text1,text2);
		if (instances%2 != 0 && text2 != "") sel.value = sel.value + text2;
		else sel.value = sel.value + text1;
	}
}

//Vérifie si les champs d'un formulaire sont bien remplis
function verifFormulaire(frm, champsString)
{
	champs = champsString.split(" ");
	test = true;
	tab = new Array();
	for(i=0;i < champs.length;i++)
	{
		if(frm.elements[champs[i]].value == '')
		{
			test = false;
			tab[tab.length] = champs[i];
		}
	}
	if(test)
	{
		return true;
	}
	else
	{
		string = tab.join(', ');
		alert('veuillez remplir le(s) champs ' + string);
		return false;
	}
}

//Modifie le tableau de gestion des prix en fonction du type de l'article (textile / autre).
function checkTextile(checkbox)
{
	if(checkbox.checked)
	{
		document.getElementById('prixu').innerHTML = 'Prix unitaire hors impression (en €)';
		document.getElementById('btnAjoutImp').style.visibility = 'visible';
		//document.getElementById('prixut').style.display = 'table-row'; // bug sous IE 6
		document.getElementById('prixut').style.display = 'inline';
		document.getElementById('zi_prixu').style.display = 'none';
	}
	else
	{
		document.getElementById('prixu').innerHTML = 'Prix unitaire net (en €)';
		document.getElementById('btnAjoutImp').style.visibility = 'hidden';
		document.getElementById('prixut').style.display = 'none';

		if(document.selection)
		{
			document.getElementById('zi_prixu').style.display = 'block';
		}
		else
		{
			//document.getElementById('zi_prixu').style.display = 'table-row'; // bug sous IE 6
			document.getElementById('zi_prixu').style.display = 'inline';
		}
	}
}

function showHelp()
{
	help2 = document.getElementById('help');
	if (help2.style.display == 'none')
	{
		help2.style.display = 'block';
	}
	else help2.style.display = 'none';
}

function clients_adresses( intitule , civil,nom , prenom ,entreprise ,adresse_1 ,adresse_2,appart ,etage ,cporte, cp ,ville ,id_pays ,fixe ,port , date_modif)
{
this.id_client_adresse =0;
this.id_client						= 0;
this.intitule						= intitule;
this.civil								= civil;
this.nom									= nom;
this.prenom								= prenom;
this.entreprise						= entreprise;
this.adresse_1						= adresse_1;
this.adresse_2						= adresse_2;
this.appart								= appart;
this.etage								= etage;
this.cporte								= cporte;
this.cp										= cp;
this.ville								= ville;
this.id_pays							=id_pays;
this.fixe									= fixe;
this.port									= port;
this.date_export					= 0;
this.date_modif						= date_modif;

}

function newwin(url, scroll, largeur, hauteur, top, left)
{
  if(top == null)
    top = 0;
  if(left == null)
    left = 0;

  top += 10;
  left += 10;

  if(largeur == 0)
    largeur = window.screen.availWidth;
  if(hauteur == 0)
    hauteur = window.screen.availHeight;

  window.open(url,'','toolbar=0,location=0,directories=0,menuBar=0,scrollbars=' + scroll + ',resizable=1,width=' + largeur + ',height=' + hauteur + ',top=' + top + ',left=' + left + ',copyhistory=0,dependent=0')
}




function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}


function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}



MM_reloadPage(true);


function update_texte(id, n, zi, s)
{
	xmlhttp.open("GET", "<?php echo APP_ABSURL ?>xmlhttp/update_texte_personnalisation.php?i=" + id + "&n=" + n + "&z=" + zi + "&s=" + s, true);
	xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

	xmlhttp.onreadystatechange = function()
	{
		if( xmlhttp.readyState == 4 )
		{
			var response = xmlhttp.responseText;
			string = 'cadre_bouton[' + n + ']';
			document.getElementById(string).innerHTML = response;
		}
	}
	xmlhttp.send(null);
}
