var functions = new Array();
var ranges = new Array();
var documents = new Array();

function Function(id,libelle) {
  this.id = id;
  this.libelle = libelle;
}

function Range(id,libelle,idFunction) {
  this.id = id;
  this.libelle = libelle;
  this.idFunction = idFunction;
}

function Document(id,libelle,idFunction,idRange) {
  this.id = id;
  this.libelle = libelle;
  this.idFunction = idFunction;
  this.idRange = idRange;
}

function rangeActivation(indiceFunction,firstOptionLabel,errorLabel) {
  if (indiceFunction != '') {
    document.range_form.p_ranges.disabled = false;
  } else {
    document.range_form.p_ranges.disabled = true;
    document.range_form.p_ranges.options[0].selected = true;
  }
  document.document_form.p_documents.disabled = true;
  document.document_form.p_documents.options[0].selected = true;
  document.getElementById("submitButton").style.display = "none";
  document.getElementById("submitButtonHide").style.display = "inline";
  fillRangeList(indiceFunction,firstOptionLabel,errorLabel);
}

function legacyRangeActivation(indiceFunction,firstOptionLabel) {
  if (indiceFunction != '') {
    document.range_form.p_ranges.disabled = false;
  } else {
    document.range_form.p_ranges.disabled = true;
    document.range_form.p_ranges.options[0].selected = true;
  }
  document.getElementById("submitButton").style.display = "none";
  document.getElementById("submitButtonHide").style.display = "inline";
  fillRangeList(indiceFunction,firstOptionLabel);
  document.getElementById("document_legacy_message").innerHTML = "<p/>";
}

function documentActivation(indiceRange,indiceFunction,firstOptionLabel,isPrepControlActivated,usePrepLabel,errorLabel) {
  if (indiceRange != '' && indiceFunction != '') {
    document.document_form.p_documents.disabled = false;
  } else {
    document.document_form.p_documents.disabled = true;
    document.document_form.p_documents.options[0].selected = true;
  }
  document.getElementById("submitButton").style.display = "none";
  document.getElementById("submitButtonHide").style.display = "inline";
  fillDocumentList(indiceRange,indiceFunction,firstOptionLabel,isPrepControlActivated,usePrepLabel,errorLabel);
}

function formActivation(indiceDocument) {
  document.getElementById("submitButton").style.display = "none";
  document.getElementById("submitButtonHide").style.display = "inline";
  if (indiceDocument != '' && indiceDocument != 0) {
    document.getElementById("submitButton").style.display = "inline";
    document.getElementById("submitButtonHide").style.display = "none";
  }
}

function formLegacyActivation(indiceRange,contentTypes,isPrepControlActivated,errorLabel) {
  document.getElementById("submitButton").style.display = "none";
  document.getElementById("submitButtonHide").style.display = "inline";
  if (indiceRange != '' && indiceRange != 0) {
    if (isPrepControlActivated=='true' && hashMapAvailableContentTypeFromPrep!=null) {
      var tabContentsTypes = contentTypes.split(",");
      var numberOfContentType = 0;
      for (j=0;j<tabContentsTypes.length;j++) {
        if (hashMapAvailableContentTypeFromPrep.get(tabContentsTypes[j])!=null && hashMapAvailableContentTypeFromPrep.get(tabContentsTypes[j])!='') {
          numberOfContentType ++;
        }
      }
      if (numberOfContentType>0) {
        document.getElementById("submitButton").style.display = "inline";
        document.getElementById("submitButtonHide").style.display = "none";
        document.getElementById("document_legacy_message").innerHTML = "<p/>";
      } else {
        document.getElementById("submitButton").style.display = "none";
        document.getElementById("submitButtonHide").style.display = "inline";
        document.getElementById("document_legacy_message").innerHTML = "<p>"+errorLabel+"</p>";
      }
    } else {
      document.getElementById("submitButton").style.display = "inline";
      document.getElementById("submitButtonHide").style.display = "none";
      document.getElementById("document_legacy_message").innerHTML = "<p/>";
    }
  }
  else {
    document.getElementById("document_legacy_message").innerHTML = "<p/>";
  }
}

function fillFunctionList(firstOptionLabel) {
  var sel = document.function_form.p_functions;
  sel.options.length = 1;
  sel.options[0] = new Option( firstOptionLabel, 0 );
  for( i=0; i<functions.length; i++ ) {
    sel.options[sel.options.length] = new Option( functions[i].libelle , functions[i].id );
  }
}

function fillRangeList(indiceFunction,firstOptionLabel,errorLabel) {
  var sel = document.range_form.p_ranges;
  sel.options.length = 1;
  sel.options[0] = new Option( firstOptionLabel, 0 );
  for( i=0; i<ranges.length; i++ ) {
    if( indiceFunction != '' && ranges[i].idFunction == indiceFunction ) {
      sel.options[sel.options.length] = new Option( ranges[i].libelle, ranges[i].id );
    }
  }
  if( sel.options.length == 1) {
    sel.disabled = true;
  }
  if(document.document_form!=null) {
    var selDoc = document.document_form.p_documents;
    if(selDoc!=null) {
      selDoc.options.length = 1;
      selDoc.options[0] = new Option( firstOptionLabel, 0 );
    }
  }
}

function getAllContentTypesForASpecificRange(indiceRange,indiceFunction) {
  var hashMapContentTypes = {};
  hashMapContentTypes = {set : function(key,value) {this[key] = value;},get : function(key) {return this[key];}};
  var listeContentType = '';
  for( i=0; i<documents.length; i++ ) {
    if( indiceRange != '' && indiceFunction != '' && documents[i].idRange == indiceRange && documents[i].idFunction == indiceFunction) {
      var tabContentTypes = documents[i].id.split(",");
      for(j=0; j<tabContentTypes.length; j++) {
        if (hashMapContentTypes.get(tabContentTypes[j])!=tabContentTypes[j]) {
          listeContentType += tabContentTypes[j]+",";
          hashMapContentTypes[tabContentTypes[j]]=tabContentTypes[j];
        }
      }
    }
  }
  listeContentType = listeContentType.substr(0,listeContentType.length-1);
  return listeContentType;
}

function fillDocumentList(indiceRange,indiceFunction,firstOptionLabel,isPrepControlActivated,usePrepLabel,errorLabel) {
  var p_documents = document.getElementById("p_documents");
  while(p_documents.options.length != 0){
    p_documents.options[p_documents.options.length - 1] = null;
  }
  
  var hashMapContentTypes = {};
  hashMapContentTypes = {set : function(key,value) {this[key] = value;},get : function(key) {return this[key];}};
  var sel = document.document_form.p_documents;
  if (isPrepControlActivated == 'true' && hashMapAvailableContentTypeFromPrep != null) {
    sel.options.length = 1;
    sel.options[0] = new Option( firstOptionLabel, 0 );
    var compteurGlobal = 0;
    for( i=0; i<documents.length; i++ ) {
      if ( indiceRange != '' && indiceFunction != '' && documents[i].idRange == indiceRange && documents[i].idFunction == indiceFunction ) {
        var tabContentsTypes = documents[i].id.split(",");
        var numberOfContentType = 0;
        var idSelected = "";
        for (j=0;j<tabContentsTypes.length;j++) {
          if (hashMapContentTypes.get(tabContentsTypes[j])!=tabContentsTypes[j] && hashMapAvailableContentTypeFromPrep.get(tabContentsTypes[j])!=null && hashMapAvailableContentTypeFromPrep.get(tabContentsTypes[j])!='') {
            numberOfContentType ++;
            compteurGlobal ++;
            if (numberOfContentType == 1){
              idSelected = hashMapAvailableContentTypeFromPrep.get(tabContentsTypes[j]);
            }
            hashMapContentTypes.set(tabContentsTypes[j],tabContentsTypes[j]);
          }
        }
        if (numberOfContentType>0) {
          if (usePrepLabel=="true" && numberOfContentType==1) {
            sel.options[sel.options.length] = new Option( idSelected, documents[i].id );
          } else {
            sel.options[sel.options.length] = new Option( documents[i].libelle, documents[i].id );
          }
        }
      }
    }
    if( sel.options.length == 1){sel.disabled = true;}
    if (compteurGlobal == 0) {
      sel.options[0] = new Option( errorLabel, 0 );
      sel.disabled = true;
    }
  } else {
    sel.options.length = 1;
    sel.options[0] = new Option( firstOptionLabel, 0 );
    for( i=0; i<documents.length; i++ ) {
      if( indiceRange != '' && indiceFunction != '' && documents[i].idRange == indiceRange && documents[i].idFunction == indiceFunction ) {
        sel.options[sel.options.length] = new Option( documents[i].libelle, documents[i].id );
      }
    }
    if( sel.options.length == 1) {
      sel.disabled = true;
    }
  }
}

function getContentTypesFromResource(url)
{
  var sousChaine1Position = eval(url.indexOf("%26c=",0)+5);
  var sousChaine2Position = url.indexOf("~",0);
  var contentTypes = url.substring(sousChaine1Position,sousChaine2Position)
  return contentTypes;
}

function getXMLHttpRequest() {
  var xhr = null;
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
      }
    }
  } else {
    xhr = false;
  }
  return xhr;
}

function execute(urlServlet,urlPrep,idRange,idFunction,langue,firstOptionLabel,isPrepControlActivated,usePrepLabel,errorLabel) {
  xhrPrep = getXMLHttpRequest();
  hashMapAvailableContentTypeFromPrep = null;  
  xhrPrep.onreadystatechange = function () {
    handleHttpResponse();
    fillDocumentList(idRange,idFunction,firstOptionLabel,isPrepControlActivated,usePrepLabel,errorLabel);
  }
  xhrPrep.open("GET", urlServlet+replaceByHexadecimalValue(urlPrep)+"%26p="+idRange+"%26c="+getAllContentTypesForASpecificRange(idRange,idFunction)+"%26L="+langue, true);
  xhrPrep.send(null);
  return true;
}

function executeLegacy(urlServlet,urlPrep,idRange,langue,contentTypes,isPrepControlActivated,errorLabel) {
  xhrPrep = getXMLHttpRequest();
  hashMapAvailableContentTypeFromPrep = null;
  xhrPrep.open("GET", urlServlet+replaceByHexadecimalValue(urlPrep)+"%26p="+idRange+"%26c="+contentTypes+"%26L="+langue, true);
  xhrPrep.send('');
  xhrPrep.onreadystatechange = function () {
    handleHttpResponse();
    formLegacyActivation(idRange,contentTypes,isPrepControlActivated,errorLabel);
  }
  return true;
}

function nodeCleaner(n) {
  if(!n.data.replace(/\s/g,'')) n.parentNode.removeChild(n);
}

function cleanXML(docElement) {
  var node = docElement.getElementsByTagName('*');
  for(i = 0; i < node.length; i++) {
    a = node[i].previousSibling;
    if (a && a.nodeType == 3) {
      nodeCleaner(a);
    }
    b = node[i].nextSibling;
    if (b && b.nodeType == 3) {
      nodeCleaner(b);
    }
  }
  return docElement;
}

function handleHttpResponse() {
  if (xhrPrep.readyState == 4 && xhrPrep.status == 200) {
    response = xhrPrep.responseXML.documentElement;
    if(response != null) {
      response = cleanXML(xhrPrep.responseXML.documentElement);
      hashMapAvailableContentTypeFromPrep = getAvailableDocumentsTypes(response);
    }
  }
}

function displayResult(response) {
  var html = '';
  var rangeId = response.getElementsByTagName("range_id").item(0).firstChild.nodeValue;
  var rangeContainsDoc = response.getElementsByTagName("contains_doc").item(0).firstChild.nodeValue;
  var contentTypeItems = response.getElementsByTagName("content_type");
  html += '<h1>Range (id: '+rangeId+', contains_doc: '+rangeContainsDoc+')</h1>';
  for(i = 0; i < contentTypeItems.length; i++) {
    var contentTypeId = contentTypeItems.item(i).getElementsByTagName("id").item(0).firstChild.nodeValue;
    var contentTypeTitle = contentTypeItems.item(i).getElementsByTagName("title").item(0).firstChild.nodeValue;
    var contentTypeContainsDoc = contentTypeItems.item(i).getElementsByTagName("contains_doc").item(0).firstChild.nodeValue;
    html += '<p>content type (id: '+contentTypeId+',title: '+contentTypeTitle+', contains_doc: '+contentTypeContainsDoc+'</p>';
  }
  document.getElementById('content').innerHTML = html;
}

function getAvailableDocumentsTypes(response) {
  var hashMap = {set : function(key,value) {this[key] = value;},get : function(key) {return this[key];}};
  var tab = response.getElementsByTagName("contains_doc");
  var rangeContainsDoc = 0;
  for (i = 0; i < tab.length; i++) {
    if (tab[i].parentNode.tagName=="check_content") {
      rangeContainsDoc = tab[i].firstChild.nodeValue;
    }
  }
  if (rangeContainsDoc == 1) {
       var contentTypeItems = response.getElementsByTagName("content_type");
    for(i = 0; i < contentTypeItems.length; i++) {
      var contentTypeId = getNodeValue(contentTypeItems.item(i).getElementsByTagName("id").item(0));
      var contentTypeTitle = getNodeValue(contentTypeItems.item(i).getElementsByTagName("title").item(0));
      var contentTypeContainsDoc = getNodeValue(contentTypeItems.item(i).getElementsByTagName("contains_doc").item(0));
      if (contentTypeContainsDoc == 1 && contentTypeId!='') {
        hashMap.set(contentTypeId,contentTypeTitle);
      }
    }
  }
  return hashMap;
}

function getNodeValue(node) {
  var value = '';
  if (node != null && node.hasChildNodes()) {
    value = node.firstChild.nodeValue;
  }
  return value;
}

function replaceByHexadecimalValue(param) {
  param = param.replace("?","%3F","g");
  param = param.replace("&","%26","g");
  return param;
}
