var ie           = false;
var ie6          = false;
var ie7          = false;
var ie8          = false;
var ff           = false;
var ff_ver       = 0;
var op           = false;
var op_ver       = 0;
var css          = false;
var svg          = null;
var ufzhost      = "";  // wird nicht mehr benötigt
var logoId       = "ufzlogosvg";
var svgId        = "";
var contrast     = "off";
var percent      = 95;
var fs_start     = 15.2;
var pixel        = 15.2;
var printer      = false;
var language     = "de";
var toolbar_svg  = new Array();
var logoPath     = "";
var bmpLogo      = "";
var bmpLogoBW    = "";
var bmpLogoWB    = "";

var logoColorsBW = new Array('black', 'white');
var logoColorsWB = new Array('white', 'black');

var toolbarColorsBW = new Array('black', 'white');
var toolbarColorsWB = new Array('white', 'black');

// +++++++++++++++++++++ mainscript +++++++++++++++++++++
window.onload   = init;
window.onunload = setCookie;
window.onresize = checkScrolling;

checkEnv();
setValues();
headContent();

function init()  {
  bodyContent(); 
  
  svg = (null != initSVG("ufzlogosvg") || true == isASVInstalled()) ? true : false;

  setContrast();

  if(ff && !document.cookie)  {
    var temp = document.defaultView.getComputedStyle(document.body,'').getPropertyValue('font-size');
    fs_start = temp.substr(0, temp.length - 2);
    pixel = fs_start;
  }

  setFontSize();    
  checkScrolling();
  correctRightLine();

  /* ErrorCatcher - muss am Ende stehen! */
  if(location.search.match('debug=')) {
    ec_sendErr('');
  }
  /* EC ENDE */
}
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++

function checkEnv()  {
  ie  = /MSIE/.test(navigator.userAgent)    ? true : false;
  ie6 = /MSIE 6/.test(navigator.userAgent)  ? true : false;  
  ie7 = /MSIE 7/.test(navigator.userAgent)  ? true : false;   
  ie8 = /MSIE 8/.test(navigator.userAgent)  ? true : false;
  ff  = /Firefox/.test(navigator.userAgent) ? true : false;
  op  = /Opera/.test(navigator.userAgent)   ? true : false;    
    
  printer  = /action=print/.test(document.URL) ? true : false;

  css = !document.getElementsByTagName("link")[0].disabled;
  
  language = /en=|es=|fr=/.test(document.URL) ? "en" : "de";

  ufzhost = /intern/.test(document.URL) ? "www.intern"
                                        : /webdev/.test(document.URL)
                                        ? "webdev.leipzig"
                                        : "www";
  ufzhost = window.location.protocol + "//" + ufzhost + ".ufz.de/";
}

function setValues()  {
  if(document.cookie)  {                                  // wenn Cookie vorhanden dann  
    contrast = getCookie()[0] != "undefined"              // falls im Cookie "undefined" steht auf Standardwerte setzen
            && typeof(getCookie()[0]) != "undefined" 
             ? getCookie()[0] : "off";                    // oder Wert aus Cookie setzen
   
     percent = getCookie()[1] != "undefined"
            && typeof(getCookie()[1]) != "undefined"
             ? getCookie()[1] : 95; 
         
       pixel = getCookie()[2] != "undefined"
            && typeof(getCookie()[2]) != "undefined"
             ? getCookie()[2] : 15.2; 
     
    fs_start = getCookie()[3] != "undefined"
            && typeof(getCookie()[3]) != "undefined"
             ? getCookie()[3] : 15.2;                                         
  }

  bmpLogo   = language == "de" ? bmpLogoDE   : bmpLogoEN;
  bmpLogoBW = language == "de" ? bmpLogoBWDE : bmpLogoBWEN;
  bmpLogoWB = language == "de" ? bmpLogoWBDE : bmpLogoWBEN;
}

var cu_sheet, bw_sheet, wb_sheet;  // globales Objekte fuer Kontrast-StyleSheets deklarieren
function headContent()  {          // fuegt CSS-Link fuer contrast.css ein (wird nur bei JS-enabled gebraucht)                             
  var style = '';

  style = (contrast == "off") ? custom_style : ''; 
  createCSSHeaderTag(style, 'cu_style');
  cu_sheet = document.getElementById('cu_style');

  style = (contrast == "wb") ? "/data/whiteblack_web_1.css" : '';  
  createCSSHeaderTag(style, 'wb_style');
  wb_sheet = document.getElementById('wb_style');

  style = (contrast == "bw") ? "/data/blackwhite_web_1.css" : '';
  createCSSHeaderTag(style, 'bw_style');
  bw_sheet = document.getElementById('bw_style');
}

function getContent()  {
  return document.URL + "&&false&&true";
}
 
function bodyContent()  {  // fuegt den nur bei JS-enabled benoetigten Content ein                                                    

  setEvents();

  if(document.getElementById("breadcrumb"))  {  
           toolbar_svg  =     Array(
                                    '/data/6189.svg',
                                    '/data/9359.svg',
			            '/data/6190.svg',
                                    '/data/6191.svg',
                                    '/data/6192.svg',
                                    '/data/6193.svg',
                                    '/data/6194.svg'
                                   );                                                                

       var toolbar_href = new Array(
                                    "javascript: onPrint();",
                                    "javascript: createPDF(getContent());",
                                    "javascript: javascript: help();",
                                    "javascript: changeFontSize('smaller');",
                                    "javascript: changeFontSize('reset');",                               
                                    "javascript: changeFontSize('bigger');",
                                    "javascript: changeContrast();"
                                   );                                                                    

       var toolbar_keys = new Array(
                                    '',
                                    '',
                                    '',
                                    '',
                                    '',                               
                                    '',
                                    ''
                                   );

  if(ie && navigator.platform == "Win32")  {
	   var toolbar_keys = new Array(
                                    '[Alt+0 Enter]',
                                    '[Alt+1 Enter]',
                                    '[Alt+2 Enter]',
                                    '[Alt+3 Enter]',
                                    '[Alt+4 Enter]',                               
                                    '[Alt+5 Enter]',
                                    '[Alt+6 Enter]'
                                   );												
  }
  else if(ff && navigator.platform == "Win32")  {
	   var toolbar_keys = new Array(
                                    '[Alt+Shift+0]',
                                    '[Alt+Shift+1]',
                                    '[Alt+Shift+2]',
                                    '[Alt+Shift+3]',
                                    '[Alt+Shift+4]',                               
                                    '[Alt+Shift+5]',
                                    '[Alt+Shift+6]'
                                   );	  
  }
												
    if(language == "de")  {
	  var toolbar_title = new Array(
                                    'Seiteninhalt drucken',
                                    'Seiteninhalt in PDF umwandeln',
                                    'allgemeine Hilfe anzeigen',
                                    'Schriften verkleinern',
                                    'Schriftgrößen zurücksetzen',                               
                                    'Schriften vergrößern',
                                    'Kontrast umschalten'
                                   );
	 }
	 else  {
	  var toolbar_title = new Array('Print page content',
                                    'Convert content to PDF',
                                    'Show common help',
                                    'Reduce fontsize',
                                    'Reset fontsize',                               
                                    'Expand fontsize',
                                    'Change contrast'
                                   );	 
	 }                                                                   
  
    var toolbar_ul =  document.createElement("ul");  // ul fuer Toolbar in breadcrumb einfuegen
    toolbar_ul.id = "toolbar";
    document.getElementById("breadcrumb").appendChild(toolbar_ul);
  
    // letzten tabindex aus breadcrumb holen und inkrementieren
    /.*tabindex="(.+?)"/g.exec(document.getElementById('breadcrumb').innerHTML.replace(/\s/g, ""));
    var last_tab = RegExp.$1 ? parseInt(RegExp.$1) + 1 : 14;
  
    for(var i = 0; i < toolbar_svg.length; i++)  {     
      var imgId = toolbar_svg[i].split("\/").pop().split("\.")[0];
      
		var toolbar_li = document.createElement("li");
      with(toolbar_li)  {
        title = unescape(toolbar_title[i]) + " " + toolbar_keys[i];
		 
        if(svg == 5)  {              
          innerHTML = "<a href=\"" + toolbar_href[i] + "\"" +
			             "onmouseout= \"if(typeof(fillSVG) == 'function') fillSVG('" + imgId + "', Array('', 'White'))\"" +
			             "onmouseover=\"if(typeof(fillSVG) == 'function') fillSVG('" + imgId + "', Array('', 'Gray'))\"" +
							 "tabindex=\"" + (++last_tab) + "\" accesskey=\"" + i + "\"></a>" + 
				          "<object data=\"" + toolbar_svg[i] + "\" type=\"image/svg+xml\" width=\"24\" height=\"24\" id=\"" + imgId + "\">" + 
							 "<param name=\"src\" value=\"" + toolbar_svg[i] + "\" />" +
							 "<param name=\"wmode\" value=\"transparent\" />" +
							 "</object>";
        }
        else  {
          innerHTML = "<a href=\"" + toolbar_href[i] + "\" tabindex=\"" + (++last_tab) + "\" accesskey=\"" + i + "\">" + 
				          "<img src=\"" + toolbar_png[i] + "\" onmouseover=\"this.src='" + hover_png[i] + "'\" onmouseout=\"this.src='" + toolbar_png[i] + "'\"" +
			      		 "width=\"24\" height=\"24\" alt=\"" + toolbar_title[i] + " " + toolbar_keys[i] + "\" /></a>";  
        }
		}  
		
      if(typeof(helpId) != "undefined")          
        document.getElementById("toolbar").appendChild(toolbar_li);
    }    
  }
}
function setEvents()  {
  if(document.getElementById("search"))  {
    with(document.getElementById("search"))  {
      if(ie)  {
        eval("onclick = function() { if (value == 'Suchbegriff' || value == 'keyword') this.value=''; }");            
      }
      else  {
        setAttribute("onclick", "if (value == 'Suchbegriff' || value == 'keyword') this.value=''");
      }  
    }
  }
}

function onPrint()  {
  var tmp = "&amp;action=print&amp;contrast=" + contrast;
  var param = /\?/.test(document.URL) ? tmp : "?" + tmp;
  var fenster = window.open(this.location + param, "", "scrollbars=yes, width=1024, height=768, left=0, top=0");
  fenster.focus();
}
function prepareForPrint()  {

  // print.css ausschalten
  //if($("printstyle"))
    //$("printstyle").href = "dummy.css";
  
  // auszublendende Elemente definieren
  var tmp;
  var objects = new Array("titleline", "colwhit", "colblue", "colopac", "topline",
                          "mainmenu", "submenu", "languages", "titlenav","bottomline",
                          "searchbox", "searchline", "toolbar", "footer");  
                   
  // Elemente ausblenden                
  for(var i = 0; i < objects.length; i++)  {
    tmp = document.getElementById(objects[i]);
    if(tmp)
      tmp.style.display = "none";
  }

  var objects = new Array("main", "title");    
  for(var i = 0; i < objects.length; i++)  {
    tmp = document.getElementById(objects[i]);
    if(tmp)
      tmp.style.backgroundImage = "none";
  }
   
  // Titel umbauen 							
  $("wrapper").style.background = "none";   // blendet erste gestrichelte Linie aus
  $("content").style.left = "-2%";          // damit content in einer Linie ist
  $("content").style.width = "90%";
  $("main").style.background = "none";      // blendet zweite gestrichelte Linie aus
  $("main").style.border = "none";          // blendet seitliche Linien aus
  $("svglogo").style.marginLeft = "70%";
  $("titletext").style.marginTop = "0";     // Kein Abstand zwischen Titel und oberem Rand
  $("titletext").style.marginRight = "35%";
  $("titletext").style.paddingTop = "30px"; // Text vertikal mittig
  $("breadcrumb").style.paddingLeft = "0";
  $("column").style.display = "none";

  // verhindert das eine Seite zuviel gedruckt wird
  if(ff)
    document.documentElement.style.height = "1%";

  // Kontrast übernehmen und verhindern dass Weiss auf Schwarz gedruckt wird
  var param = location.search.split("contrast=")[1];  
  contrast = param != "wb" ? param : "bw";
}

function help()  {
  location.href = !/:8080/.test(document.URL) ? "/index.php?de=" + helpId : "../hilfe.htm";
}

function changeContrast()  {  // Kontrast-Modi aendern (off -> bw -> wb -> off)
  switch(contrast)  {
    case "off":
      contrast = "bw";
    break;  
    case "bw":
      contrast = "wb";
    break;  
    case "wb":
      contrast = "off";
    break;    
    default:
      contrast = "off";
    break;
  }
  setContrast();
}

function setContrast()  {

  if(printer)
    prepareForPrint();
  
  switch(contrast)  {
    case "off":
      if(!cu_sheet.href) cu_sheet.setAttribute("href", custom_style);
      wb_sheet.disabled = true;
      bw_sheet.disabled = true;
             
      if(svg)  {
        fillSVG_neu("ufzlogosvg", Array(''));
        fillSVG_neu("obj12466",   Array(''));
        fillSVG_neu("obj12665",   Array(''));
        fillSVG_neu("obj12464",   Array(''));
        fillSVG_neu("obj12463",   Array(''));

        //toolbar
        fillSVG_neu('6189', Array(''));
        fillSVG_neu('9359', Array(''));
        fillSVG_neu('6190', Array(''));
        fillSVG_neu('6191', Array(''));
        fillSVG_neu('6192', Array(''));
        fillSVG_neu('6193', Array(''));
        fillSVG_neu('6194', Array(''));
      }
      else
        document.getElementById('ufzlogoimg').src = bmpLogo;
    break;
  
    case "bw":
      if(!bw_sheet.href) bw_sheet.setAttribute("href", "/data/blackwhite_web_1.css");  
      wb_sheet.disabled = true;  
      bw_sheet.disabled = false;

      if(svg)  {
        fillSVG_neu('ufzlogosvg', logoColorsBW);
        fillSVG_neu("obj12466", Array('black'));
        fillSVG_neu("obj12665", Array('black'));
        fillSVG_neu("obj12464", Array('black'));
        fillSVG_neu("obj12463", Array('black', 'black', 'black', 'white'));

        //toolbar
        fillSVG_neu('6189', toolbarColorsBW);
        fillSVG_neu('9359', toolbarColorsBW);
        fillSVG_neu('6190', toolbarColorsBW);
        fillSVG_neu('6191', toolbarColorsBW);
        fillSVG_neu('6192', toolbarColorsBW);
        fillSVG_neu('6193', toolbarColorsBW);
        fillSVG_neu('6194', toolbarColorsBW);
      }
      else
        document.getElementById('ufzlogoimg').src = bmpLogoBW;                                                                                                                                                    
    break;
  
    case "wb":
      if(!wb_sheet.href) wb_sheet.setAttribute("href", "/data/whiteblack_web_1.css");
      wb_sheet.disabled = false;
      bw_sheet.disabled = true;

      if(svg)  {      
        fillSVG_neu('ufzlogosvg', logoColorsWB);
        fillSVG_neu("obj12466", Array('white', 'black'));
        fillSVG_neu("obj12665", Array('white', 'black'));
        fillSVG_neu("obj12464", Array('white', 'black'));
        fillSVG_neu("obj12463", Array('white', 'white', 'white', 'black'));

        //toolbar
        fillSVG_neu('6189', toolbarColorsWB);
        fillSVG_neu('9359', toolbarColorsWB);
        fillSVG_neu('6190', toolbarColorsWB);
        fillSVG_neu('6191', toolbarColorsWB);
        fillSVG_neu('6192', toolbarColorsWB);
        fillSVG_neu('6193', toolbarColorsWB);
        fillSVG_neu('6194', toolbarColorsWB);
      }
      else
        document.getElementById('ufzlogoimg').src = bmpLogoWB;         
    break;
  }

  if(printer)  {
    printer = false;
    window.setTimeout("window.print()", 1000);
  }
}

function fillToolbarSVG(colors)  {
  for(var i = 0; i < toolbar_svg.length; i++)  {
    var imgId = toolbar_svg[i].split("\/").pop().split("\.")[0];
    fillSVG(imgId, colors);
  }  
}

var last_action;                                              // globale Variable fuer letzte Aktion deklarieren
function changeFontSize(action)  {
  if(action != "reset")  {                                    // wenn nicht Schriftgroesse zuruecksetzen geklickt wurde
    var op = action == "bigger" ? "+" : "-";                  // Operator bestimmen
    if(document.defaultView)  {                               // fuer Firefox & Co.
      // aktuelle Schriftgroesse (px) im Firefox ermitteln - Dank an Thomas Lange
      var temp = parseInt(document.defaultView.getComputedStyle(document.body,'').getPropertyValue('font-size'));
      if(temp > 9 && temp < 29 || action != last_action)  {      
        pixel = eval(temp + op + 1);           // Quelle: http://aktuell.de.selfhtml.org/weblog/schriftgroesse
      } 
    }
    else if(document.body.currentStyle)  {                    // fuer IE
      // aktuelle Schriftgroesse (%) im IE ermitteln
      var temp = parseInt(document.body.currentStyle.fontSize);
      if(temp > 65 && temp < 180 || action != last_action)  {
        percent = eval(temp + op + 5);                        // Schriftgroesse um 5% aendern (je nach Operator)
      }
    }
  }
  else  {
    percent = 95;
    
    pixel = parseInt(pixel);
    pixel = pixel > fs_start ? pixel - Math.abs(fs_start - pixel)
                             : pixel + Math.abs(fs_start - pixel);  // bei Reset wieder auf urspruengliche Schriftgroesse setzen
  }
  setFontSize();                                                    // ermittelte Schriftgroesse setzen
  last_action = action;                                             // letzte Aktion merken (z.B. bigger)
}

function setFontSize()  {
  if(document.body.currentStyle) {
    if(isNaN(percent)) percent = parseInt(percent);
    if(isNaN(percent)) percent = 95;
  
    document.body.style.fontSize =  percent + "%";
  } 

  if(document.defaultView)  {
    if(isNaN(pixel)) pixel = parseInt(pixel);
    if(isNaN(pixel)) pixel = 15.2;

    document.body.style.fontSize = pixel + "px";
  }
}

function setCookie()  {
  var year    = 1000 * 60 * 60 * 24 * 365;
  var now     = new Date();
  var expires = new Date(now.getTime() + year);

  document.cookie = "UFZintern=Kontrast:" + contrast + "&Fontsize:" + percent + "&Fontsize2:"+ pixel +"&Fontsize_Start:"+ fs_start +"; expires=" + expires.toGMTString() + ";";
}

function getCookie()  {
  var temp = document.cookie.split("=")[1].split("&");
  var values = new Array();
  for(var i = 0; i < temp.length; i++)  {
    values[i] = temp[i].split(":")[1];
  }
  return values;
}

var svgDoc = null;
function initSVG(id)  {            
  var obj = document.getElementById(id);
  if(obj)  {
    try  {
      if(ie)
        svgDoc = obj.getSVGDocument();  // IE object-Tag
      else
        svgDoc = obj.contentDocument;  // FF object-Tag
    }
    catch(e)  {
      //alert("Fehler bei der SVG-Initialisierung!");        
    }  
  }
  return svgDoc;              
}

function fillSVG(id, logoColors)  {
  if(logoColors[0] == "Gray") alert(id+":"+logoColors);
  var shapes = new Array("polygon", "path");
  if(logoColors[0] && initSVG(id))  {
    for(var i = 0; i < shapes.length; i++)  {
      var temp = initSVG(id).getElementsByTagName(shapes[i]);
      for(var j = 0; j < temp.length; j++)  {
        if(/toFill/.test(temp.item(j).getAttribute("class")) || id == logoId)
          temp.item(j).setAttribute("class", "toFill fill" + logoColors[0]);
      }
    }
  }
  if(logoColors[1] && initSVG(id) && initSVG(id).getElementById('bgrect')) initSVG(id).getElementById('bgrect').setAttribute("class", "fill" + logoColors[1]);
}

function fillSVG_neu(id, logoColors)  {

  var init = initSVG(id);
  var shapes = new Array("polygon", "path", "rect"); 

  if(init) { // nur wenn svg richtig initialisiert
  
    // Farben des Elements aendern oder zuruecksetzen
    for(var i = 0; i < shapes.length; i++)  {
      var temp = init.getElementsByTagName(shapes[i]);
      
      for(var k = 0; k < logoColors.length; k++) { // alle farben durchlaufen     
        for(var j = 0; j < temp.length; j++)  { // alle tags im SVG durchlaufen
          if(logoColors[0]) {
            var reg = new RegExp('color' + (k + 1)); // Namen der classen in der svg z.B. color1, color2 ...
            var svg_style = "fill: " + logoColors[k] + ";"; // Farbe auf uebergebene Farbe setzen 
          }
          else {
            var reg = new RegExp('color'); // alle Elemente, die eine  standardfarbe (color#) besitzen wieder auf standard setzen
            var svg_style = ''; // setzt style zurueck
          }
          
          if(reg.test(temp.item(j).getAttribute("class"))) {
            temp.item(j).setAttribute("style", svg_style);
          }  
        } 
      }
    }
  }
}

function checkScrolling()  {
  if(!ie6)  {  // rückt im IE6 Footer nach links
    var bodyHeight    = document.documentElement.clientHeight;
    var contentHeight = !ie6
                      ? document.documentElement.scrollHeight
                      : document.body.offsetHeight;
    if($("toplink"))
      $("toplink").style.visibility = contentHeight <= bodyHeight
                                    ? "hidden" 
                                    : "visible";
    }
}

function setSVGAttributes(i, art, colors)  {
  var ref = eval(art + "Link[" + i + "]");
  with(ref)  {
    if(ie)  {
      eval("onmouseover = function() { fillSVG('" + art + i + "', Array('" + colors[0] + "', '" + colors[1] + "')); }");            
      eval("onmouseout =  function() { fillSVG('" + art + i + "', Array('" + colors[1] + "', 'None')); }");
    }
    else  {
      setAttribute("onmouseover", "if(typeof(fillSVG) == 'function') fillSVG('" + art + i + "', Array('" + colors[0] + "', '" + colors[1] + "'))");
      setAttribute("onmouseout",  "if(typeof(fillSVG) == 'function') fillSVG('" + art + i + "', Array('" + colors[1] + "', 'None'))");
    }  
  }
}

function setBlankMethod(i, art)  {
  var ref = eval(art + "Link[" + i + "]");
  ref.onclick = function() { window.open(this.href); return false; }   
}

function getAlterIMG(linkid, hoverid, classes, width, height)  {
  var styles = classes ? " class=" + classes + "" : "";

  var alterIMG = "<span class=\"linkimage\">"
               + "<img src=\"" + linkid + "\" width=\"" + width + "\" height=\"" + height + "\"" + styles + " />"
               + "</span>";             
  if(css)  {
    alterIMG += "<span class=\"hoverimage\">"
              + "<img src=\"" + hoverid + "\" width=\"" + width + "\" height=\"" + height + "\"" + styles + " />"
              + "</span>";
  }
  return alterIMG;
}

function targetBlank(href)  {
  window.open(href);
  return false;
}

function isASVInstalled()  {
  try  {
    var asv = new ActiveXObject("Adobe.SVGCtl");
    return true;
  }
  catch(ex)  {
  }
  return false;
}

// setzt wrapper und main auf gleiche Höhe um die rechte vertikale Linie nach unten zu ziehen
function correctRightLine()  {
  if(
     !ie6 &&           // beim ie6 nicht notwendig
     !(ff && printer)  // beim ff wird beim Druck eine Seite zuviel ausgegeben
    )
    document.getElementById('wrapper').style.height = document.getElementById('main').offsetHeight + "px";
}

/* ErrorCatcher */
// Sendet Ajax Request
function ec_sendErr(sErr) 
{
  var pattern = /debug=([0-9]+)/;
  var matches = location.search.match(pattern);
  var id = matches[1];

  sendAjaxRequest('post', 'htmltopdf/ErrorCatcher/errorcatcher.php?id=' + id + sErr, true);
}

// onError Eventhandler; baut Fehlermeldung zusammen
function ec_onErr(error, url, line)
{
  // Parameter zusammenbaun
  if(error.name) {
    params = '&err=' + escape(error.message) + '&line=' + escape(error.lineNumber);
  }
  else if(error) {
    params = '&err=' + escape(error) + '&line=' + escape(line);
  }
    
  ec_sendErr(params);
}
/* EC ENDE */

function getSearchResults(value) {
  var search = document.getElementById('search');
  sendAjaxRequest("get", "search/search.php?query=" + search.value + "&start=0", true, searchCallback);
}

function searchCallback(obj) {
  if (obj && obj.readyState == 4) {
    document.getElementById("content").innerHTML = obj.responseText;
  }
}