/*
  Author: Techocraft, Uroš Renko
  Dependencies: Prototype library 1.6+
*/

var TcSlideShow = Class.create(
{
  
  frequency:        4, // seconds
  containerID:      "div#content-panel-inner",

	initialize: function()
  {	
    this._Create();
  },

  findChildElementById: function(el, id)
  {
    $A(el.childNodes).each(
      function(item)
      {
        if (item.attributes!=null)
        {
          var i = Element.readAttribute($(item),'id');
          if (i==id)
          {
            objTcSlideShow.CurrentImage = item;
            return;
          }
        }
      }
    );
  },
  
  ImageOnLoad: function()
  {
    var _content = $$(objTcSlideShow.containerID);
    if (_content=="")
    {
      return;
    } else
    {
      _content = _content[0];
    }
    if (_content)
    {
      _content.innerHTML = objTcSlideShow.Response.innerHTML;
    }
  },
  
  CurrentImage: 'undefined',
  Response: 'undefined',
  
  dataUpdater: function(transport)
  {
    if ((transport.responseText=="\n") || (transport.responseText==""))
    {
      return;
    }
    var _obj = $(document.createElement("div"));
    _obj.innerHTML = transport.responseText;
    objTcSlideShow.Response = _obj;
    objTcSlideShow.findChildElementById(_obj, 'news-image');
    if (objTcSlideShow.CurrentImage)
    {
      var _img_obj = new Image();
      _img_obj.onload = objTcSlideShow.ImageOnLoad;
      _img_obj.src = objTcSlideShow.CurrentImage.src;
    }
  },
  
  linksArray: 'undefined',
  linksCount: function()
  {
    if (objTcSlideShow.linksArray=='undefined')
    {
      return 0;
    } else
    {
      return objTcSlideShow.linksArray.length;
    }
  },
  linksCurrent: -1,

  slideShow: function()
  {
    var i;
    if (objTcSlideShow.linksArray=='undefined')
    {
       var linksArray = $$('input.slideshow');
       if (linksArray=='undefined')
       {
         i = -1;
         return;
       } else
       {
         objTcSlideShow.linksArray = linksArray;
         i = 1;
       }
    } else
    {
      i = objTcSlideShow.linksCurrent;
    }
    c = objTcSlideShow.linksCount();
    if ((i>-1) && (c>0))
    {
      var nextLink = objTcSlideShow.linksArray[i].value;
      var myAjax = new Ajax.Request( '/slide/' + nextLink, { method: 'post', parameters: '', onSuccess: objTcSlideShow.dataUpdater });
      i = i + 1;
      if (i>=c)
      {
        i = 0;
      }
      objTcSlideShow.linksCurrent = i;
    }
  },

  _Create: function()
  {
  },

	_Destroy: function()
  {
  }

});

function TcSlideShowInit()
{ 
  objTcSlideShow = new TcSlideShow();
  new PeriodicalExecuter(objTcSlideShow.slideShow, objTcSlideShow.frequency);
}

Event.observe(window, 'load', TcSlideShowInit, false);

