/*
 * Thickbox 2 Sefrengo
 * von Olaf Bosch http://olaf-bosch.de
 * Demo: http://olaf-bosch.de/bugs/jquery/fileman/
 * Copyright (c) 2006 Olaf Bosch
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * $Date: 2006-12-08
 * $Rev: 1.0.1
 ***** beruht auf Original:
 * Thickbox 2.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2006 cody lindley
 * Thickbox is built on top of the very light weight jQuery library.
 */
//on page load call TB_init
jQuery(document).ready(function($) {
  jQuery(document).ready(TB_init);

    //add thickbox to href elements that have a class of .thickbox
    function TB_init(){
      $("a.thickbox").click(function(){
         var url = this.href;
         if(url.indexOf("?")!==-1){ //If there is a query string involved
          var baseURL = url.substr(0, url.indexOf("?"));
         }else{
             var baseURL = url;
         }
      var checkURL = baseURL.toLowerCase();
      if( /\.(jpg|jpeg|png|gif|bmp|css|txt|pdf|wmv|mov|swf|avi|htm|php|xml|html)$/.test(checkURL) ) {
              var t = this.title || null;
              var g = false; //this.rel || false
                    // PopUp - definieren
                    var w = getNumber(this.id) || 500;  // max. Breite
                    var h = getNumber(this.name) || 630;  // max. Höhe
                    //alert (h);
              TB_show(t,g,checkURL,url, h, w);
              this.blur();
              return false;
      }
      });
    }
    // PopUp - definieren
    //var DivH = 550;  // max. Höhe
    //var DivW = 630;  // max. Breite
    function getNumber(id){
            var tmp = id.split("n");
            return tmp[1];
    }

    function TB_show(caption, imageGroup, checkURL, url, DivH, DivW) {//function called when the user clicks on a thickbox link
      try {
        if( /\.(jpg|jpeg|png|gif|bmp)$/.test(checkURL) ) { // Bilder

        if (document.getElementById("TBhideSelect") == null) {
        $("body").append("<iframe id='TBhideSelect'></iframe>\n<div id='TBoverlay'>\n</div>\n<div id='TBwindow'>\n</div>");
        $("#TBoverlay").click(TB_remove);
        }

        if(caption==null){caption=""};
        $(window).scroll(TB_position);
        TBoverlaySize();

        $("body").append("\n<div id='TBload'></div>");
        TBload_position();

          TBprevCaption = "";
          TBprevURL = "";
          TBprevHTML = "";
          TBnextCaption = "";
          TBnextURL = "";
          TBnextHTML = "";
          TBimageCount = "";
          TB_FoundURL = false;
          if(imageGroup){
            TB_TempArray = $("a[@rel="+imageGroup+"]").get();
            for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TBnextHTML == "")); TB_Counter++) {
              var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase();
                if (!(TB_TempArray[TB_Counter].href == url)) {
                  if (TB_FoundURL) {
                    TBnextCaption = TB_TempArray[TB_Counter].title;
                    TBnextURL = TB_TempArray[TB_Counter].href;
                    TBnextHTML = "\n<span id='TBnext'>\n<a href='#'>Next <small>(</small>&#8594;<small>)</small></a></span>";
                  } else {
                    TBprevCaption = TB_TempArray[TB_Counter].title;
                    TBprevURL = TB_TempArray[TB_Counter].href;
                    TBprevHTML = "\n<span id='TBprev'>\n<a href='#'><small>(</small>&#8592;<small>)</small> Prev</a></span>";
                  }
                } else {
                  TB_FoundURL = true;
                  TBimageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);
                }
            }
          }
          imgPreloader = new Image();
          imgPreloader.onload = function(){
          imgPreloader.onload = null;

          // Resizing large images - orginal by Christian Montoya edited by me.
          var pagesize = TB_getPageSize();
          var x = pagesize[0] - 150;
          var y = pagesize[1] - 150;
          var imageWidth = imgPreloader.width;
          var imageHeight = imgPreloader.height;
          if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth);
            imageWidth = x;
            if (imageHeight > y) {
              imageWidth = imageWidth * (y / imageHeight);
              imageHeight = y;
            }
          } else if (imageHeight > y) {
            imageWidth = imageWidth * (y / imageHeight);
            imageHeight = y;
            if (imageWidth > x) {
              imageHeight = imageHeight * (x / imageWidth);
              imageWidth = x;
            }
          }
          // End Resizing

          TB_WIDTH = imageWidth + 0; //30
          TB_HEIGHT = imageHeight + 0; //30
          $("#TBwindow").fadeIn("fast").append("<div id='TBtitle'><div id='TBcloseAjaxWindow'><a href='#' id='TBcloseWindowButton' title='Schließen'>Fenster schließen <small>X</small></a>\n</div><div id='TBajaxWindowTitle'>"+caption+"\n<div id='TBsecondLine'>" + TBimageCount + TBprevHTML + TBnextHTML + "\n</div>\n</div>\n</div>"+"\n<a href='' id='TBimageOff' title='Schließen'>\n<img id='TBimage' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>");

          $("#TBcloseWindowButton").click(TB_remove);

          if (!(TBprevHTML == "")) {
            function goPrev(){
              $("#TBwindow").remove();
              $("body").append("\n<div id='TBwindow'>\n</div>");
              TB_show(TBprevCaption, imageGroup, checkURL, TBprevURL);
              return false;
            }
            $("#TBprev").click(goPrev);
          }

          if (!(TBnextHTML == "")) {
            function goNext(){
              $("#TBwindow").remove();
              $("body").append("\n<div id='TBwindow'>\n</div>");
              TB_show(TBnextCaption, imageGroup, checkURL, TBnextURL);
              return false;
            }
            $("#TBnext").click(goNext);
          }

          document.onkeydown = function(e){
            if (e == null) { // ie
              keycode = event.keyCode;
            } else { // mozilla
              keycode = e.which;
            }
            if(keycode == 27){ // close
              TB_remove();
            } else if(keycode == 39){ // display previous image
              if(!(TBnextHTML == "")){
              document.onkeydown = "";
              goNext();
              }
            } else if(keycode == 37){ // display next image
              if(!(TBprevHTML == "")){
              document.onkeydown = "";
              goPrev();
              }
            }
          }

          TB_position();
          $("#TBload").remove();
          $("#TBimageOff").click(TB_remove);
          $("#TBwindow").css({display:"block"}); //for safari using css instead of show
          }

          imgPreloader.src = url;
        }
    // Ende Bilder
    // Ajax im DIV
        if( /\.(htm|xml|html)$/.test(checkURL) ) {

        if (document.getElementById("TBhideSelect") == null) {
        $("body").append("<iframe id='TBhideSelect'></iframe>\n<div id='TBoverlay'>\n</div>\n<div id='TBwindow'>\n</div>");
        $("#TBoverlay").click(TB_remove);
        }

        if(caption==null){caption=""};
        $(window).scroll(TB_position);
        TBoverlaySize();

        $("body").append("\n<div id='TBload'></div>");
        TBload_position();
        TB_resize(DivW, DivH);

          $("#TBwindow").fadeIn("fast").append("\n<div id='TBtitle'>\n<div id='TBcloseAjaxWindow'><a href='#' id='TBcloseWindowButton'>Fenster schließen <small>X</small></a>\n</div>\n<div id='TBajaxWindowTitle'>"+caption+"\n</div>\n</div>\n<div id='TBajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'>\n</div>");

          $("#TBcloseWindowButton").click(TB_remove);

        if( /\.(htm|html)$/.test(checkURL) ) {
           $.ajax({
           type: "GET",
           url: url,
           dataType: "html",
           success: function(msg){
             $("#TBajaxContent").html(msg);
             TB_position();
             $("#TBload").remove();
             $("#TBwindow").css({display:"block"});
             }
           });
        }
        if( /\.(xml)$/.test(checkURL) ) {
           $.ajax({
           type: "GET",
           url: url,
           dataType: "html",
           success: function(xml){
             xml = xml.replace(/</g, "&lt;").replace(/ /g, "&nbsp;").replace(/\n/g, "<br \/>");
             $("#TBajaxContent").append(xml);
             TB_position();
             $("#TBload").remove();
             $("#TBwindow").css({display:"block"});
    }
    });
        }
      }
    // Ende Ajax
    // IFrame
        if( /\.(txt|css|php)$/.test(checkURL) ){

        if (document.getElementById("TBhideSelect") == null) {
        $("body").css({margin : "0",padding: "0"}).append("<iframe id='TBhideSelect'></iframe>\n<div id='TBoverlay'>\n</div>\n<div id='TBwindow'>\n</div>");
        $("#TBoverlay").click(TB_remove);
        }

        if(caption==null){caption=""};
        $(window).scroll(TB_position);
        TBoverlaySize();

        $("body").append("\n<div id='TBload'></div>");
        TBload_position();
        TB_resize(DivW, DivH);

          $("#TBwindow").fadeIn("fast").append("\n<div id='TBtitle'>\n<div id='TBcloseAjaxWindow'><a href='#' id='TBcloseWindowButton' title='Schließen'>Fenster schließen <small>X</small></a>\n</div>\n<div id='TBajaxWindowTitle'>"+caption+"\n</div>\n</div><iframe frameborder='0' hspace='0' src='"+url+"' id='TBiframeContent' name='TBiframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH)+"px;' onload='TB_showIframe()'></iframe>");
          $("#TBcloseWindowButton").click(TB_remove);

              TB_position();
              if(frames['TBiframeContent'] == undefined){//be nice to safari
                $("#TBload").remove();
                $("#TBwindow").css({display:"block"});
                $(document).keyup( function(e){ var key = e.keyCode; if(key == 27){TB_remove()} });
          }
        }
    // Ende IFrame
    // PDF in new Window
        if( /\.(pdf)$/.test(checkURL) ) {
          var winObj = null

            var xPos = Math.floor((screen.availWidth  - DivW) / 2)
            var yPos = Math.floor((screen.availHeight - DivH) / 2)
            if (winObj != null && !winObj.closed)
                    winObj.close()
            winObj = window.open(url, 'daWin', 'width=' + DivW + ', height=' + DivH
                         + ', location=no, menubar=no, resizable=yes,'
                         + 'status=no, toolbar=no, screenX=' + xPos + ', screenY='
                         + yPos + ', left=' + xPos + ', top=' + yPos)
            winObj.focus()
        }

    // Ende PDF
    // WMV MOV SWF
        if( /\.(wmv|mov|swf|avi)$/.test(checkURL) ) {

        if (document.getElementById("TBhideSelect") == null) {
        $("body").append("<iframe id='TBhideSelect'></iframe>\n<div id='TBoverlay'>\n</div>\n<div id='TBwindow'>\n</div>");
        $("#TBoverlay").click(TB_remove);
        }

        if(caption==null){caption=""};
        $(window).scroll(TB_position);
        TBoverlaySize();

        $("body").append("\n<div id='TBload'></div>");
        TBload_position();
        TB_resize(DivW, DivH);

         $("#TBwindow").fadeIn("fast").append("\n<div id='TBtitle'>\n<div id='TBcloseAjaxWindow'><a href='#' id='TBcloseWindowButton'>Fenster schließen <small>X</small></a>\n</div>\n<div id='TBajaxWindowTitle'>"+caption+"\n</div>\n</div>\n<div id='TBajaxContent' style='padding:0;width:"+TB_WIDTH+"px;height:"+ajaxContentH+"px;'></div>");
        if( /\.(wmv|avi)$/.test(checkURL) ) {

    if($.browser.msie) {
         $("#TBajaxContent").append("<object id='wmv' type='video/x-ms-wmv' width='' height='' data='"+url+"' ><param name='src' value='"+url+"' /><param name='autostart' value='true' /><param name='showcontrols' value='true' /><param name='stretchtofit' value='false' /><param name='controller' value='true' /></object>");
     } else {
      ajaxContentH = ajaxContentH + 1;
         $("#TBajaxContent").css({overflow:"hidden"}).append("<object style='margin-top:-1px' id='wmv' type='video/x-ms-wmv' width='"+TB_WIDTH+"' height='"+ajaxContentH+"' data='"+url+"' ><param name='src' value='"+url+"' /><param name='autostart' value='true' /><param name='showcontrols' value='true' /><param name='stretchtofit' value='false' /><param name='controller' value='true' /></object>");
      }
    }
        if( /\.(mov)$/.test(checkURL) ) {

    if($.browser.msie) {
         $("#TBajaxContent").append("<object id='wmv' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab' width='"+TB_WIDTH+"' height='"+ajaxContentH+"'><param name='src' value='"+url+"' /><param name='controller' value='true' /><param name='autoplay' value='true' /></object>");
     } else {
         $("#TBajaxContent").css({overflow:"hidden"}).append("<object id='wmv' type='video/quicktime' data='"+url+"' width='"+TB_WIDTH+"' height='"+ajaxContentH+"'><param name='autoplay' value='true' /><param name='controller' value='true' /></object>");
      }
    }
        if( /\.(swf)$/.test(checkURL) ) {

    if($.browser.msie) {
         $("#TBajaxContent").append("<object id='wmv' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='"+TB_WIDTH+"' height='"+ajaxContentH+"'><param name='movie' value='"+url+"' /></object>");
     } else {
     ajaxContentH = ajaxContentH + 1;
         $("#TBajaxContent").css({overflow:"hidden"}).append("<object style='margin-top:-1px' id='wmv'type='application/x-shockwave-flash' data='"+url+"' width='"+TB_WIDTH+"' height='"+ajaxContentH+"'><param name='movie' value='"+url+"' /></object>");
      }
    }
         TB_position();
         $("#TBload").remove();
         $("#TBwindow").css({display:"block"});
         $("#TBcloseWindowButton").click(TB_remove);

        }
    // Ende  WMV MOV SWF

      } catch(e) {
        alert( e );
      }
    }

    //helper functions
    function TB_resize(DivW, DivH){
          TB_WIDTH = (DivW*1) + 0; //30
          TB_HEIGHT = (DivH*1) + 15; //40
          ajaxContentW = TB_WIDTH - 0; //30
          ajaxContentH = TB_HEIGHT - 0; //45

          // Resizing large images - orginal by Christian Montoya edited by me.
          /*var pagesize = TB_getPageSize();
          var x = pagesize[0] - 100;
          var y = pagesize[1] - 100;
          if (ajaxContentW > x) {
            ajaxContentH = ajaxContentH * (x / ajaxContentW);
            ajaxContentW = x;
            if (ajaxContentH > y) {
              ajaxContentW = ajaxContentW * (y / ajaxContentH);
              ajaxContentH = y;
            }
          } else if (ajaxContentH > y) {
            ajaxContentW = ajaxContentW * (y / ajaxContentH);
            ajaxContentH = y;
            if (ajaxContentW > x) {
              ajaxContentH = ajaxContentH * (x / ajaxContentW);
              ajaxContentW = x;
            }
          }
          TB_WIDTH = (ajaxContentW*1) + 0; //30
          TB_HEIGHT = (ajaxContentH*1) + 0;*/ //40
          // End Resizing
    }
    function TB_showIframe(){
      $("#TBload").remove();
      $("#TBwindow").css({display:"block"});
    }
    function TB_remove() {
      $("#wmv").stop().empty().remove();
      $("#TBwindow").fadeOut("fast",function(){$('#TBwindow,#TBhideSelect').remove();});
      $("#TBoverlay").fadeOut("fast",function(){$('#TBoverlay,').remove();});
      $("#TBload").remove();
      return false;
    }
    function TB_position() {
      var pagesize = TB_getPageSize();
      var arrayPageScroll = TB_getPageScrollTop();
      $("#TBwindow").css({width:TB_WIDTH+"px",left: (arrayPageScroll[0] + (pagesize[0] - TB_WIDTH)/2)+"px", top: (arrayPageScroll[1] + (pagesize[1]-TB_HEIGHT)/2)+"px" });
    }
    function TBoverlaySize(){
      if (window.innerHeight && window.scrollMaxY || window.innerWidth && window.scrollMaxX) {
        yScroll = window.innerHeight + window.scrollMaxY;
        xScroll = window.innerWidth + window.scrollMaxX;
        var deff = document.documentElement;
        var wff = (deff&&deff.clientWidth) || document.body.clientWidth || window.innerWidth || self.innerWidth;
        var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
        xScroll -= (window.innerWidth - wff);
        yScroll -= (window.innerHeight - hff);
      } else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){ // all but Explorer Mac
        yScroll = document.body.scrollHeight;
        xScroll = document.body.scrollWidth;
      } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        yScroll = document.body.offsetHeight;
        xScroll = document.body.offsetWidth;
        }
      $("#TBoverlay").css({"height":yScroll +"px"});
      $("#TBhideSelect").css({"height":yScroll +"px","width":xScroll +"px"});
    }
    function TBload_position() {
      var pagesize = TB_getPageSize();
      var arrayPageScroll = TB_getPageScrollTop();
      $("#TBload")
      .css({left: (arrayPageScroll[0] + (pagesize[0] - 100)/2)+"px", top: (arrayPageScroll[1] + ((pagesize[1]-100)/2))+"px" })
      .css({display:"block"});
    }
    function TB_getPageScrollTop(){
      var yScrolltop;
      var xScrollleft;
      if (self.pageYOffset || self.pageXOffset) {
        yScrolltop = self.pageYOffset;
        xScrollleft = self.pageXOffset;
      } else if (document.documentElement && document.documentElement.scrollTop || document.documentElement.scrollLeft ){   // Explorer 6 Strict
        yScrolltop = document.documentElement.scrollTop;
        xScrollleft = document.documentElement.scrollLeft;
      } else if (document.body) {// all other Explorers
        yScrolltop = document.body.scrollTop;
        xScrollleft = document.body.scrollLeft;
      }
      arrayPageScroll = new Array(xScrollleft,yScrolltop)
      return arrayPageScroll;
    }
    function TB_getPageSize(){
      var de = document.documentElement;
      var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
      var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight
      arrayPageSize = new Array(w,h)
      return arrayPageSize;
    }
    document.onkeydown = function(e){
      if (e == null) { // ie
        keycode = event.keyCode;
      } else { // mozilla
        keycode = e.which;
      }
      if(keycode == 27){ // close
        TB_remove();
      }
    }
});