/*
  Trefferanzeige der Metasuche
  Datei: navi.js
  Autor: M.Schönbeck
  Anmerkung: Dieses Skript erfordert den Zugriff auf die jQuery-Bibliothek
*/
var dbg= false;  // Debuginformationen ausgeben
var req;
var versuche= 10;
var sStatus = "";
var timeout_s = 20000;
var allhits = 0;
var checkedItems = null; // dieses Array wird in template.createcluster initialisiert
var timer = null;
var allChecked = true;  

function clearSubjectNodes (nodeItems) {
  $.each(nodeItems, function (idx, item) {
    var rxp = /(\d+)\.(\d)+/;
    var a = rxp.exec(item.sid);
    if (a == null) {
      return;
    }
    var fcid = "cid_"+a[0];
    var node = document.getElementById (fcid);
    if (node != null) {
      var txtNode = document.createTextNode ("   ");
      if (node.firstChild != null) {
        node.replaceChild (txtNode, node.firstChild);
      }
      else  {
        node.appendChild (txtNode);
      }
    }
  });
}

function findCheckedItemSid (sid) {
  var rxp = /\d+\.(\d+\.\d+)/;
  var ret = -1;
  $.each(checkedItems, function (idx, item) {
    var pcid = rxp.exec(item["sid"])[1];
    if (pcid == sid) {
      ret = idx;
    }
  })
  return ret;
}

function getNodeValue (dom, path) {
  var elem = dom.find (path);
  if (elem.length > 0)
    return (elem[0].firstChild.data);
  else
    return "nil";
}

function mapDbItems () {
  $.ajax({
    type: "get",
    url: "/vascoda",
    data: "SERVICE=TEMPLATE&SUBSERVICE=GETHITCOUNT&REQID="+req.reqid+"&SID="+req.sid+"&INFOTYP=1",
    complete: function(resp){
      var xml = resp.responseXML;
      var sdDOM = jQuery(resp.responseXML);
      var subjects =  sdDOM.find ("/sd/subject");
      /* Iteration ueber Faecher */
      $.each( subjects, function(idx, subject){
        var sid= subject.attributes[0].nodeValue;
        var sbj= jQuery(subject);
        var entries= sbj.find("entry");
        /* Iteration ueber Portale */
        $.each (entries, function (i, entry){
          var pid= entry.attributes[0].nodeValue;
          if (entry.attributes.length > 1) {
            var cidx = findCheckedItemSid (sid+"."+pid);
            if (cidx > 0) {
              checkedItems[cidx].msid = entry.attributes[1].nodeValue;
            }
          }
        });
      })
      updateHitcount();
    }
  })
}

function showHitInfo (id, hits, incr) {
  var node = document.getElementById (id);
  if (node == null)
    return;
  var v = null;
  var s ="";
  var anode = document.getElementById ("a_"+id);
  if (anode != null) {
    var v = anode.getAttributeNode("title").value;
    s = jQuery.trim(v);
  }
  var h = hits;
  if (isNaN(parseInt(h)) && s.length != 0 && s.match(/[\.]+/) != "...")
    return;
  if (incr == true) {
    var myhits = parseInt(s);
    if (myhits) {
      h += myhits;
    }
  }
  if (isNaN (h) || h == 0) 
    return;
  var mya_elem = document.createElement("a");
  var mya_attr = document.createAttribute ("title");
  if (id.split(".").length > 2) // Portal
    mya_attr.nodeValue = "Mindestens "+h+" weitere Treffer finden Sie direkt in diesem Fachportal";
  else // Fach
    mya_attr.nodeValue = "Mindestens "+h+" weitere Treffer finden Sie in zugeordneten Fachportalen"; 
  mya_elem.setAttributeNode (mya_attr);
  var myid_attr = document.createAttribute ("id");
  myid_attr.nodeValue = "a_"+id;
  mya_elem.setAttributeNode (myid_attr);

  var txtNode = document.createTextNode ("*"); /* ehemals document.createTextNode (h) */
  mya_elem.appendChild (txtNode);

  if (node.firstChild != null)
    node.replaceChild (mya_elem, node.firstChild);
  else
    node.appendChild (mya_elem);
}

function updateHitNode (id, hits, incr) {
  var node = document.getElementById (id);
  if (node == null)
    return;
  var s = $.trim(node.innerHTML);
  var h = hits;
  if (isNaN(parseInt(h)) && s.length != 0 && s != "...")
    return;
  if (incr == true) {
    var myhits = parseInt(s);
    if (myhits) {
      h += myhits;
    }
  }
  var txtNode = document.createTextNode (h);
  if (node.firstChild != null)
    node.replaceChild (txtNode, node.firstChild);
  else
    node.appendChild (txtNode);
 }

function updateHitcount () {
  var total = 0;
  clearSubjectNodes (checkedItems); // Ist checkedItems wirklich gefuellt? jan 20071124
  $.ajax({
    type: "get",
    url: "/vascoda",
    data: "SERVICE=TEMPLATE&SUBSERVICE=GETHITCOUNT&REQID="+req.reqid+"&SID="+req.sid+"&INFOTYP=0",
    complete: function(resp){
      var xml = resp.responseXML;
      var myDOM = jQuery(resp.responseXML);
      var databases = myDOM.find("/REQ/DB");
      var hitsDb= "...";
      updateHitNodes (checkedItems, hitsDb);
      if (getNodeValue (myDOM, "/REQ/STATE") == "DONE") {
        versuche = 0;
      }
      $.each( databases, function(idx, dbitem){
        var iDOM = jQuery (dbitem);
        if (getNodeValue (iDOM, "STATE") == "DONE") {
          var error = getNodeValue (iDOM, "ERRORCODE");
          switch (error) {
            case "505":
              hitsDb = 0;
              break;
            case "0":
              hitsDb = Number(getNodeValue (iDOM, "HIT_COUNT"));
              break;
            default:
              hitsDb= "?";
          }
          // Relation von msid und sid der "angehakten" Datenbanken ermitteln
          var nodeItems = $.grep(checkedItems, function(item, n){
            return item.msid == dbitem.attributes[0].nodeValue;
          });
          updateHitNodes (nodeItems, hitsDb);
          // Gesamttreffer
          var f = true;
          $.each (nodeItems, function(idx, item){
            if (f && !isNaN(hitsDb) && item.msid == dbitem.attributes[0].nodeValue) {
              total += hitsDb;
              // jedes Portal darf in der Gesamtsumme nur einmal beruecksichtigt werden
              f = false;
            }
          })
        }
      })
      // HACK ; von der Fachportal-Seite zurueck zur Trefferliste wurde total immer auf 0 gesetzt ; jan 20071124
      totalHits = getNodeValue (myDOM, "/REQ/TOTALHITS");
      if ( totalHits > total )
         total = totalHits;
      showInfo (total);
    }
  })
}

function pushCheckedItem (sid, cbx) {
  var obj = new Object();
  obj.sid  = sid;
  obj.msid  = null;
  obj.cbx = cbx;
  checkedItems.push (obj);
}

function displaySubtrees ()
{
  var ret=false;
  if (allChecked || checkedItems == null) 
    return;
  var lastid;
  var lasttableid;
  $.each(checkedItems, function (idx, item) {
    if (!ret) {
      var tbody=item.cbx.parentNode.parentNode.parentNode;
      $(tbody).removeClass('none');
      $(tbody).addClass('active');
      $(tbody).show();
      var table = item.cbx.parentNode.parentNode.parentNode.parentNode;
      $(table).addClass('active');
/*      $(table).parentNode.addClass('active');*/
      var cbxid = item.cbx.getAttribute("id");
      if (cbxid) {
        var s= cbxid.slice(0, 8);
        if (s!= lastid) {
          $('.'+s).show();
          var a = $('#b_'+s);
          a[0].title = 'zuklappen';
          $("img:first", a[0]).remove();
          var btn = new Image; btn.src = '/Vascoda/images/icon_form_hide.gif';
          a[0].appendChild (btn);
          LeftNavigation.NodeExpanded[a[0].id.replace(/^b_/,'')] = 1;
          var tid = '#b_'+s.slice(0, 5)+'_all';
          if (lasttableid != tid) {
            a= $(tid);
            a[0].title = 'zuklappen';
            lastid =s;
            $("img:first", a[0]).remove();
            var btn = new Image; btn.src = '/Vascoda/images/icon_form_hide.gif';
            a[0].appendChild (btn);
            LeftNavigation.NodeExpanded[a[0].id.replace(/^b_/,'')] = 1;
            lasttableid = tid;
          }
        }
      }
    }
  })
  return;
}

function pushCheckedItems () {
  debug("pushCheckedItems (): "+getTimeStamp());
  if (checkedItems != null)
    return;
  checkedItems = new Array ();
  var choice = document.getElementById ("choice");
  if (choice == null)
      return;
  var myChoice = jQuery(choice);
  var inp = myChoice.find("input");
  $.each( inp, function(idx, cbx){
    if (cbx.value.match(/\d+\.\d+\.\d+/)) {
      if(cbx.checked)
        pushCheckedItem (cbx.value, cbx);
      else 
        allChecked = false;
    }
  })
}

function showInfo (hits) {
  var sMsg = "";
  var txtnode = null;
  var hitnode= document.getElementById("allhits");
  var infonode= document.getElementById("mssearch_info");
  var msHits = $("#hits_from_ms");
  var info = $("#mssearch_info");
  if (timer != null) {
    window.clearTimeout(timer);
  }
  if (info.length == 0 || hits == null)
    return;


  // das Element ist noch nicht vorhanden, weil die Suchmaschine schneller war als die Metasuche
  if (msHits.length == 0) {
    var html= "<span class='fett'>*</span>&nbsp;<span id='hits_from_ms'>"+hits+"</span> "+_Vascoda_1003+".";
    if (hits > 0) {
//      html= "<a href='/"+req.base+"?SERVICE=TEMPLATE&amp;SUBSERVICE=FACHPORTALE&amp;SID="+req.sid+"&amp;MS_REQID="+req.reqid+"'><span id='hits_from_ms'>"+hits+"</span> weitere Treffer können nur direkt in den Fachportalen angezeigt werden.</a>";
        html = '<a href="' + jQuery('#fpHref').attr('class') + '">' + html + '</a>';
    }
    $('#totalMSHits').append(html);
  }
  else
    updateHitNode ("hits_from_ms", hits);
/* die Anzeige der Gesamttreffer soll nach den Vorgaben der Gescaeftsstelle nun entfallen
  if (allhits == 0)
    allhits = parseInt(hitnode.firstChild.nodeValue);
  hits = parseInt(hits); // Sicher ist Sicher; jan 20071124
  var h = allhits+hits;
  if (!isNaN (h)) {
    txtnode=document.createTextNode(h);
    hitnode.replaceChild(txtnode, hitnode.firstChild);
  }
*/
 info.empty();
 if (versuche <= 0 ) {
    //sMsg = _Vascoda_1005;
    //info.append(sMsg);
    updateHitNodes (checkedItems, " ");
  }
  else {
    sStatus = sStatus + "." ;
    var html="<img src='/Vascoda/images/ajax-loader.gif' alt='"+_Vascoda_1004+sStatus+"' title='"+_Vascoda_1004+sStatus+"' />";
    info.append(html);
    debug ("versuche= "+versuche);
    updateHitNodes (checkedItems, "...");
    --versuche;
    timer = window.setTimeout("updateHitcount()", timeout_s);
  }
}

function sprintf(num,size,pre) {
  pre=(pre)?pre:"0";
  var sign=(num<0)?"-":"";
  var rslt=(pre=="0")?sign:"";
  num=Math.abs(parseInt(num,10));
  size-=(""+num).length;
  for(var i=1;i<=size;i++) {
    rslt+=""+pre;
  }
  rslt+=((pre!="0")?sign:"")+num;
  return rslt;
}

function updateHitNodes (nodeItems, hits) {
  $.each(nodeItems, function (idx, item) {
    var ccid= "cid_"+item.sid;
    showHitInfo (ccid, hits, false); 
    if (!isNaN(parseInt(hits))) {
      var rxp = /(\d+)\.(\d)+/;
      var a = rxp.exec(item.sid);
      if (a == null) {
        return;
      }
      var fcid = "cid_"+a[0];
      // Treffer fuer Faecher aufsummieren
      showHitInfo (fcid, hits, true);
//      updateHitNode (fcid, hits, true);
    }
  });
}


/* *********  zum debuggen:  *************
*/


function debug (sVal) {
  if (!dbg)
    return;
  if ($("#debug").length == 0)
    $("<div id='debug'></div>").insertBefore("#mssearch_info");
  $("#debug").append(sVal).append("<br/>");
}

function getTimeStamp () {
  var date = new Date();
  var ts = date.getHours ()+":"+date.getMinutes()+":"+date.getSeconds()+":"+ date.getMilliseconds();
  return ts;
}


