/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 
 * Modifications | Christian Schindler
 * Edited 29.01.2008
 * + add closeWindow image [magnifier_minus.png] to TB_closeWindow
 * Edited 30.01.2008
 * + changed function arguments for ThickBox inclusion: tb_show(url, caption, description, imageGroup, index)
 * + NEW variable: arrayURL
 * + baseURL: changed [url] to [arrayURL]
 * + TB_PrevHTML, TB_NextHTML: function goPrev, function goNext
 * -> added new var TB_PrevDescription, TB_NextDescription, TB_PrevIndex, TB_NextIndex
 * Edited 19.05.2008
 * + erase link for dark background -> only close with minifier-button now
*/
      
var tb_pathToImage = "data/referenzen/fotostudio/modul/loadingAnimation.gif";

// on page load
$(document).ready(function(){ 
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});


function tb_show(url, caption, description, imageGroup, index) {// function called when user clicks on a thickbox link in FLASH

  var arrayURL 		= url;// split image url array from FLASH
  var currURL 		= url[index];

  var arrayCAPTION 	= caption;// split image caption array from FLASH
  var currCAPTION 	= caption[index];

  var arrayDESC 	= description;// split image description array from FLASH
  var currDESC 		= description[index];
  

  try {
    if (typeof document.body.style.maxHeight === "undefined") {// if IE 6
      $("body","html").css({height: "100%", width: "100%"});
      $("html").css("overflow","hidden");
      if (document.getElementById("TB_HideSelect") === null) {// iframe to hide select elements in ie6
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
      }
    }else{//all others
      if(document.getElementById("TB_overlay") === null){
        $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
      }
    }
    
    if(tb_detectMacXFF()){
      $("#TB_overlay").addClass("TB_overlayMacFFBGHack");// use png overlay so hide flash
    }else{
      $("#TB_overlay").addClass("TB_overlayBG");// use background and opacity
    }
    
    if(caption===null){caption="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");// add loader to the page
    $('#TB_load').show();// show loader

    var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
    var urlType = currURL.toLowerCase().match(urlString);
    if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){
	  
	  // check for image groups
      if(imageGroup){
		TB_TempArray = arrayURL;
		TB_Counter_Next = (index + 1) % TB_TempArray.length;
		TB_Counter_Prev = (index - 1 + TB_TempArray.length) % TB_TempArray.length;

		TB_NextURL 			= TB_TempArray[TB_Counter_Next];
		TB_NextCaption 		= arrayCAPTION[TB_Counter_Next];
		TB_NextDescription 	= arrayDESC[TB_Counter_Next];
		TB_NextIndex		= TB_Counter_Next;
		TB_NextHTML 		= "<div id='TB_next'><a href='#' onfocus='this.blur()'></a></div>";
		
		TB_PrevURL 			= TB_TempArray[TB_Counter_Prev];
		TB_PrevCaption 		= arrayCAPTION[TB_Counter_Prev];
		TB_PrevDescription 	= arrayDESC[TB_Counter_Prev];
		TB_PrevIndex		= TB_Counter_Prev;
		TB_PrevHTML 		= "<div id='TB_prev'><a href='#' onfocus='this.blur()'></a></div>";
      }   
	  else 
	  {
		TB_NextHTML 		= "<div id='TB_next'>&nbsp;</div>";
		TB_PrevHTML 		= "<div id='TB_prev'>&nbsp;</div>";
	  }
	  
	  // image preloader
      imgPreloader = new Image();
      imgPreloader.onload = function(){    
      imgPreloader.onload = null;
      // Resizing large images
      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;
      TB_HEIGHT = imageHeight + 0;
	  
	  // append html to document
      $("#TB_window").append("<a href='' id='TB_ImageOff' title='Ansicht schließen'><img id='TB_Image' src='"+currURL+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+currCAPTION+"'/></a>" + "<div id='TB_caption'>"+currCAPTION+"<div id='TB_secondLine'>"+currDESC+"</div></div>" + "<div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'><img src='data/referenzen/fotostudio/modul/magnifier_minus.gif' width='26px' height='26px' alt='Ansicht schließen' /></a></div>" + "<div id='TB_panel' style='width:'"+imageWidth+"''><div id='TB_panelbttns'>" + TB_NextHTML + TB_PrevHTML + "</div></div>");
      $("#TB_closeWindowButton").click(tb_remove);
      
      // functions for next/prev buttons [goPrev(), goNext()]
      if (!(TB_PrevHTML === "")) {
        function goPrev(){
          if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(url, caption, description, imageGroup, TB_PrevIndex);
          return false;  
        }
        $("#TB_prev").click(goPrev);
      }
      
      if (!(TB_NextHTML === "")) {    
        function goNext(){
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(url, caption, description, imageGroup, TB_NextIndex);
          return false;  
        }
        $("#TB_next").click(goNext);
      }
	  
	  // define key functions
      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(!(TB_NextHTML == "")){
            document.onkeydown = "";
            goNext();
          }
        } else if(keycode == 37){ // display next image
          if(!(TB_PrevHTML == "")){
            document.onkeydown = "";
            goPrev();
          }
        }  
      };
      
      tb_position();
      $("#TB_load").remove();
      $("#TB_ImageOff").click(tb_remove);
      $("#TB_window").css({display:"block"}); //for safari using css instead of show
      };
      
      imgPreloader.src = currURL;
    }
	
	
    if(!params['modal']){
      document.onkeyup = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        }  
      };
    }
    
  } catch(e) {
    //nothing here
  }
}

//helper functions below
function tb_remove() {
  $("#TB_imageOff").unbind("click");
  $("#TB_closeWindowButton").unbind("click");
  $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
  $("#TB_load").remove();
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    $("body","html").css({height: "auto", width: "auto"});
    $("html").css("overflow","");
  }
  
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

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 = [w,h];
  return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}
