// name: auto galerie
// author: Semerad Vaclav gurroa@gurroa.cz
// copyright: Medisoft (c) 2009

// settings

var __BorderColor = '#404040';
var __BorderFontColor = 'white';
var __BorderStyle = 'solid';
var __TransparentLevel = 0.65;
var __AnimateImageTransfer = false;


// Basic variables
var OtherOnLoadFunctions = null;
var ImageArray = new Array();
var SmallArray = new Array();
var ImgToLoad = null;
var DebugAlerts = new Array();


// Divs cache variables
var GalleryDiv = null;
var ImgToDisplay = 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);

// 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 {

    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; 
              aHref.href = 'javascript: DisplayGalleryImage('+i+')';
              aHref.target = '';
              delete i;      
            }
            delete sUrl;
          }
          delete iElem;
        }
        delete aHref;
      }
      if (txtdebug != '') 
        alert(txtdebug);
    }
  
  } 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; 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: 20px; 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 CE, Arial; font-size: 10px; float: left; text-decoration: none"></a>'+
             '<a href="javascript:CloseGalleryImage()" style="background-color: '+__BorderColor+'; color: '+__BorderFontColor+'; font-family: Arial CE, Arial; 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: 15px">'+
             '<a id="NextHref" href="javascript: ;" style="background-color: '+__BorderColor+'; margin: 1px; padding: 0; color: '+__BorderFontColor+'; font-family: Arial CE, Arial; font-size: 10px; text-decoration: none; float: right;">Krok &gt;&gt;</a>'+
             '<a id="PreviousHref" href="javascript: ;" style="background-color: '+__BorderColor+'; margin: 1px; padding: 0; color: '+__BorderFontColor+'; font-family: Arial CE, Arial; 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: 43; background-color: #7F7F7F;'+
           '-moz-opacity:'+__TransparentLevel+';filter:alpha(opacity='+Math.round(__TransparentLevel * 100)+');opacity:'+__TransparentLevel+'; ">';
    htm += '</div>';

    document.body.innerHTML = document.body.innerHTML + htm;
    
    GalleryDiv = document.getElementById('GalleryDiv');
    ImgToDisplay = document.getElementById('AutoGalleryImage');
    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 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];
      
      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()) {
      CloseGalleryImage();
      return false;
    }
              
    ImgToDisplay.src = ImgToLoad.src;

    BackgroundDiv.style.display = 'block';
    GalleryDiv.style.display = 'block';
    
    if (DebugAlerts && DebugAlerts.length > 0) {
     
      //alert(DebugAlerts.join("\n"));
      while (DebugAlerts.length > 0)
        DebugAlerts.pop();
    
    }
    
    setTimeout("FollowingScrolling()", 100);

  } catch(e) {
    alert(e.message);
  }
}

function RepairScrollWidthAndHeight() {
  try {
    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 += 30;
    ImgDivContainer.style.width = wid + 'px';
    ImgDivContainer.style.height = hei + 'px';
    
    var bnFaster = false;
        
    ImgDivContainerPosition[0] = getScrollWidth() + Math.round((BodyWid - wid) / 2);
    if ((ImgDivContainerMove[0] == 0) || (ImgDivContainerMove[0] == ImgDivContainerPosition[0])) ImgDivContainerMove[0] = ImgDivContainerPosition[0];
    else {
      ImgDivContainerMove[0] += Math.round((ImgDivContainerPosition[0] - ImgDivContainerMove[0]) * 0.15);
      bnFaster = true;
    }
        
    ImgDivContainerPosition[1] = getScrollHeight() + Math.round((BodyHei - hei) / 2); 
    if ((ImgDivContainerMove[1] == 0) || (ImgDivContainerMove[1] == ImgDivContainerPosition[1])) ImgDivContainerMove[1] = ImgDivContainerPosition[1];
    else {
      ImgDivContainerMove[1] += Math.round((ImgDivContainerPosition[1] - ImgDivContainerMove[1]) * 0.15);
      bnFaster = true;
    }
    
    if (!__AnimateImageTransfer) {
      ImgDivContainerMove[0] = ImgDivContainerPosition[0];
      ImgDivContainerMove[1] = ImgDivContainerPosition[1];
      bnFaster = false;
    }
    
    ImgDivContainer.style.left = ImgDivContainerMove[0] + 'px';
    ImgDivContainer.style.top  = ImgDivContainerMove[1] + 'px';

    LastScroll = getScrollWidth()+':'+getScrollHeight();
    
    if (bnFaster) 
      setTimeout("RepairScrollWidthAndHeight()", 50);

    return true; 
  } catch(e) {
    alert(e.message);
    return false;
  }
}

function FollowingScrolling() {
  if (LastScroll != getScrollWidth()+':'+getScrollHeight()) {   
    RepairScrollWidthAndHeight();

    LastScroll = getScrollWidth()+':'+getScrollHeight();
    FollowingScrollingTimeOut = setTimeout("FollowingScrolling()", 50);
  } 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 null;
  
}

OtherOnLoadFunctions = document.onLoad;
document.onLoad = LaterInitAutoGallery(); 


