// name: auto galerie
// author: Semerad Vaclav gurroa@gurroa.cz
// copyright: Medisoft (c) 2009, 2010, 2011

// settings

var __BorderColor = '#90181B';
var __BorderFontColor = '#F6D4D5';
var __BorderStyle = 'solid';
var __TransparentLevel = 0.65;
var __AnimateImageTransfer = true;


// Basic variables
var OtherOnLoadFunctions = null;
var ImageArray = new Array();
var SmallArray = new Array();
var TitleArray = new Array();
var ImgToLoad = null;
var DebugAlerts = new Array();


// Divs cache variables
var GalleryDiv = null;
var ImgToDisplay = null;
var ImgTitle = null;
var BackgroundDiv = null;
var ImgDivContainer = null;
var PreviousHref = null;
var NextHref = null;
var ImageHref = null;
var ImgNameHref = null;
var LastScroll = '0:0';
var FollowingScrollingTimeOut = null;

var ImgDivContainerPosition = new Array(0, 0);
var ImgDivContainerMove     = new Array(0, 0);
var MoveDistance            = 0;
var GalleryWasInitied       = false;

// Gallery initialization onLoad 
function LaterInitAutoGallery() {
  // Other on load actions
  if (OtherOnLoadFunctions) {
    eval(OtherOnLoadFunctions);
  }
  setTimeout("InitAutoGallery()", 200);
}

  
// Takes all <a elems with <img elem in it which are linking to an img with similar name
// Changes all of this <a elements to link to the DisplayGalleryImage function
function InitAutoGallery() {
  try {
    if (GalleryWasInitied)  
      return true;

    var AHrefs = document.getElementsByTagName('a');
    if (AHrefs.length > 0) {
      var txtdebug = '';
      for (var i = 0; i < AHrefs.length; i++) {
        var aHref = AHrefs[i];
        if (aHref && aHref.href && (aHref.href.length > 0) ) {
          var iElem = GetSubImage(aHref);
          if (iElem) {
            var sUrl = '' + aHref.href.toLowerCase();
            if (IsImage(sUrl.toLowerCase()) && (sUrl.indexOf(GetFileName(iElem.src)) > 0 || iElem.src.indexOf(GetFileName(sUrl))) ) {
              var i = ImageArray.length;
              ImageArray[i] = aHref.href;    
              SmallArray[i] = iElem.src;
              TitleArray[i] = aHref.title ? aHref.title : iElem.title; 
              if (aHref.className == 'lightbox') {
                aHref.parentNode.innerHTML = '<a href="javascript: DisplayGalleryImage('+i+')"><img src="'+iElem.src+'" width="'+iElem.width+'px" height="'+iElem.height+'px"></a>';
              } else {
                aHref.href = 'javascript: DisplayGalleryImage('+i+')'; 
              }
              delete i;      
            }
            delete sUrl;
          }
          delete iElem;
        }
        delete aHref;
      }
      if (txtdebug != '') 
        alert(txtdebug);
    }
    GalleryWasInitied = true;
  
  } catch(e) {
    alert(e.message);
  }
}

// wait function
function DoWait(millis)  {
  var date = new Date();
  var curDate = new Date(); 
  while(curDate-date < millis) {
    curDate = new Date(); 
  } 
  delete date;
  delete curDate;  
} 

// Draws basic divs for image display, draws with style.display = none
// Fills divs cache variables
function InitGalleryDiv() {
  try {
    var htm = '';
    htm += '<div id="GalleryDiv" style="display: none; margin: 0; padding: 0; position: absolute; left: 0px; top: 0px; z-index: 999; width: 100%; height: 100%; background-color: transparent; '+
           'text-align: center; ">';

    htm += '<div id="ImgDivContainer" style="position: absolute; padding: auto; margin: 0; height: auto; border: 4px '+__BorderStyle+' '+__BorderColor+'; background-color: '+__BorderColor+';">';
      htm += '<div style="width: 100%; background-color: '+__BorderColor+'; text-align: right">'+
             '<a href="" target="_Image" id="ImgNameHref" style="color: '+__BorderFontColor+'; font-family: Arial, Arial CE; font-size: 10px; float: left; text-decoration: none"></a>'+
             '<a href="javascript: CloseGalleryImage()" style="background-color: '+__BorderColor+'; color: '+__BorderFontColor+'; font-family: Arial, Arial CE; font-size: 10px; text-decoration: none; margin: 5px">Schovat</a>'+
             '</div>';
             
      htm += '<a id="ImageHref" href=""><img src="" id="AutoGalleryImage" style="width: 100%" border="0" /></a>';
    
      htm += '<div style="width: 100%; background-color: '+__BorderColor+'; margin: 0; padding: 0; height: 20px; line-height: 18px">'+
             '<a id="NextHref" href="javascript: ;" style="background-color: '+__BorderColor+'; margin: 1px; padding: 0; color: '+__BorderFontColor+'; font-family: Arial, Arial CE; font-size: 10px; text-decoration: none; float: right;">Krok &gt;&gt;</a>'+
             '<span id="ImgTitle" style="color: '+__BorderFontColor+'; font-family: Arial, Arial CE; font-size: 12px; text-decoration: none">Popis obrázku</span>'+
             '<a id="PreviousHref" href="javascript: ;" style="background-color: '+__BorderColor+'; margin: 1px; padding: 0; color: '+__BorderFontColor+'; font-family: Arial, Arial CE; font-size: 10px; text-decoration: none; float: left;">&lt;&lt; Krok</a>'+
             '</div>';

    htm += '</div>';
    
    htm += '</div>';

    htm += '<div id="BackgroundDiv" style="display: none; position: absolute; width: 100%; height: 100%; left: 0px; top: 0px; z-index: 998; background-color: #7F7F7F;'+
           '-moz-opacity:'+__TransparentLevel+';filter:alpha(opacity='+Math.round(__TransparentLevel * 100)+');opacity:'+__TransparentLevel+'; ">';
    htm += '</div>';

    document.body.innerHTML = htm + document.body.innerHTML;
    
    GalleryDiv = document.getElementById('GalleryDiv');
    ImgToDisplay = document.getElementById('AutoGalleryImage');
    ImgTitle = document.getElementById('ImgTitle');
    BackgroundDiv = document.getElementById('BackgroundDiv');
    ImgDivContainer = document.getElementById('ImgDivContainer');
    NextHref = document.getElementById('NextHref');
    PreviousHref = document.getElementById('PreviousHref');
    ImageHref = document.getElementById('ImageHref');
    ImgNameHref = document.getElementById('ImgNameHref');
    
  } catch(e) {
    GalleryDiv = null;
    alert(e.message);
  }
}

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}

function getScrollWidth() {
  var w = window.pageXOffset ||
          document.body.scrollLeft ||
          document.documentElement.scrollLeft;
          
  DebugAlerts[DebugAlerts.length] = 'getScrollWidth: ' + (w ? w : 0);
  return w ? w : 0;
} 

function getScrollHeight() {
  var h = window.pageYOffset ||
          document.body.scrollTop ||
          document.documentElement.scrollTop;

  DebugAlerts[DebugAlerts.length] = 'getScrollHeight: ' + (h ? h : 0);
  return h ? h : 0;
}

function getWindowWidth() {
  var w = window.innerWidth || 
          document.documentElement.clientWidth || 
          document.body.clientWidth;

  DebugAlerts[DebugAlerts.length] = 'getWindowWidth: ' + (w ? w : 0);
  return w ? w : 0;
}

function getWindowHeight() {
  var h = window.innerHeight || 
          document.documentElement.clientHeight || 
          document.body.clientHeight;
          
  DebugAlerts[DebugAlerts.length] = 'getWindowHeight: ' + (h ? h : 0);
  return h ? h : 0;
}

// Init gallery if not initialized
// Load image, resize image display and show image through the ContinueToDisplayImage function
function DisplayGalleryImage(Index) {
  if (Index >= 0) {

    if (Index >= ImageArray.length) Index = 0;

    if (!GalleryDiv) InitGalleryDiv();
    if (!GalleryDiv) {
      alert('Nelze!');
    }
  
    try {
      BackgroundDiv.style.width = Max(Max(document.documentElement.clientWidth, document.body.scrollWidth), document.body.clientWidth);// getScrollWidth() + getWindowWidth();
      BackgroundDiv.style.height = Max(Max(document.documentElement.clientHeight, document.body.scrollHeight), document.body.clientHeight);// getScrollHeight() + getWindowHeight();

      ImgToLoad = new Image();
      ImgToLoad.src = ImageArray[Index];
      ImgTitle.innerHTML = TitleArray[Index];
      
      if (FollowingScrollingTimeOut) 
        clearTimeout(FollowingScrollingTimeOut);
      
      ContinueToDisplayImage(1);
      
      ImgNameHref.href = ImageArray[Index];
      ImgNameHref.innerHTML = ImageArray[Index];
            
      PreviousHref.style.display = (Index > 0) ? 'block' : 'none';
      PreviousHref.href = 'javascript: DisplayGalleryImage('+(Index - 1)+');';
  
      NextHref.style.display = (Index < ImageArray.length - 1) ? 'block' : 'none';
      NextHref.href = 'javascript: DisplayGalleryImage('+(Index + 1)+');';
      ImageHref.href = 'javascript: DisplayGalleryImage('+(Index + 1)+');';
      
    } catch(e) {
      alert(e.message);
    }
    
  }
  delete Index;
}

function Min(a, b) {
  if (a > b) {
    //alert(a + ' < ' + b + ' == ' + b);
    return b
  }
  //alert(a + ' < ' + b + ' == ' + a);
  return a;
}

function Max(a, b) {
  if (a < b) return b
  return a;
}


// Waits for 1.5s to load the image, if not loaded hide image view
// Resize
function ContinueToDisplayImage(n) {
  try {
    if (!ImgToLoad) {
      delete n;
      return false;
    }
  
    if (ImgToLoad.width < 1 && n < 11) {
      setTimeout("ContinueToDisplayImage("+(n+1)+")", 150);
      delete n;
      return;

    } 
    delete n;
    
    if (!RepairScrollWidthAndHeight(true)) {
      CloseGalleryImage();
      return false;
    }
              
    ImgToDisplay.src = ImgToLoad.src;    

    BackgroundDiv.style.display = 'block';
    GalleryDiv.style.display = 'block';
    
    if (DebugAlerts && DebugAlerts.length > 0) {
     
      //var txt = DebugAlerts.join("\n");
      //alert(txt);
      while (DebugAlerts.length > 0) DebugAlerts.pop();
    
    }
    
    setTimeout("FollowingScrolling()", 10);

  } catch(e) {
    alert(e.message);
  }
}

function RepairScrollWidthAndHeight(bnForceResize) {
  try {
    while (DebugAlerts.length > 0) DebugAlerts.pop();

    var ImageWidth = Max(1, ImgToLoad.width);
    var ImageHeight = Max(1, ImgToLoad.height);
    if (ImageWidth == 1) ImageWidth = 640;
    if (ImageHeight == 1) ImageHeight = 480;

    var BodyWid = getWindowWidth();
    var BodyHei = getWindowHeight();
            
    var wid = BodyWid - 100;
    var hei = BodyHei - 100;
    
    if (ImageWidth < wid && ImageHeight < hei) {
    
      wid = ImageWidth;
      hei = ImageHeight;
      
    } 
    
    while ((wid > BodyWid - 110) || (hei > BodyHei - 110)) {
     
      if (ImageWidth > ImageHeight) {
        wid = wid - 20;
        hei = Math.round(wid * (ImageHeight / ImageWidth));
      } else {
        hei = hei - 20;
        wid = Math.round(hei * (ImageWidth / ImageHeight));
      }
      
    }
    
   
    ImgToDisplay.style.width = wid + 'px';
    ImgToDisplay.style.height = hei + 'px';
   
    wid += 10;
    hei += 50;
    ImgDivContainer.style.width = wid + 'px';
    ImgDivContainer.style.height = hei + 'px';
    
    DebugAlerts[DebugAlerts.length] = 'ImgBoxWid: ' + (wid ? wid : 0);
    DebugAlerts[DebugAlerts.length] = 'ImgBoxHei: ' + (hei ? hei : 0);
    
    var bnFaster = false;
    var ScrollTop = getScrollHeight();
    var ScrollLeft = getScrollWidth();
    
    var leftBorder = Math.round((BodyWid - wid) / 2);
    var topBorder  = Math.round((BodyHei - hei) / 2);
    DebugAlerts[DebugAlerts.length] = 'ImgBox leftBorder: ' + (leftBorder ? leftBorder : 0);
    DebugAlerts[DebugAlerts.length] = 'ImgBox topBorder: ' + (topBorder ? topBorder : 0);
        
    ImgDivContainerPosition[0] = ScrollLeft + leftBorder;
    if ((ImgDivContainerMove[0] == 0) || (ImgDivContainerMove[0] == ImgDivContainerPosition[0])) ImgDivContainerMove[0] = ImgDivContainerPosition[0];
    else {
      //Math.round
      MoveDistance = ((ImgDivContainerPosition[0] - ImgDivContainerMove[0]) * 0.04);
      if (MoveDistance == 0) 
        ImgDivContainerMove[0] += (ImgDivContainerPosition[0] < ImgDivContainerMove[0] ? -1 : 1);
      else
        ImgDivContainerMove[0] += MoveDistance;

      bnFaster = true;
    }
        
    ImgDivContainerPosition[1] = ScrollTop + topBorder; 
    if ((ImgDivContainerMove[1] == 0) || (ImgDivContainerMove[1] == ImgDivContainerPosition[1])) ImgDivContainerMove[1] = ImgDivContainerPosition[1];
    else {
      //Math.round
      MoveDistance = ((ImgDivContainerPosition[1] - ImgDivContainerMove[1]) * 0.04);
      if (MoveDistance == 0) 
        ImgDivContainerMove[1] += (ImgDivContainerPosition[1] < ImgDivContainerMove[1] ? -1 : 1);
      else
        ImgDivContainerMove[1] += MoveDistance;

      bnFaster = true;
    }
    
    if (!__AnimateImageTransfer || bnForceResize) {
      ImgDivContainerMove[0] = ImgDivContainerPosition[0];
      ImgDivContainerMove[1] = ImgDivContainerPosition[1];
      bnFaster = false;
    }
    
    ImgDivContainer.style.left = Math.round(ImgDivContainerMove[0]) + 'px';
    ImgDivContainer.style.top  = Math.round(ImgDivContainerMove[1]) + 'px';

    BackgroundDiv.style.width = '100%';
    BackgroundDiv.style.height = getDocHeight() + 'px';
    BackgroundDiv.style.left = ScrollLeft + 'px';
    BackgroundDiv.style.top  = '0px';

    LastScroll = ScrollLeft+':'+ScrollTop;
    
    if (bnFaster) 
      setTimeout("RepairScrollWidthAndHeight()", 20);

    return true; 
  } catch(e) {
    alert(e.message);
    return false;
  }
}

function FollowingScrolling() {
  if (LastScroll != getScrollWidth()+':'+getScrollHeight()) {   
    RepairScrollWidthAndHeight();

    LastScroll = getScrollWidth()+':'+getScrollHeight();
    FollowingScrollingTimeOut = setTimeout("FollowingScrolling()", 20);
  } else 
    FollowingScrollingTimeOut = setTimeout("FollowingScrolling()", 200);
}

// Hides gallery
function CloseGalleryImage() {
  ImgDivContainerMove[0] = 0;
  ImgDivContainerMove[1] = 0;
  if (GalleryDiv) {
    GalleryDiv.style.display = 'none';
    BackgroundDiv.style.display = 'none';
  }
}

// Return filename of the link
function GetFileName(AUrl) {

  if (!AUrl) {
    delete AUrl;
    return '';
  }
  
  var Ar = AUrl.toLowerCase().split('\\').join('/').split('/');
  delete AUrl;
  if (Ar.length > 0) {
    var ret = Ar[Ar.length - 1];
    delete Ar;
    return ret;
  }
  delete Ar;
  return '';
  
}

// Test wheter it is an image or not
function IsImage(AText) {

  var ret = false;
  if (AText.indexOf('.jpg') > 0) ret = true;
  else
  if (AText.indexOf('.jpeg') > 0) ret = true;
  else
  if (AText.indexOf('.gif') > 0) ret = true;
  else
  if (AText.indexOf('.png') > 0) ret = true;
  else
  if (AText.indexOf('.wmf') > 0) ret = true;
  else
  if (AText.indexOf('.bmp') > 0) ret = true;
  
  delete AText;
  return ret;

}

// Find first sub image elem
function GetSubImage(AHref) {
  
  //var ImgElem = AHref.firstChild;  
  var ImgElems = AHref.getElementsByTagName('img');
  delete AHref;

  var ImgElem = null;
  if (ImgElems.length > 0) ImgElem = ImgElems[0];
  
  if (ImgElem && ImgElem.tagName && ImgElem.tagName.toLowerCase() == 'img') {
    //if (ImgElem.src.toLowerCase().indexOf('.jpg') > 0) 
    if (IsImage(ImgElem.src.toLowerCase()))
      return ImgElem;
  }

  return false;
  
}

OtherOnLoadFunctions = document.onLoad;
document.onLoad = LaterInitAutoGallery(); 


