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

//see Klettergruppe.js on how to extend!

//
// Import a javascript file
//
function import_js(jsFile) {
//alert('import '+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=false;
  if (cur_script && cur_script.func) {
    if (cur_script.func=='jQuery') {  //need to wait for jQuery
      try { f=eval("window."+cur_script.func); } catch(e) {}
      if (!f) {
        if (js_loadcount++<=10) {
          setTimeout(js_loaded, 100);  //wait some more, max 10 times
          return;
        }
    //alert(cur_script.name+' not loaded');
      }
    } else waitfor=cur_script.func  //otherwise only wait for the very last loaded script
  }
  cur_script=scripts.shift();
  if (cur_script) {
    js_loadcount=0;
    import_js(cur_script.name);
  } else {
    try { f=eval("window."+waitfor); } catch(e) {}
    if (!f) {
      if (js_loadcount++<=10) {
        setTimeout(js_loaded, 100);  //wait some more, max 10 times
        return;
      }
  //alert(cur_script.name+' not loaded');
    }
    all_loaded();
  }
}
//
// start loading javascript (but wait some time for other scripts to extend 'scripts')
//setTimeout(js_loaded, 1000);
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(/[\?#]*/,'');
    url1=url.replace(/\/[^\/]*$/,'.html');
        //url1: z.B. Anlagen/Braunschweiger-Huette/Touren.html -> Anlagen/Braunschweiger-Huette.html
//    $('#sektionmenu a').each(function() {
    $('.davmenu a').each(function() {
      if (this.href.replace(/[\?#]*/,'')==url || this.href.replace(/[\?#]*/,'')==url1) {
        if (this.href.replace(/[\?#]*/,'')==url1) url1='';
        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().prop('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
    //
    $('.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'
    });

    //
    //Ein-/Mehrspaltig
    //
    $(window).resize(function() {
      if ($('.first.column').size()==0) {
        if (!autospaltig) return;
/*
        //Einspaltig
        var minx=0; var maxx=0; var flatter=false;
        $('table.Bild').each(function (i) {
          if ($(this).attr('align')=='left') {
            var x=$(this).position().left;
            if (minx==0) minx=x;
            if (minx>0 && x!=minx) {
              //move bild down to next paragraph
              //$(this).next().after($(this));
              flatter=true;
            }
          } else {
            var x=$(this).position().left+$(this).outerWidth();
            if (maxx==0) maxx=x;
            if (maxx>0 && x!=maxx) {
              //move bild down to next paragraph
              //$(this).next().after($(this));
              flatter=true;
            }
          }
          });
        //if (minx<0) alert('Flatter links');
        //if (maxx<0) alert('Flatter rechts');
        if (!flatter) {
          return;
        }
        flatterd=true;
        //if flatter: -> mehrspaltig
*/
      }
      if ($('.mtbbericht').data("resizing")) return;
      $('.mtbbericht').data("resizing",true);
      if ($.browser.msie){
        if ($('.mtbbericht').data("timeout")){
          clearTimeout($('.mtbbericht').data("timeout"));
        }
        $('.mtbbericht').data("timeout", setTimeout(resizespaltig, 100));
      } else {
        resizespaltig();
      }
    });
    //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();
  if (autospaltig) $(window).resize();

  if (window.sub_all_loaded) window.sub_all_loaded();
};

/*********************************************************************************/
/*** 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 ***/
var autospaltig=false;
//var flatterd=false;
function mehrspaltig() {
  minwidth=0;
  $('table.Bild').each(function (i) {
      var w=$(this).outerWidth(); if (w>minwidth) minwidth=w;
      $(this).data('align',$(this).attr('align')).data('margin',$(this).css('margin'))
    }).
//    attr('align', 'center').css('margin','auto').
    addClass('dontsplit');
//  var cols=Math.floor($('.mtbbericht').width()/minwidth);
//  if (cols==1) return;
  var cols=$('.mtbbericht').width()<620?1:($('.mtbbericht').width()<1000?2:3);
  if (cols==1) return einspaltig();
//  if (cols==2 && flatterd) { flatterd=false; return; }
  var spacer=10;
  if ($('.mtbbericht').width()/cols<minwidth+150)
    $('table.Bild').attr('align', 'center').css('margin','auto');
    //patched: added 'spacer'
  $('.mtbbericht').columnize({ columns: cols, xwidth: minwidth, spacer: spacer, buildOnce: true, lastNeverTallest: true });
  $('#togglespaltig span').text('einspaltig');
}

function einspaltig() {
//  $(window).unbind('resize');
  $('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
  if ($('.mtbbericht').children(':first').attr('tagName')=='BR')
    $('.mtbbericht').children(':first').remove();     // remove the probably 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');
  });
  $('#togglespaltig span').text('mehrspaltig');
}
function togglespaltig() {
  if ($('.first.column').size()>0) einspaltig();
  else mehrspaltig();
}
function resizespaltig() {
  if ($('.first.column').size()>0)
    einspaltig();
  mehrspaltig();
  $('.mtbbericht').data("resizing",false);
}

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;
}

