//cree une fenetre popup avec le msg donne, elle se ferme en tapant sur Entree
function messageWindow(title, msg, width, height)
{
  var left = (screen.width/2) - width/2;
  var top = (screen.height/2) - height/2;
  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,'
                +'scrollbars=no,resizable=no,copyhistory=yes,width='+width+',height='+height
                +',left='+left+',top='+top+',screenX='+left+',screenY='+top;
  var msgWindow = window.open("","msgWindow", styleStr);
  var head = '<head>\n<title>'+title+'</title>\n</head>\n<body bgcolor="#FFCC33" onKeyDown="self.close()">\n';
  var body = '<center>'+msg+'\n<br><p>\n<form>\n<input type="button" value="  Entrée  "  '
             +'onClick="self.close()">\n</form>\n</center>\n</body>';
  msgWindow.document.write(head + body);
}

//cree une fenetre popup avec le msg donne, la taille, la position(x,y) elle se ferme en tapant sur Entree
function popWindow(title, msg, width, height, x, y, url)
{
  var left = (x == 'c') ? ((screen.width/2) - width/2) : x;
  var top = (y == 'c') ? ((screen.height/2) - height/2) : y;
  var styleStr = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes'
                +',resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+',top='+top;
  
  if( url )
    window.open( msg, "msgWindow", styleStr);
  else 
  {
    var msgWindow = window.open("","msgWindow", styleStr);
    var head = '<head>\n<title>'+title+'</title>\n</head>\n<body onKeyDown="self.close()">\n';
    var body = msg+'<center>\n<br><p>\n<form>\n<input type="button" value="  Entrée  " '
              +' onClick="self.close()">\n</form>\n</center>\n</body>';
    msgWindow.document.write(head + body);
  }
}

//coche toutes les cases a cocher de nom cbN du formulaire adminForm
function checkAll( n )
{
	var f = document.adminForm;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) 
	{
		cb = eval( 'f.cb' + i );
		if (cb)
		  cb.checked = c;
	}
}

//coche le checkbox 'nom'
function chck( nom )
{
	cb = eval( 'document.adminForm.'+nom );
	cb.click();
}

//verifie que les champs donnes en arguments (apres le nom du formulaire) sont renseignes
function submForm() {
  var args = submForm.arguments;
  var form = 'document.' + args[0];
  var boutSubmit = form + '.sub' + args[0];
  boutSubmit.disabled = true;
  
  for( var i=1; i<args.length; i++)
  {
  	champ = eval( form+'.'+args[i] );
	if( champ.value == '' ) 
	{
	  alert( "Un ou plusieurs champs ne sont pas renseignés" )
	  champ.focus();
	  champ.className='highlight';
	  return false;
	}
  }
  return true;
}

//verifie si champ str est une adresse mail
function isEmail(str)
{
  // are regular expressions supported?
  var supported = 0;
  if (window.RegExp) {
    var tempStr = "a";
    var tempReg = new RegExp(tempStr);
    if (tempReg.test(tempStr)) supported = 1;
  }
  if (!supported) 
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

//alerte si mail mauvais
function veriMail( str )
{
  if( ! isEmail( str ) )
  {
    alert('Adresse e-mail non valide');
    return false;
  }
  return true;
}

//alerte si mail AOL
function veriAol( str )
{
  if( str.indexOf( "@aol." ) >= 0 )
  {
    alert('Adresse AOL interdite (blacklistage abusif)');
    return false;
  }
  return true;
}

function veriPass( champ1,champ2 )
{
  
  if( champ1.value != champ2.value )
  {
    alert('Les deux mots de passe ne correspondent pas!' );
    return false;
  }
  if( champ1.value.length < 5 )
  {
    alert('Le mot de passe est trop court (5 caractères alphanumériques minimum)!' );
    return false;
  }
  return true;
}

//verification de l'age
function veriAge( champ, min )
{
  if( champ.value < min )
  {
    alert('L\'age doit être supérieur à '+min+' ans !');
    return false;
  }
  return true;
}

//Verifications a la soumission du formulaire PJ
function subPJ()
{
  if( progress == 1 ) 
  {
    alert('Opération en cours d\'éxécution!');
    exit();
  }
  var progress = 1;
  if( ! veriAge( document.PJ.age, 15 ) )
    return false;
  if( ! veriPass( document.PJ.passwd, document.PJ.passwd2 ) )
    return false;
  if( ! veriMail( document.PJ.email.value ) )
    return false;
  if( ! veriAol( document.PJ.email.value ) )
    return false;
  if( submForm( 'PJ', 'username', 'passwd', 'email', 'nom', 'prenom', 'age', 'planete', 'race', 'back', 'arme' ) )
    document.PJ.submit();
}

//Verification de la taille d'un champ
function verifTaille( champ, taille )
{
  if( champ.value.length >= taille ) 
  {
    alert('Il y a trop de caractères!');
	champ.focus();
	champ.className='highlight';
    return false;
  }
  return true;
}

//Affiche le champ cache nom
function afficheChampCache( nom, which )
{
  var nava = (document.layers);
  var dom = (document.getElementById);
  var iex = (document.all);
  if (nava) { cach = "document."+nom }
  else if (dom) { cach = document.getElementById( nom ).style }
  else if (iex) { cach = nom+".style" }
  cach.display = which;
}

//cache le champ cache
function cacheChampCache( nom )
{
  var nava = (document.layers);
  var dom = (document.getElementById);
  var iex = (document.all);
  if (nava) { cach = "document."+nom }
  else if (dom) { cach = document.getElementById( nom ).style }
  else if (iex) { cach = nom+".style" }	
  cach.display = "none";
}

//cache le champ cache
function toggleChampCache( nom, which )
{
  var nava = (document.layers);
  var dom = (document.getElementById);
  var iex = (document.all);
  if (nava) { cach = "document."+nom }
  else if (dom) { cach = document.getElementById( nom ).style }
  else if (iex) { cach = nom+".style" }

  if( cach.display == "none" )
    cach.display = which;
  else
    cach.display = "none";
}

//affiche ou cache le champ de choix des postes dans AE GetIn
function modifChampCache()
{
  if( document.PJ.arme.value == 1 )
    afficheChampCache( 'cache', 'table-row' );
  else
    cacheChampCache( 'cache' );
}

/**
* Ajoute l'elements selectionne d'une liste a l'autre
*/
function addSelectedToList( frmName, srcListName, tgtListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );
	var tgtList = eval( 'form.' + tgtListName );

	var srcLen = srcList.length;
	var tgtLen = tgtList.length;
	var tgt = "x";

	//build array of target items
	for (var i=tgtLen-1; i > -1; i--) {
		tgt += "," + tgtList.options[i].value + ","
	}

	//Pull selected resources and add them to list
	for (var i=srcLen-1; i > -1; i--) {
		if (srcList.options[i].selected && tgt.indexOf( "," + srcList.options[i].value + "," ) == -1) {
			opt = new Option( srcList.options[i].text, srcList.options[i].value );
			tgtList.options[tgtList.length] = opt;
		}
	}
}

/**
* Ajoute le couple de chaine donne à la liste donnée
*//*
function addStringToList( frmName, str1, str2, tgtListName ) {
	var form = eval( 'document.' + frmName );
	var tgtList = eval( 'form.' + tgtListName );

	var tgtLen = tgtList.length;
	var tgt = "x";
	var value = str2 + "," + str1;

	//build array of target items
	for (var i=tgtLen-1; i > -1; i--) {
		tgt += "," + tgtList.options[i].value + ","
	}

	if (tgt.indexOf( "," + value + "," ) == -1) {
		opt = new Option( str1, value );
		tgtList.options[tgtList.length] = opt;
	}
}*/

//supprime l'elementdonne d'une liste
function delSelectedFromList( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	var srcLen = srcList.length;

	for (var i=srcLen-1; i > -1; i--) {
		if (srcList.options[i].selected) {
			srcList.options[i] = null;
		}
	}
}

//cree une chaine de caractere a partir des elt selectionnes d'une liste, separes par le separator
function implodeListVal( form, list, champrep, separator )
{
    var listSource = eval( 'document.' + form + '.' + list );
	var champRecept = eval( 'document.' + form + '.' + champrep );
	var temp = new Array;
	
	for (var i=0, n=listSource.options.length; i < n; i++) {
		temp[i] = listSource.options[i].value;
	}
	champRecept.value = temp.join( separator );
}

//cree une chaine de caractere a partir des textes des elt selectionnes d'une liste, separes par le separator
function implodeListTxt( form, list, champrep, separator )
{
    var listSource = eval( 'document.' + form + '.' + list );
	var champRecept = eval( 'document.' + form + '.' + champrep );
	var temp = new Array;
	
	for (var i=0, n=listSource.options.length; i < n; i++) {
		temp[i] = listSource.options[i].text;
	}
	champRecept.value = temp.join( separator );
}

//pour disable tous les champs d'unite sauf celui choisi
function chooseUnit( nb, id )
{
  for( i=1; i<=nb; i++ )
  {
	var liste = eval( 'document.form_new.poste'+i );
    liste.disabled = true;
  }
  if( id != 0 )
  {
    var listeSel = eval( 'document.form_new.poste'+id );
    listeSel.disabled = false;
  }
}

//pour voir les imges d'une liste de defilement d'images
/*
function previewImg( list, form, image, siteUrl )
{
  srcList = eval( "document." + form + "." + list );
  srcImage = eval( "document." + image );
  var fileName = srcList.options[srcList.selectedIndex].text;
  var fileName2 = srcList.options[srcList.selectedIndex].value;
  if ( fileName2 == "" )
  {
	srcImage.src = siteUrl + '/images/blank.png';
  } else {
	srcImage.src = siteUrl + '/upload/' + fileName2;
  }
}*/
function endisable()
{
  var args = endisable.arguments;
  var which = args[0].checked;
  
  for( i=1; i<args.length; i++ )
  {
    args[i].disabled = ! which;
  }  
}

function fileManager(field_name, url, type, win) {      
    width = 660;
    height = 500;
    x = parseInt(screen.width / 2.0) - (width / 2.0);
    y = parseInt(screen.height / 2.0) - (height / 2.0);
    urlPopup = 'http://localhost/site-mere/tinymce/plugins/filemanager/'
        +'insertfile/insert_file.php?standalone=true'
        +'&type='+type
        +'&field_name='+field_name
        +'&cur_url='+url;
  
    var win2 = window.open( urlPopup,
                            "mceFM",
                            "top=" + y + ",left=" + x + ",scrollbars=no,dialog=yes,minimizable=no"
                            +",modal=yes,width="+ width +",height="+ height +",resizable=no" );

    setTimeout(function(){win2.lastWin = win;}, 2000 );
}

function changeContent( htmlElementId, value )
{
  document.getElementById( htmlElementId ).innerHTML = value;
}

//pour aelivreor
function changeDebut( offset )
{
  document.livreor.debut.value = offset;
  document.livreor.etat.value = "change";
  document.livreor.submit();
}

//pour aenews
function changeDebutNs( offset )
{
  document.aenews.debut.value = offset;
  document.aenews.submit();
}

//pour aelist
//change d'item
function changeItem( newitem )
{
  document.configOffi.itemn.value = newitem;
  document.configOffi.debut.value = 0;
  document.configOffi.submit();
}

//acces a la page dont l'id de debut est specifie
function page( id )
{
  document.configOffi.debut.value = id;
  document.configOffi.submit();
}

// formulaire d'identification
function clickLoginIpt(elt) {
	elt.className = "selectedInput";
}

function blurLoginIpt(elt) {
	if(elt.value == '') {
		elt.className = "loginInput";
	}
}

function clickPassIpt(elt) {
	elt.className = "selectedInput";
}

function blurPassIpt(elt) {
	if(elt.value == '') {
		elt.className = "passInput";		
	}
}

// pour gerer les cellules d'articles et les modeles
// table : HTMLTableSectionElement tableau parent (tbody) du formulaire
// imgDelSrc : string adresse de l'image de suppression d'une ligne
// bAdmin : boolean du champ a creer default false [optional]
function CellCreator( el, imgDelSrc, instanceName, bAdmin, input ){
    this.parentTable = el;
    this.fieldIndex = 0;
    this.imgDelSrc = imgDelSrc;
    this.instanceName = instanceName;
    this.cell1 = this.cell2 = '';
    this.admin = bAdmin != null ? bAdmin : false;
    this.input = input != null ? document.getElementById(input) : null;
}

// nom : String nom du champ [optional]
// desc : string description du champ a creer [optional]
// valeur : string la valeur champ a creer [optional]
CellCreator.prototype.addField = function( nom, desc, valeur ) {
    this.fieldIndex ++;
    nom = nom != null ? nom : '';
    desc = desc != null ? desc : '';
    valeur = valeur != null ? valeur : '';
    
    var tempRow = document.createElement( "tr" );
    var tempCell1 = document.createElement( "td" );
    var tempCell2 = document.createElement( "td" );
    tempCell1.setAttribute('valign','top');
    
    tempRow.setAttribute( "id", "cellFieldRow"+this.fieldIndex );
    
    this.cell1 = '<input type="text" name="champ'+this.fieldIndex
                  +'" id="champ'+this.fieldIndex+'" value="'+nom+'"/>'
                  +'<a href="javascript:'+this.instanceName
                  +'.removeField(\'cellFieldRow'+this.fieldIndex+'\')" title="Supprimer ce champ">'
                  +' <img src="'+this.imgDelSrc+'" border=\"0\" /></a>';
    
    if( this.admin )
      this.cell2 = '<input type="text" name="desc'+this.fieldIndex
                  +'" id="desc'+this.fieldIndex+'" value="'+desc+'" size="40"/>';
    else {
      this.cell2 = '<textarea name="valeur'+this.fieldIndex+'" id="valeur'+this.fieldIndex+'">';

      if(desc != '')
      this.cell1 += '&nbsp;<a href="javascript:void(0)" onMouseOver="return overlib(\''+desc+'\',\'adaptive_width\')"'
                    +' onMouseOut="return nd()" onFocus="this.blur()" class="tooltip" >'
                    +'aide</a>';
    }
                  
    
    tempCell1.innerHTML = this.cell1;
    tempCell2.innerHTML = this.cell2;
    tempRow.appendChild( tempCell1 );
    tempRow.appendChild( tempCell2 );
    this.parentTable.appendChild( tempRow );
    if(!this.admin)
      window.tinyMCE.addMCEControl(document.getElementById('valeur'+this.fieldIndex),
                                   'valeur'+this.fieldIndex);
}

// id : string id de la ligne a supprimer [optional]
CellCreator.prototype.removeField = function( id ) {
    if( id != null )
      this.parentTable.removeChild( document.getElementById( id ) );
    else
      this.parentTable.removeChild( this.parentTable.lastChild );
}

// modele : array modele de cellule
CellCreator.prototype.mapModele = function( modele ) {
    this.clear();
    for( i=0; i < modele.length; i++ )
        this.addField( modele[i][0], modele[i][1], modele[i][2] );
}

// supprime tout
CellCreator.prototype.clear = function() {
    this.cell1 = this.cell2 = '';
    this.fieldIndex = 0;
    
    for(var i=this.parentTable.childNodes.length-1; i>=0; i--)
        this.parentTable.removeChild(this.parentTable.childNodes[i]);
}

// enregistre une chaine de caractère contenant les champs et leur valeurs
// dans l'input prévu à cet effet (si il est donné)
CellCreator.prototype.commit = function() {
    if(this.input != null){
        var committedString = new Array();
        // creation de la chaine de caracteres
        for(var i=0, j=0; i<=this.fieldIndex; i++ ) {
            if((document.getElementById('cellFieldRow'+i))!=null) {
              committedString[j] = '[['+document.getElementById('champ'+i).value+'],';
              valeur = this.admin ? document.getElementById('desc'+i).value
                                  : document.getElementById('valeur'+i).value; 
              committedString[j] += '['+valeur+']]';
              j++;
            }
        }
        myString = '['+committedString.join(',')+']';
        this.input.value = myString;
    } else {
        return false;
    }
}