//**************************************************************************************
// Fichier : common.js
// Desc.   : Bibliothèque de fonction Javascript
//**************************************************************************************

/*******************************************************************************************
Fonction pour la gestion des champs IMAGE
********************************************************************************************/
function zoomImage(zoomfile, name, width, height)
{
        var hauteur= document.body.clientHeight;
        var largeur= document.body.clientWidth-180;

        if( height != "") hauteur=height;
        if( width != "") largeur=width;

        var top=0;
        var left=0;

        if( height != "") top+=100;
        if( width != "")  left+=100;

        nom="ZOOM";
        if( name != "") nom=name;

        window_temp=window.open(zoomfile,nom,'scrollbars=yes,top='+top+'px,left='+left+'px,width='+largeur+'px,height='+hauteur+'px,resizable=no,location=no,dependant=yes');

        //return window_temp;
}

function register_position(){
  mouse_x = 0;
  mouse_y = 0;
  document.onmousemove = position;
}

function position(evt){
  if(!evt) evt = window.event;
  mouse_x = evt.clientX;
  mouse_y = evt.clientY;
}

function popUp(theURL,larg,haut,posX,posY){
 info1 = window.open(theURL,"info1","dependent=yes,status=no,scrollbars=no,menubar=no,resizable=no,width="+ larg +"px,height="+ haut +"px,outerwidth="+ larg +"px,outerheight="+ haut +"px,top="+posY+",left="+posX+",screenX="+posX+",screenY="+posY);
 info1.focus();
}

/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


function zoomImageFit(zoomfile, name)
{
        nom="PREZOOM";
        if( name != "") nom=name;

        window_temp=window.open(zoomfile,nom,'scrollbars=yes,top=50px,left=50px,width=100px,height=100px,resizable=yes,location=no,dependant=yes');

        return window_temp;
}


/*******************************************************************************************
Fonctions relatives à la gestion des tableaux de liste
********************************************************************************************/

// Fonction qui coche ou décoche toute les cases de selection de la liste
function selectAll (formName)
{
        checked = document.forms[formName].elements['chkSelAll'].checked;

        len = document.forms[formName].elements.length;
        for(i=0; i < len; i++) {
            if ((document.forms[formName].elements[i].type == 'checkbox') &&
                (document.forms[formName].elements[i].name != 'chkSelAll'))
                    document.forms[formName].elements[i].checked = checked;
        }
}

function selectAllTexts (formName)
{
        len = document.forms[formName].elements.length;
        for(i=0; i < len; i++) {
            if ((document.forms[formName].elements[i].type == 'text') &&
                (trim(document.forms[formName].elements[i].value) == '')){
                    alert("Vous devez saisir tout les champs");
                    return false;

            }
        }
        return true;
}

function trim(string)
{
return string.replace(/(^\s*)|(\s*$)/g,'');
}

function selectAllExcept (formName)
{
        checked = document.forms[formName].elements['chkSelAll'].checked;

        len = document.forms[formName].elements.length;
        for(i=0; i < len; i++) {
            if ((document.forms[formName].elements[i].type == 'checkbox') &&
                (document.forms[formName].elements[i].name != 'chkSelAll')&&
                (document.forms[formName].elements[i].name != 'equals') )
                    document.forms[formName].elements[i].checked = checked;
        }
}



// Ask confirmation before deleting an element in a list
function confirmDelete (formName)
{
    flag = false;
    len = document.forms[formName].elements.length;
    for(i = 0; i < len; i++) {
            if ((document.forms[formName].elements[i].type == 'checkbox') &&
                 document.forms[formName].elements[i].checked) {
                   flag = true;
            }
    }

    if (flag == false) {
        alert ("Vous devez sélectionner un élément à supprimer.");
        return false;
    }

    return  window.confirm ('Etes-vous certain de vouloir supprimer le ou les élément(s) sélectionnée(s) ?');

}


/*******************************************************************************************
Fonctions de controle des champs de saisie des formulaires
********************************************************************************************/

// controle la validité de la date saisie
function isDate(d)
{
    if (d == '')
        return true;

    var amin=1900;  // année mini
    var amax=2060;  // année maxi
    var separateur='-'; // separateur entre jour/mois/annee
    var j=(d.substring(0,2));
    var m=(d.substring(3,5));
    var a=(d.substring(6));
    var ok=true;
    if ( ((isNaN(j))||(j<1)||(j>31)) && (ok==true) )  {
        ok = false;
    }
    if ( ((isNaN(m))||(m<1)||(m>12)) && (ok==true) )  {
        ok = false;
    }
    if ( ((isNaN(a))||(a<amin)||(a>amax)) && (ok==true) )  {
        ok = false;
    }
    if ( ((d.substring(2,3)!=separateur)||(d.substring(5,6)!=separateur)) && (ok==true) )   {
        ok = false;
    }

    return ok;
}



//vérifie si la chaine envoyée est de type e-mail
function isMail (mail)
{
      if (mail == '')
          return true;

      if ((mail.indexOf("@")>=0)&&(mail.indexOf(".")>=0)) {
         return true
      } else {
         return false
      }
}

//vérifie si la chaine envoyée correspond à une URL valide
function isUrl (mail)
{
      if (mail == '')
          return true;

      if (mail.indexOf("www.")>=0) {
         return true
      } else {
         return false
      }
}


function isInteger (sText)
//vérifie si la chaine envoyée est de type entier positif
{
   var ValidChars = "0123456789";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function isPhone (sText)
//vérifie si la chaine envoyée est un numéro de téléphone
{
   var ValidChars = "0123456789().-+ ";
   var IsTel=true;
   var Char;

   for (i = 0; i < sText.length && IsTel == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsTel = false;
         }
      }
   return IsTel;
}

function isPostalCode  (sText)
//vérifie si la chaine envoyée est un numéro de code postal
{
   var ValidChars = "0123456789";
   var IsCP=true;
   var Char;

   if (sText=='')
       return true;

   if (sText.length != 5)
       return false;

   for (i = 0; i < sText.length && IsCP == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsCP = false;
         }
      }
   return IsCP;
}


function isUnsignedFloat (sText)
//vérifie si la chaine envoyée est de type démale positif
{
   var ValidChars = "0123456789,";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function isDecimal (sText, m, d, s)
// vérifie si le nombre saisi est un nombre positif avec maximum m de précision
// dont d pour la parie décimale
{
   var ValidChars = "0123456789,";
   var IsNumber=true;
   var Char;
   var mm = 0;
   var dd = 0;
   var VirgulePassee = false;

   for (i = 0; i < sText.length && IsNumber == true; i++)
   {
      Char = sText.charAt(i);
      if (Char ==',')
      {
            if (sText.length-i > d+1)
             return (false);
         VirgulePassee = true;
      }
      if (!VirgulePassee)
           mm = mm + 1;
      else
           dd = dd + 1;
      if (ValidChars.indexOf(Char) == -1)
      {
         return (false);
      }
   }

   if (mm + d <= m)
      return true;
   else
      return false;
}
/*******************************************************************************************
Fonctions de calcul de prix (discount et tva)
********************************************************************************************/

function calculateD(){
    var discount = document.getElementById("discount").value.replace(",",".")/100;
    var priceD = document.getElementById("ProductPriceD").value.replace(",",".");
    var priceTI = document.getElementById("ProductPriceTI").value.replace(",",".");
    myValue = (Math.round((priceTI-(priceTI*discount))*100)/100) + "";
    document.getElementById("ProductPriceD").value = myValue.replace(".",",");
}
function calculateTI(){
    var discount = document.getElementById("discount").value.replace(",",".")/100;
    var priceD = document.getElementById("ProductPriceD").value.replace(",",".");
    var priceTI = document.getElementById("ProductPriceTI").value.replace(",",".");
    myValue = (Math.round((parseFloat(priceD) + parseFloat((priceD*discount)))*100)/100) + ""
    document.getElementById("ProductPriceTI").value = myValue.replace(".",",");
}

/*******************************************************************************************
listing cacher/ouvrir
********************************************************************************************/

var persisteduls=new Object()
var ddtreemenu=new Object()

ddtreemenu.closefolder="/themes/admin/css/clearmind/closed.gif" //set image path to "closed" folder image
ddtreemenu.openfolder="/themes/admin/css/clearmind/open.gif" //set image path to "open" folder image

//////////No need to edit beyond here///////////////////////////

ddtreemenu.createTree=function(treeid, enablepersist, persistdays){

  var ultags=document.getElementById(treeid).getElementsByTagName("ul")
  if (typeof persisteduls[treeid]=="undefined")
    persisteduls[treeid]=(enablepersist==true && ddtreemenu.getCookie(treeid)!="")? ddtreemenu.getCookie(treeid).split(",") : ""
  for (var i=0; i<ultags.length; i++)
    ddtreemenu.buildSubTree(treeid, ultags[i], i)

  //if enable persist feature
  if (enablepersist==true){
    var durationdays=(typeof persistdays=="undefined")? 1 : parseInt(persistdays)
    ddtreemenu.dotask(window, function(){ddtreemenu.rememberstate(treeid, durationdays)}, "unload") //save opened UL indexes on body unload
  }
}

ddtreemenu.buildSubTree=function(treeid, ulelement, index){

  ulelement.parentNode.className="submenu"
  if (typeof persisteduls[treeid]=="object"){ //if cookie exists (persisteduls[treeid] is an array versus "" string)
    if (ddtreemenu.searcharray(persisteduls[treeid], index)){
      ulelement.setAttribute("rel", "open")
      ulelement.style.display="block"
      ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
    }
    else
      ulelement.setAttribute("rel", "closed")
  } //end cookie persist code
  else if (ulelement.getAttribute("rel")==null || ulelement.getAttribute("rel")==false) //if no cookie and UL has NO rel attribute explicted added by user
    ulelement.setAttribute("rel", "closed")
  else if (ulelement.getAttribute("rel")=="open") //else if no cookie and this UL has an explicit rel value of "open"
    ddtreemenu.expandSubTree(treeid, ulelement) //expand this UL plus all parent ULs (so the most inner UL is revealed!)

  ulelement.parentNode.onclick=function(e){
    var submenu=this.getElementsByTagName("ul")[0]

    // particulier pour le "ftp"
    // empeche l'expand de l'arborescence si un des divs "menu" est ouvert
    var flag_notmove=false;
    var alldivs=document.getElementsByTagName('div');
    for(var k=0, elm; elm=alldivs[k++];) {
      if(elm.style.visibility == "visible"){
        flag_notmove=true;
        break;
      }
    }

    if (submenu.getAttribute("rel")=="closed"){
      submenu.style.display="block"
      submenu.setAttribute("rel", "open")
      ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
    }
    else if ((flag_notmove == false) && (submenu.getAttribute("rel")=="open")){
      submenu.style.display="none"
      submenu.setAttribute("rel", "closed")
      ulelement.parentNode.style.backgroundImage="url("+ddtreemenu.closefolder+")"
    }
    ddtreemenu.preventpropagate(e)

  }

  ulelement.onclick=function(e){
    ddtreemenu.preventpropagate(e)
  }
}

//expand a UL element and any of its parent ULs
ddtreemenu.expandSubTree=function(treeid, ulelement){

  var rootnode=document.getElementById(treeid)
  var currentnode=ulelement
  currentnode.style.display="block"
  currentnode.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
  while (currentnode!=rootnode){
    if (currentnode.tagName=="UL"){ //if parent node is a UL, expand it too
      currentnode.style.display="block"
      currentnode.setAttribute("rel", "open") //indicate it's open
      currentnode.parentNode.style.backgroundImage="url("+ddtreemenu.openfolder+")"
    }
    currentnode=currentnode.parentNode
  }
}

//expand or contract all UL elements
ddtreemenu.flatten=function(treeid, action){

  var ultags=document.getElementById(treeid).getElementsByTagName("ul")
  for (var i=0; i<ultags.length; i++){
    ultags[i].style.display=(action=="expand")? "block" : "none"
    var relvalue=(action=="expand")? "open" : "closed"
    ultags[i].setAttribute("rel", relvalue)
    ultags[i].parentNode.style.backgroundImage=(action=="expand")? "url("+ddtreemenu.openfolder+")" : "url("+ddtreemenu.closefolder+")"
  }
}

//store index of opened ULs relative to other ULs in Tree into cookie
ddtreemenu.rememberstate=function(treeid, durationdays){

  var ultags=document.getElementById(treeid).getElementsByTagName("ul")
  var openuls=new Array()
  for (var i=0; i<ultags.length; i++){
    if (ultags[i].getAttribute("rel")=="open")
      openuls[openuls.length]=i //save the index of the opened UL (relative to the entire list of ULs) as an array element
  }
  if (openuls.length==0) //if there are no opened ULs to save/persist
    openuls[0]="none open" //set array value to string to simply indicate all ULs should persist with state being closed
  ddtreemenu.setCookie(treeid, openuls.join(","), durationdays) //populate cookie with value treeid=1,2,3 etc (where 1,2... are the indexes of the opened ULs)
}

////A few utility functions below//////////////////////

//get cookie value
ddtreemenu.getCookie=function(Name){

  var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
  if (document.cookie.match(re)) //if cookie found
    return document.cookie.match(re)[0].split("=")[1] //return its value
  return ""
}

//set cookei value
ddtreemenu.setCookie=function(name, value, days){

  var expireDate = new Date()
  //set "expstring" to either future or past date, to set or delete cookie, respectively
  var expstring=expireDate.setDate(expireDate.getDate()+parseInt(days))
  document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()+"; path=/";
}

//searches an array for the entered value. If found, delete value from array
ddtreemenu.searcharray=function(thearray, value){

  var isfound=false
  for (var i=0; i<thearray.length; i++){
    if (thearray[i]==value){
      isfound=true
      thearray.shift() //delete this element from array for efficiency sake
      break
    }
  }
return isfound
}

//prevent action from bubbling upwards
ddtreemenu.preventpropagate=function(e){

  if (typeof e!="undefined")
    e.stopPropagation()
  else
    event.cancelBubble=true
}

//assign a function to execute to an event handler (ie: onunload)
ddtreemenu.dotask=function(target, functionref, tasktype){

  var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
  if (target.addEventListener)
    target.addEventListener(tasktype, functionref, false)
  else if (target.attachEvent)
  target.attachEvent(tasktype, functionref)
}

function preloadimage() {
var doc=document;
if(doc.images){ if(!doc.precharg) doc.precharg=new Array();
var i,j=doc.precharg.length,x=prechargimg.arguments; for(i=0; i<x.length; i++)
if (x[i].indexOf("#")!=0){ doc.precharg[j]=new Image; doc.precharg[j++].src=x[i];}}
}
