/*********************************************************************************
 Copyright (c) 2002-2005 Armin Burger
 Copyright (c) 2005-2006 GEOSIGNAL - www.geosignal.fr - contact@geosignal.fr

 
 Permission is hereby granted, free of charge, to any person obtaining 
 a copy of this software and associated documentation files (the "Software"), 
 to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, 
 and/or sell copies of the Software, and to permit persons to whom the Software 
 is furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included 
 in all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
 FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR OR 
 COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
 IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**********************************************************************************/

/**********************************************************
 * 
 *
 *
 *********************************************************/
var legendContainer = new Object();

/**
 * initialize and write TOC by calling XMLHttp function 'updateToc()' 
 * 
 */
function initToc() {
    catsAlwaysChecked = splitCatsAlwaysChecked(catsAlwaysChecked);
    legendContainer.checkedGrpList = defGroupList;
    var tocurl = 'x_toc.php?' + SID;
    updateToc(tocurl, '');
}


function splitCatsAlwaysChecked(str) {
  var arr  = [];
  if(str != "") {
    var cats = str.split("|#|");
    for(var i=0; i<cats.length; i++) {
      var cat  = cats[i].split("||");
      var grps = cat[1].split(",");
      for(var j=0; j<grps.length; j++) {
        grps[j] = grps[j].trim();
      }
      arr[arr.length] = [cat[0].trim(), grps];
    }
  }
  return arr;      
}

/**
 * Toggle groups and categories (and related images)
 * attached as onClick script to plus/minus icons and links
 */
function tg(group) {
    var crIE = (document.all && !navigator.userAgent.match(/Opera|Konqueror|Safari/i) ? true : false);
    var divobj = document.getElementById(group);
    var dheight;

    if (divobj.style.visibility == 'hidden') {
        var visToSet = 'visible';
        if (crIE) {
            dheight = 0;
            divobj.style.width = 'auto';
        } else {
            dheight = 'auto';
            divobj.style.overflow = "visible";
        }
        document.getElementById(group + '_timg').src = 'images/tree/minus.gif';
    } else {
        var visToSet = 'hidden';
        if (crIE) {
            divobj.style.width = 0;
            dheight = 1;
        } else {
            dheight = 0;
        }
        divobj.style.overflow = 'hidden';
        document.getElementById(group + '_timg').src = 'images/tree/plus.gif';
    }
    
    divobj.style.height = dheight;
    divobj.style.visibility = visToSet;
    //document.getElementById('pmtree').style.overflow = 'auto';
}

function tg2(oCb, group) {
  if(plusMinusChecbox) {
    var divobj  = document.getElementById(group);  
    if((oCb.checked && divobj.style.visibility != "visible") || (!oCb.checked && divobj.style.visibility != "hidden")) {
      divobj.style.visibility == oCb.checked ? "hidden" : "visible";
      tg(group);
    }
  }
  setlayers(group);
}

function myGetElementsByName(name, tagName) {
  if (document.all) {
    var arr = [];
    var elements = typeof(tagName) == "undefined" ? document.all : document.body.getElementsByTagName(tagName);
    for (var i=0; i<elements.length; i++) {
        if (elements[i].name == name) { arr[arr.length] = elements[i]; }
    }
    return arr;     
  }
  
  return document.getElementsByName(name);
}

function isGrpInAlwaysChecked(grpName) {
  grpName = grpName.trim();
  for (var i=0; i<catsAlwaysChecked.length; i++) {
    var grps = catsAlwaysChecked[i][1];
    for (var j=0; j<grps.length; j++) {
      if (grps[j] == grpName) { return true; }
    }
  }
  return false;
}

function isCatInAlwaysChecked(catName) {
  catName = catName.trim();
  for (var i=0; i<catsAlwaysChecked.length; i++) {
    if (catsAlwaysChecked[i][0] == catName) { return true; }
  }
  return false;
}

function sg(oCb, cat, grpList) {
  // Thèmes d'un groupe  
  if(typeof(grpList) != "undefined") {
    var arrGrp = grpList.split(",");
    for (var i = 0; i < arrGrp.length; i++) {
      var oCbGrp = document.getElementById('ginput_'+arrGrp[i]);
      oCbGrp.checked = oCb.checked;      
      if (plusMinusChecbox) {
        var divobj = document.getElementById(arrGrp[i]);
        if ((oCb.checked && divobj.style.visibility != "visible") || (!oCb.checked && divobj.style.visibility != "hidden")) {     
          divobj.style.visibility == oCb.checked ? "hidden" : "visible";
          tg(arrGrp[i]);
        }      
      }
    }
  // Tous les Thèmes de tous les groupes
  } else {
    // On coche/décoche
    var cbxList = myGetElementsByName('groupscbx', 'INPUT');
    if (cbxList.length > 0) {
      for (var i=0; i<cbxList.length; i++) {
        if (oCb.checked == false) {
          var grpName = cbxList[i].id.substr(7); // id = "ginput_XXXXX"        
          if (isGrpInAlwaysChecked(grpName) == false) { cbxList[i].checked = oCb.checked; }                  
        } else {
          cbxList[i].checked = oCb.checked;
        }
      }
    }
    // On affiche/masque
    if(plusMinusChecbox) {   
      var grpcList = myGetElementsByName('grpc', 'DIV');
      if (grpcList.length > 0) {
        for (var i=0; i<grpcList.length; i++) {
          if((oCb.checked && grpcList[i].style.visibility != "visible") || (!oCb.checked && grpcList[i].style.visibility != "hidden")) {          
            if (oCb.checked == false) {
              if (isGrpInAlwaysChecked(grpcList[i].id) == false) {
                grpcList[i].style.visibility == "visible";
                tg(grpcList[i].id);            
              }                      
            } else {
              grpcList[i].style.visibility == "hidden";
              tg(grpcList[i].id);            
            }
          }
        }
      }
    }    
  }

  // Un groupe
  if(typeof(cat) != "undefined") {
    var divobj  = document.getElementById(cat);
    if((oCb.checked && divobj.style.visibility != "visible") || (!oCb.checked && divobj.style.visibility != "hidden")) {
      divobj.style.visibility == oCb.checked ? "hidden" : "visible";
      tg(cat);
    }
  // Tous les groupes  
  } else {
    // On coche/décoche
    var cbxList = myGetElementsByName('catscbx', 'INPUT');   
    if (cbxList.length > 0) {    
      for (var i=0; i<cbxList.length; i++) {
        if (oCb.checked == false) {
          var catName = cbxList[i].id.substr(7); // id = "ginput_XXXXX"        
          if (isCatInAlwaysChecked(catName) == false) { cbxList[i].checked = oCb.checked; }                  
        } else {
          cbxList[i].checked = oCb.checked;
        }
      }
    }
    // On affiche/masque
    if(plusMinusChecbox) {   
      var catcList = myGetElementsByName('catc', 'DIV');      
      if (catcList.length > 0) {
        for (var i=0; i<catcList.length; i++) {
          if((oCb.checked && catcList[i].style.visibility != "visible") || (!oCb.checked && catcList[i].style.visibility != "hidden")) {          
            if (oCb.checked == false) {           
              if (isCatInAlwaysChecked(catcList[i].id) == false) {
                catcList[i].style.visibility == "visible";
                tg(catcList[i].id);
              }                        
            } else {
              catcList[i].style.visibility == "hidden";
              tg(catcList[i].id);
            }
          }
        }
      }
    }
  }

  setlayers();
}

/**
 * Initialize TOC tree
 * attached as onLoad script to hidden image in legend/TOC
 */
function treeInit(catStyle, grpStyle) { 
    //alert('init');
    legendContainer.catStyle = catStyle;
    
    if (catStyle == 'tree') {
        if (document.all) {
            var divList = document.getElementsByTagName('div');
            var catcList = [];
            var grpcList = [];
    
            var c = 0;
            var g = 0;
            for (var d=0; d<divList.length; d++) {
                if (divList[d].name == 'catc') {
                    catcList[c] = divList[d];
                    c++;
                    //alert(divList[d].id);
                } else if (divList[d].name == 'grpc') {
                    grpcList[g] = divList[d];
                    g++;
                }
            }
        
        } else {
            var catcList = document.getElementsByName('catc');
            var grpcList = document.getElementsByName('grpc');
        }
        
        if (catcList.length > 0) {
            for (var i=0; i<catcList.length; i++) {  
                catcList[i].style.visibility='hidden';         
                tg(catcList[i].id);
            }
        } 

        if (grpStyle == 'tree') {
            if (grpcList.length > 0) {
                var cbxList = document.getElementsByName('groupscbx');
                for (var j=0; j<grpcList.length; j++) {
                    if (isCheckedGroup(cbxList[j].id)) {                                       
                      grpcList[j].style.visibility='hidden';  // hidden -> pour le passer en visible
                    } else {
                      grpcList[j].style.visibility='visible'; // visible -> pour le passer en hidden
                    }

                    tg(grpcList[j].id);
                }
            }
        }
        
        legendContainer.catcList = catcList;
        legendContainer.grpcList = grpcList;
        
    }
    
    // In case of reload from 'swapToLayerView()' reset active categories for Layer View
    if (legendContainer.catcListV) {
        resetLayerViewSettings();
    }
    
    resetCheckedGroups();
}    

function isCheckedGroup(GroupName) {
  if (legendContainer.checkedGrpList) {
      var checkedGrpList = legendContainer.checkedGrpList;
      for (var x=0; x<checkedGrpList.length; x++) {
        if (GroupName == checkedGrpList[x]) { return true; }
      }
  }
  return false;
}

/**
 * Sets popup legedn over map visible
 * attached as onClick script to button
 */
function showPopupLegend() {
    var tocurl = 'x_toc.php?' + SID + '&legendonly=1';
    showMapLegend(tocurl, ''); 
}


/**
 * for legStyle 'swap': swap from LAYER view to LEGEND view
 * attached as onClick script to button
 */
function swapToLegendView() {
    if (legendContainer.catStyle == 'tree') getActiveCats();
    var tocurl = 'x_toc.php?' + SID + '&legendonly=1&swaplegend=1';
    swapLegend(tocurl, ''); 
    
    getCheckedGroups();
}

/**
 * for legStyle 'swap': swap from LEGEND view to LAYER view
 * attached as onClick script to button
 */
function swapToLayerView() {
    var legDiv = document.getElementById('toclegend');
    //var tocDiv = document.getElementById('toc');
    var tocDiv = document.getElementById('tree');
    //legDiv.style.visibility = 'hidden';
    tocDiv.style.visibility = 'visible';
    tocDiv.innerHTML = legendContainer.legTxt;

    // update TOC CSS depending on scale
    var tocurl = 'x_toc_update.php?' + SID;
    updateTocScale(tocurl, '');
    
    //window.setTimeout("resetLayerViewSettings()", 200);
}

/**
 * for legStyle 'swap': when swapping back from LEGEND view to LAYER view:
 * reset settings for opened tree nodes
 */
function resetLayerViewSettings() {
    catcListV = legendContainer.catcListV;
    catcListH = legendContainer.catcListH;
    
    for (var v=0; v<catcListV.length; v++) {  
        document.getElementById(catcListV[v].id).style.visibility = 'hidden';
        tg(catcListV[v].id);
    }
    
    for (var h=0; h<catcListH.length; h++) {  
        document.getElementById(catcListH[h].id).style.visibility = 'visible';
        tg(catcListH[h].id);
    }
}

function resetCheckedGroups() {
    //alert(legendContainer.checkedGrpList);
    if (legendContainer.checkedGrpList) {
        var checkedGrpList = legendContainer.checkedGrpList;
        for (var x=0; x<checkedGrpList.length; x++) {
            document.getElementById(checkedGrpList[x]).checked = true;
        }
    }
}

/**
 * Get and set active (opened) categories
 * store arrays for visible and hidden category contents in object property 
 */
function getActiveCats() { 
    var catcList = legendContainer.catcList;
    
    var catcListV = [];
    var catcListH = [];
    var v = 0;
    var h = 0;
    
    for (var i=0; i<catcList.length; i++) {  
        if (catcList[i].style.visibility == 'visible') {
            catcListV[v] = catcList[i];
            v++;
        } else {
            catcListH[h] = catcList[i];
            h++;
        }
    }
    
    legendContainer.catcListV = catcListV;
    legendContainer.catcListH = catcListH;
}

function getCheckedGroups() {
    var checkedGrpList = [];
    var g = 0;
    var cbxList = document.getElementsByName('groupscbx');
    if (cbxList.length > 0) {
        for (var i=0; i<cbxList.length; i++) {
            if (cbxList[i].checked) {
                checkedGrpList[g] = cbxList[i].id;
                g++;
            }
        }
    }
    
    legendContainer.checkedGrpList = checkedGrpList;
}



function setDefGroups(groups) {


}




