//
// define scripts to be loaded, waiting for 'func' to exist before next is loaded
//
var scripts=[
  {name: '/scripts/jquery.js',       func: 'jQuery' },
  {name: '/scripts/lightbox.js',     func: 'jQuery.fn.lightBox'},
  {name: '/scripts/autocolumn.js',     func: 'jQuery.fn.columnize'}
];

//
// Import a javascript file
//
function import_js(jsFile) {
	var head = document.getElementsByTagName("head")[0] || document.documentElement,
		script = document.createElement("script");
	script.type = "text/javascript";
  script.src = jsFile;
	// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
	// This arises when a base node is used (#2709).
	head.insertBefore( script, head.firstChild );
	//head.removeChild( script ); //not good for IE and opera!

  // wait till loaded, than load next
  setTimeout(js_loaded, 0);
}
//
// wait till javascript loaded, than load next
//
var js_loadcount;
var cur_script;
function js_loaded() {
//geht nicht in IE oder opera:
//  if (cur_script && typeof(eval(cur_script.func))=='undefined') {
  var f;
  try { f=eval("window."+cur_script.func); } catch(e) { f=false; }
  if (cur_script && !f) {
    if (js_loadcount++<=10) {
      setTimeout(js_loaded, 100);  //wait some more, max 10 times
      return;
    }
//alert(cur_script.name+' not loaded');
  }
  cur_script=scripts.shift();
  if (cur_script) {
    js_loadcount=0;
    import_js(cur_script.name);
  } else
    all_loaded();
}
//
// start loading javascript
js_loaded();

//////////////////////////////////////////////////////////////////////////////////
// All javascripts are loaded now
//
function all_loaded() {
  $(document).ready(function() {

    //
    // center background image
    //
    //bgcenter();
    //$(window).resize(bgcenter);

    //
    // style current menu item
    //
    var url=document.URL;
    url=url.replace(/[\?#]*/,'');
    $('#sektionmenu a').each(function() {
      if (this.href.replace(/[\?#]*/,'')==url) {
        var m=$(this);
        //unfold current menu
        m.closest('li.davmainmenu').find('ul').css('display','list-item');
        //style current menu item
        m.addClass('current').parent().addClass('current');
    //
    // print the 'Where am I' text
    //
        var wai=$('#whereami');
        var txt=m.text();
        //find surrounding 'ul' and add text of preceeding <a> or #text
        while ((m=m.closest('ul:not("#sektionmenu")')), m.length&&m.attr) {
          var ptxt=m.prev().length
            ?m.prev().text()    //a <a> node
            :m.parent().attr('firstChild').textContent; //a #text node
                        //Its not possible with jQuery to get the first #text node
          if (ptxt) txt=ptxt+' > '+txt;
          m=m.parent();
        }
        wai.text(txt.replace(/\-\s*kurse/,'kurse'));
        return false; //stop each-loop
      }
    });

    //
    // Die Bilder in den Bildboxen mit Bildunterschrift
    //
    $('table.Bild a').lightBox({
      singleImage:      true, //patched!
      davbs:            true, //patched!
      maxWidth:         -1000,  //patched! <0: fit to page to this max
      maxHeight:        -1000,  //patched!

  		fixedNavigation:		false,
    	overlayBgColor: '#dFd',
    	overlayOpacity: 0.8,
  		imageLoading:			'/scripts/images/lightbox-ico-loading.gif',
  //			imageBtnPrev:			'/scripts/images/lightbox-btn-prev.gif',
  //			imageBtnNext:			'/scripts/images/lightbox-btn-next.gif',
  //			imageBtnClose:		'/scripts/images/lightbox-btn-close.gif',
  		imageBtnPrev:			'/scripts/images/prev.png',
  		imageBtnNext:			'/scripts/images/next.png',
  		imageBtnClose:		'/scripts/images/close.gif',
  		imageBlank:				'/scripts/images/lightbox-blank.gif',
    	containerResizeSpeed: 350,
    	txtImage: 'Bild',
    	txtOf: 'von'
    });

    //
    //Zweipspaltig
    //
    //mehrspaltig();

    //
    // switch stylesheet if called as "URL?style=name"
    //
    var url=document.URL;
    var styleind=url.indexOf("style=");
    if (styleind>0) {
      var h=url.indexOf("#");
      var styleName=(h<0)?url.substring(styleind+6):url.substring(styleind+6,h);
      if ($('link[@rel*=style][title="'+styleName+'"]').length) {
        $('link[@rel*=style][title]').each(function() {
          this.disabled = true;
          if (this.getAttribute('title') == styleName) this.disabled = false;
        });
        //createCookie('style', styleName, 365);
        /* add style to all links (but better use cookies?) */
        $('a').each(function() {
          h=this.href.indexOf("#");
          if (h>0) {
            if (this.href.indexOf("?style=")<0)
              this.href=this.href.substring(0,h)+"?style="+styleName+this.href.substring(h);
          } else {
            this.href+="?style="+styleName;
          }
        });
      } else alert('Stylesheet '+styleName+' ist nicht bekannt');
    }

  });
  if (window.iffLoaded) iffLoaded();
};

/*********************************************************************************/
/*** Search box ***/

function toggleSBSize(big) {
    var sb = document.getElementById('searchinput');
//    if (big)
//        sb.style.width = '20em;';
//    else
//        sb.style.width = '10em;';
  if (big && (sb.value=='Suchen' || sb.value=='Search')) sb.value='';
}

/*********************************************************************************/
/*** Kleinanzeigen ***/
/* ist in DBhtml.js
function getData(script, table, field, key, event) {
  $.get(script, { 'obfuscate': table, 'field': field, 'key': key },
    function(data){
      if (data) $(event.target).html(data);
    }, 'text');
}  
*/
/*********************************************************************************/
/*** Ein-/Mehrspaltig ***/
function mehrspaltig() {
  $('table.Bild').each(function (i) {
      $(this).data('align',$(this).attr('align')).data('margin',$(this).css('margin'))}).
        attr('align', 'center').css('margin','auto').addClass('dontsplit');
  $('.mtbbericht').columnize({ xcolumns: 2, width: 320, xheight: 800, buildOnce: false });
  $('#togglespaltig span').text('einspaltig');
}

function einspaltig() {
  $('table.Bild').each(function (i) {
      $(this).attr('align', $(this).data('align')).css('margin',$(this).data('margin'))});
  $('.column').children().appendTo('.mtbbericht');  // merge columns into the mtbbericht
  $('.column').remove();                            // remove the now empty columns
  $('.mtbbericht').children(':first').remove();     // remove the added <br>
  $('.splitted').each(function (i) {  // merge split elements together (needs patch in autocolumn.js)
                                      // this probably only works for simple splitted <p>
    $(this).append($(this.nextSibling).remove().html()).removeClass('splitted');
  });
  $(window).unbind('resize');
  $('#togglespaltig span').text('mehrspaltig');
}
function togglespaltig() {
  if ($('.first.column').size()>0) einspaltig();
  else mehrspaltig();
}

function bgcenter() {
  bgwidth=512;
  w=($('#davheader').innerWidth()-220-bgwidth)/2+220;
  $('#davheader').css('background-position',w+'px center');
}

/*********************************************************************************/
/*** Obfuscated mail ***/
function getMail(name, rep, event) {
  var target=event.target?event.target:event.srcElement;  // IE kennt target nicht :-(
  while (!target.getAttribute('href') || target.getAttribute('src'))  // IE liefert bei href auch src von z.B. <img>
    target=target.parentNode;
  if (target.getAttribute('href').indexOf('@')>0) return true;
  var call="trgZnvy.cuc?anzr";
  if (!name)
    name=target.textContent.replace(/\s*$/,'').split(' ').pop();

  var ajax;
  try {			// W3C-Standard
   call=call.replace(/[a-zA-Z]/g, function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);})
   ajax = new XMLHttpRequest();
  } catch(w3c) {
   try {			// Internet Explorer
    ajax = new ActiveXObject("Msxml2.XMLHTTP");
   } catch(msie) {
    try {		// Internet Explorer alt
     ajax = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(msie_alt) {
     //alert("Ihr Browser kann keine Records anzeigen.");
     return false;	// !!! Link auf XML-Dokument
    }
   }
  }
  // Datei anfordern (asynchron)
  ajax.open('GET', '/'+call+'='+name, false);
  ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  // umgeht Internet Explorers Caching von GET-Anfragen
  ajax.setRequestHeader('If-Modified-Since', 'Sat, 1 Jan 2000 00:00:00 GMT');
  ajax.send('');

  if (!ajax.responseXML) {  // z.B. php-Syntax error
//    if (ajax.responseText) alert('2 '+ajax.responseText);
//    else alert(name+': not found');
    return false;
  }
  try {
    var mail=ajax.responseXML.getElementsByTagName("mail")[0].firstChild.nodeValue;
    var name=ajax.responseXML.getElementsByTagName("name")[0].firstChild.nodeValue;
    target.setAttribute('href','mailto:"'+name+'" <'+mail+'>');
  } catch(e) { mail=''; };
  if (mail && rep) {
    target.removeAttribute('title');
    target.removeAttribute('onclick');
    if (target.firstChild && target.firstChild.nodeName=='#text')
      target.firstChild.nodeValue=mail;
    else {
      while (target.lastChild) target.removeChild(target.lastChild);
      textNode=document.createTextNode(mail);
      target.appendChild(textNode);
    }
  } else {
    target.setAttribute('title', 'deaktiviert');
  }
  return false;
}
