//
// 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='';
}

/*********************************************************************************/
/*** 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');
}
