// **********************************************************************************************
// Random-Image-Function
// **********************************************************************************************
// Global Variables
var objLastPosition = new Array();
var gIntervalState = 0;

// Dynamic Change of random images
function DynamicRandomImage(pUniqueKey, pImgName, pInterval, pImagePath, pDynamic, pImageFading, pCaption, pAlttext, pCurrentImageIndex)
{
  // new DynamicRandomImage( 
  // pUniqueKey = "26", 
  // pUrl = "typo3conf/ext/thme_randomimage/pi1/randomimage.php", 
  // pImgName = "dif5ae5bda6ddf967ba1e30cae72eb84f2", 
  // pInterval = 5000, 
  // pImagePath= "fileadmin/templates/random/", 
  // pImageCount = 1, 
  // pDynamic = 1,  
  // pImageFading = '1', 
  // pCaption = '', 
  // pAlttext = '', 
  // pCurrentImageIndex = 0).randomize();
  this.uniqueKey = pUniqueKey;
  this.url = "typo3conf/ext/thme_randomimage/pi1/randomimage.php";
  this.imgName = pImgName;
  this.interval = pInterval;
  this.imagePath = pImagePath;
  this.bigImagePath = '';
  this.imageCount = 1;
  this.dynamic = pDynamic;
  this.recursive = 0;
  this.ignore = '';
  this.ignoreFolder = '';
  this.ignoreFile = '';
  this.sort = 0;
  this.sortorder = 1;
  this.sortOnDynamicChange = 0;
  this.imageMaxW = '0';
  this.imageMaxH = '0';
  this.bigImageMaxW = '0';
  this.bigImageMaxH = '0';
  this.imageFading = pImageFading;
  this.imagemagick = 0;
  this.debug = 0;
  this.caption = pCaption;
  this.alttext = pAlttext;
  this.link = '0';
  this.imParams = '';
  this.bigImageImParams = '';
  this.imCommand = '';
  this.imCommandParams = '';
  this.bigImageImCommand = '';
  this.bigImageImCommandParams = '';
  this.currentImageIndex = pCurrentImageIndex;
  this.tempImage = null;
  this.newCaption = null;
  this.a = -1;

  this.arrImg = new Array(1);
  this.arrLinks = new Array(1);
  this.arrCaptions = new Array(1);
  this.arrFadings = new Array(1);
  this.arrAlts = new Array(1);
  this.imgNumber = 0;
  this.zufallsZahl = 0;
  this.xmlhttp = GetXMLObject();

  DynamicRandomImage.prototype.randomize = function()
  {
    var thisObject = this;

    // get random image number to replace
    var a = Math.random();
    a *= thisObject.imageCount;
    a = Math.ceil(a);
    if (a == thisObject.zufallsZahl) {if (a+1 > thisObject.imageCount) {a = 1;} else {a++;}};

    if (gIntervalState == 0)
    {
      if (this.imgNumber != 0) {if (this.imgNumber > this.imageCount) {this.imgNumber = 1;}}
      if (this.imgNumber == 0)
      {
        var urlArgs = this.url + "?uniqueKey=" + this.uniqueKey + "&path=" + this.imagePath + "&bigImagePath=" + this.bigImagePath + "&count=" + this.imageCount + "&dynamic=" + this.dynamic + "&recursive=" + this.recursive + "&ignore=" + this.ignore + "&ignorefolder=" + this.ignoreFolder + "&ignorefile=" + this.ignoreFile + "&sort=" + this.sort + "&sortorder=" + this.sortorder + "&sortOnDynamicChange=" + this.sortOnDynamicChange + "&imw=" & this.imageMaxW + "&imh=" + this.imageMaxH + "&bmw=" + this.bigImageMaxW + "&bmh=" + this.bigImageMaxH + "&im=" + this.imagemagick + "&caption=" + escape(this.arrCaptions[a-1]) + "&link=" + escape(this.arrLinks[a-1]) + "&alt=" + escape(this.arrAlts[a-1]) + "&imparams=" + escape(this.imParams).replace(/\+/g,"%2B") + "&biimparams=" + escape(this.bigImageImParams).replace(/\+/g,"%2B") + "&imcommand=" + escape(this.imCommand).replace(/\+/g,"%2B") + "&imcommandparams=" + escape(this.imCommandParams).replace(/\+/g,"%2B") + "&biimcommand=" + escape(this.bigImageImCommand).replace(/\+/g,"%2B") + "&biimcommandparams=" + escape(this.bigImageImCommandParams).replace(/\+/g,"%2B") + "&curindex=" + this.currentImageIndex + "&t=" + new Date().getTime();
      }
      else
      {
        var urlArgs = this.url + "?uniqueKey=" + this.uniqueKey + "&path=" + this.imagePath + "&bigImagePath=" + this.bigImagePath + "&count=1" +                  "&dynamic=" + this.dynamic + "&recursive=" + this.recursive + "&ignore=" + this.ignore + "&ignorefolder=" + this.ignoreFolder + "&ignorefile=" + this.ignoreFile + "&sort=" + this.sort + "&sortorder=" + this.sortorder + "&sortOnDynamicChange=" + this.sortOnDynamicChange + "&imw=" + this.imageMaxW + "&imh=" + this.imageMaxH + "&bmw=" + this.bigImageMaxW + "&bmh=" + this.bigImageMaxH + "&im=" + this.imagemagick + "&caption=" + escape(this.arrCaptions[a-1]) + "&link=" + escape(this.arrLinks[a-1]) + "&alt=" + escape(this.arrAlts[a-1]) + "&imparams=" + escape(this.imParams).replace(/\+/g,"%2B") + "&biimparams=" + escape(this.bigImageImParams).replace(/\+/g,"%2B") + "&imcommand=" + escape(this.imCommand).replace(/\+/g,"%2B") + "&imcommandparams=" + escape(this.imCommandParams).replace(/\+/g,"%2B") + "&biimcommand=" + escape(this.bigImageImCommand).replace(/\+/g,"%2B") + "&biimcommandparams=" + escape(this.bigImageImCommandParams).replace(/\+/g,"%2B") + "&curindex=" + this.currentImageIndex + "&t=" + new Date().getTime();
      }
      for (var i = 1; i <= this.imageCount; i++) {urlArgs = urlArgs + "&img" + i + "=" + this.arrImg[i-1];}

      try
      {
          if (this.imgNumber != 0)
          {
            // get one new random image
            this.xmlhttp.open("GET", urlArgs, true);
            this.xmlhttp.onreadystatechange = function()
            {
              if (thisObject.xmlhttp.readyState == 4)
              {
                var xmlResponse = thisObject.xmlhttp.responseText;
                
                if (xmlResponse != '')
                {
                  // take image informations in variables
                  var arrTemp = xmlResponse.split("x;x");
                  thisObject.a = a;
                  thisObject.tempImage = new Image();
                  thisObject.tempImage.src = arrTemp[1];

                  // Setting new Caption of the image in object variable
                  if (document.getElementById('cap_'.concat(thisObject.imgName).concat(thisObject.a)) != null)
                  {
                    var strCaption = arrTemp[4].toString().replace('\n', '').replace('\r', '');
                    if (strCaption != '')
                    {
                      thisObject.newCaption = strCaption;
                    }
                    else
                    {
                      thisObject.newCaption = thisObject.arrCaptions[thisObject.a-1];
                    }
                  }
                  
                  // replace image source of current image
                  thisObject.tempImage.load = thisObject.loadCompleted();
                  
                  // Write filename of bigimage to div
                  if (document.getElementById('bi_'.concat(thisObject.imgName).concat('_').concat(a)) != null)
                  {
                    document.getElementById('bi_'.concat(thisObject.imgName).concat('_').concat(a)).innerHTML = arrTemp[2];
                  }
                  
                  // Write new href in link around the image
                  if (document.getElementById('lnk_'.concat(thisObject.imgName).concat(a)) != null)
                  {
                    strLink = arrTemp[3].toString().replace('\n', '').replace('\r', '');
                    strTarget = '';
                    var arrLink = strLink.split(' ');
                    if (arrLink.length > 1) {strLink = arrLink[0]; strTarget = arrLink[1];} else {strLink = arrLink[0]; strTarget = '';}
                    
                    if (strLink != '')
                    {
                      document.getElementById('lnk_'.concat(thisObject.imgName).concat(a)).href = strLink;
                      document.getElementById('lnk_'.concat(thisObject.imgName).concat(a)).target = strTarget;
                    }
                    else
                    {
                      var arrLink = thisObject.arrLinks[a-1].split(" ");
                      if (arrLink.length > 1) {strLink = arrLink[0]; strTarget = arrLink[1];} else {strLink = arrLink[0]; strTarget = '';}
                      document.getElementById('lnk_'.concat(thisObject.imgName).concat(a)).href = strLink;
                      document.getElementById('lnk_'.concat(thisObject.imgName).concat(a)).target = strTarget;
                    }
                  }
                  
                  document.getElementById(thisObject.imgName.concat(a)).alt = arrTemp[5];
                  document.getElementById(thisObject.imgName.concat(a)).title = '';
                  
                  // set new current image index
                  thisObject.currentImageIndex = arrTemp[6];

                  // update current image array
                  thisObject.arrImg[a-1] = arrTemp[0];
                  thisObject.imgNumber = a;
                  thisObject.zufallsZahl = a;
                }
              }
            }
            this.xmlhttp.send(null)
          }
          else
          {
            // first time -> save current images, captions and links in array
            var arrCap = this.caption.split('x;x');
            var arrLnk = this.link.split('x;x');
            var arrFad = this.imageFading.split('x;x');
            var arrAlt = this.alttext.split('x;x');

            for (var i=0; i < this.imageCount; i++)
            {
              // Images
              var img = document.getElementById("fi_".concat(this.imgName).concat("_").concat(i+1)).innerHTML.toString();
              this.arrImg[i] = img;

              // Fadings
              if (arrFad[i] == null) {arrFad[i] = 0;}
              this.arrFadings[i] = arrFad[i];

              // Links
              if (arrLnk[i] == null) {arrLnk[i] = '';}
              this.arrLinks[i] = arrLnk[i];
              
              // Captions
              if (arrCap[i] == null) {arrCap[i] = '';}
              this.arrCaptions[i] = arrCap[i];

              // Alttext
              if (arrAlt[i] == null) {arrAlt[i] = '';}
              this.arrAlts[i] = arrAlt[i];
            }

            this.imgNumber++;
          }
      }
      catch(e)
      {
        this.writeDebugInfo('Exception: ' + e);
      }
    }
    window.setTimeout( function () { thisObject.randomize(); }, this.interval);
  }
  
  // Write Debug-Information
  DynamicRandomImage.prototype.writeDebugInfo = function(strMessage)
  {
    if (this.debug == 1)
    {
      var objDebug = document.getElementById('randomimages_debug');
      if (objDebug != null)
      {
        var dtmDate = new Date();
        var hour = dtmDate.getHours(); if (hour < 10) {hour = '0' + hour};
        var minute = dtmDate.getMinutes(); if (minute < 10) {minute = '0' + minute};
        var second = dtmDate.getSeconds(); if (second < 10) {second = '0' + second};
        var strTime = hour + ':' + minute + ':' + second;
        objDebug.innerHTML = objDebug.innerHTML.toString() + strTime + '<br />' + strMessage + '<br /><br />';
      }
    }  
  }
  
  // Image Loading Completed function
  DynamicRandomImage.prototype.loadCompleted = function()
  {
    if (this.tempImage.complete == false)
    {
      var thisObject = this;
      setTimeout(function() { thisObject.loadCompleted() }, 50);
      return (false);
    }
    if (document.getElementById(this.imgName.concat(this.a)))
    {
      if (document.getElementById('cap_' + this.imgName.concat(this.a)) != null)
      {
        document.getElementById('cap_' + this.imgName.concat(this.a)).innerHTML = this.newCaption;
      }

      if (this.arrFadings[this.a-1] == 0)
      {
        document.getElementById(this.imgName.concat(this.a)).src = this.tempImage.src;
      }

      document.getElementById(this.imgName.concat(this.a)).width = this.tempImage.width;
      document.getElementById(this.imgName.concat(this.a)).height = this.tempImage.height;

      // Set position of div and start fading
      if (this.arrFadings[this.a-1] == 1)
      {
        // Get caption width and height, if caption exists
        var captionHeight = 0;
        var captionWidth = 0;
        if (document.getElementById('cap_' + this.imgName.concat(this.a)) != null)
        {
          captionHeight = RandomImage_GetCurrentStyle(document.getElementById('cap_' + this.imgName.concat(this.a)), 'height').replace('px', '').replace('auto', '');
          captionWidth = RandomImage_GetCurrentStyle(document.getElementById('cap_' + this.imgName.concat(this.a)), 'width').replace('px', '').replace('auto', '');
        }
        if (captionHeight == '') {captionHeight = 0;}
        if (captionWidth == '') {captionWidth = 0;}

        // Calculate width and height of fading div
        var fadingWidth = this.tempImage.width;
        var fadingHeight = this.tempImage.height;
        if (eval(captionWidth) > eval(fadingWidth)) {fadingWidth = captionWidth;}
        fadingHeight = eval(fadingHeight) + eval(captionHeight);

        // Set position and width and height of fading div
        document.getElementById('fd_' + this.imgName + '_' + this.a).style.width = fadingWidth + 'px';
        document.getElementById('fd_' + this.imgName + '_' + this.a).style.height = fadingHeight + 'px';
        document.getElementById('fd_' + this.imgName + '_' + this.a).left = document.getElementById(this.imgName.concat(this.a)).offsetLeft + 'px';
        document.getElementById('fd_' + this.imgName + '_' + this.a).top = document.getElementById(this.imgName.concat(this.a)).offsetTop + 'px';

        this.milliSec = 1000;
        this.fade();
      }
      
    }
  }
  
  // initialization of fading in new image
  DynamicRandomImage.prototype.fade = function()
  { 
    if (document.getElementById('cap_' + this.imgName.concat(this.a)) != null)
    {
      this.writeDebugInfo('Old Caption: ' + document.getElementById('cap_' + this.imgName.concat(this.a)).innerHTML);
      this.writeDebugInfo('New Caption: ' + this.newCaption);
    }

    //set the current image as background 
    document.getElementById('fd_' + this.imgName + '_' + this.a).style.backgroundImage = 'url(' + document.getElementById(this.imgName.concat(this.a)).src + ')'; 

    //start fading
    var thisObject = this;
    setTimeout(function() { thisObject.fadeChange() }, 50);
  } 
  
  // fading in new image
  DynamicRandomImage.prototype.fadeChange = function()
  {
    //make image and caption transparent 
    RandomImage_ChangeOpac(0, this.imgName.concat(this.a)); 
    if (document.getElementById('cap_' + this.imgName.concat(this.a)) != null)
    {
      RandomImage_ChangeOpac(0, 'cap_' + this.imgName.concat(this.a)); 
    }

    var thisObject = this;
    setTimeout(function() { thisObject.fadeIt() }, 50);
  }
  
  DynamicRandomImage.prototype.fadeIt = function()
  {
    var speed = Math.round(this.milliSec / 100); 
    var timer = 0; 

    //make new image
    document.getElementById(this.imgName.concat(this.a)).src = this.tempImage.src; 
    
    //make new caption
    if (document.getElementById('cap_'.concat(this.imgName.concat(this.a))) != null)
    {
      document.getElementById('cap_' + this.imgName.concat(this.a)).innerHTML = this.newCaption;
    }

    //fade in image and caption
    for(i = 0; i <= 100; i++)
    { 
      setTimeout("RandomImage_ChangeOpac(" + i + ",'" + this.imgName.concat(this.a) + "','" + 'cap_' + this.imgName.concat(this.a) + "')",(timer * speed)); 
      timer++;
    }
  }
    
  // Get xml object (crossbrowser valid)
  function GetXMLObject()
  {
    var xmlhttp=false;
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
    if (!xmlhttp && typeof XMLHttpRequest!="undefined") {
      try {
        xmlhttp = new XMLHttpRequest();
      } catch (e) {
        xmlhttp=false;
      }
    }
    if (!xmlhttp && window.createRequest) {
      try {
        xmlhttp = window.createRequest();
      } catch (e) {
        xmlhttp=false;
      }
    }
    return xmlhttp;
  }  
}

// Helper: find x-position of a object
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}


// Helper: find y-position of a object
function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

// Helper: change the opacity for different browsers 
function RandomImage_ChangeOpac(opacity, id, id2)
{ 
    if ((opacity/100) > 0.99) {return (false);}
    var object = document.getElementById(id).style; 
    object.filter = "alpha(opacity=" + opacity + ")";
    object.KhtmlOpacity = (opacity / 100); 
    object.MozOpacity = (opacity / 100); 
    object.opacity = (opacity / 100); 
    
    if (id2 != null)
    {
      if (document.getElementById(id2) != null)
      {
        var object = document.getElementById(id2).style; 
        object.filter = "alpha(opacity=" + opacity + ")";
        object.KhtmlOpacity = (opacity / 100); 
        object.MozOpacity = (opacity / 100); 
        object.opacity = (opacity / 100); 
      }
    }
}

// Helper: get style of an element
function RandomImage_GetCurrentStyle (objElement, cssPropertyName)
{
  if (window.getComputedStyle)
  {
    return window.getComputedStyle(objElement, '').getPropertyValue(cssPropertyName.replace(/([A-Z])/g, "-$1").toLowerCase());
  }
  else if (objElement.currentStyle)
  {
    return objElement.currentStyle[cssPropertyName];
  }
  else
  {
    return '';
  }
}

