var historyHash = null;

function selectZIP(zipId)
{
  var zipSelectId = document.getElementById('quick_prospekt_submit_content') ? "zip-select_content" : "zip-select";
  var storeSelectId = document.getElementById('quick_prospekt_submit_content') ? "store-select_content"  : "store-select";
  
  if (document.getElementById("quick_prospekt_submit_content") != null)
  {
    $$("div.right_items div.prospekt")[0].empty();
  }
  
  if (!$(zipSelectId) && zipId == null) return
  
  var storeSelect = $(storeSelectId);
  storeSelect.empty();
  
  if ($(zipSelectId))
  {
    var value = $(zipSelectId).options[$(zipSelectId).selectedIndex].value;
  }
  else
  {
    var value = zipId;
  }
  
  var select = new Element("option", {'class' : 'first'});
  select.appendText("Standort...");
  select.value = "noselect";
  storeSelect.adopt(select);
  
  if (value != "noselect")
  {
    if ($defined(prospekte[value]))
    {
      $each(prospekte[value], function(storePathArray, storeName) {
        var select = new Element("option");
        select.appendText(storeName.replace(/__ae__/g, "ä").replace(/__ue__/g, "ü").replace(/__ss__/g, "ß").replace(/__oe__/g, "ö"));
        $each(storePathArray, function(storePath, key) {
          select.value = storePath;
        });
        storeSelect.adopt(select);
      });
    }
  }
  
  storeSelect.selectedIndex = 0;
}





function openProspect(showHint)
{
  var zipSelectId = $("quick_prospekt_submit_content") ? "zip-select_content" : "zip-select";
  var storeSelectId = $("quick_prospekt_submit_content") ? "store-select_content"  : "store-select";

	var value = $(storeSelectId).options[$(storeSelectId).selectedIndex].value;
	
	if (value != "noselect")
	{
		MOOdalBox.open(
		"/fileadmin/templates/moodalbox/hausprospekt.php?store=" + value,
		"Prospekt",
		"960 660" );
	}
	else
	{
		var zipSelect = $(zipSelectId);
		
		if (zipSelect == null)
		{
		    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie zunächst einen Standort aus.");
		}
		else
		{
			if (zipSelect.options[zipSelect.selectedIndex].value == "noselect")
			{
			   if (showHint)
			   {
			    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie zunächst einen Postleitzahlenbereich und dann einen Standort aus.");
         }
         else
         {
			    window.location.href = '/start/prospekte.html';
			   }
			}
			else
			{
			    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie noch einen Standort aus.");
			}
		}
	}
}


function initProspectList() {
  var prospectlist = $('prospectlist');
  if (!prospectlist) return;
  $each(prospekte, function(ziphouses, zip) {
    var headline = new Element('h2', {
      'text' : new String("PLZ-Gebiet " + zip + "...")
    });
    headline.inject(prospectlist);
    
    var cols = new Element('div', {'class' : 'cols-5050'});
    var colLeft = new Element('div', {'class' : 'left'});
    var colRight = new Element('div', {'class' : 'right'});
    var clearer = new Element('div', {'class' : 'clearer'});
    var hr = new Element('hr');

    var listLeft = new Element('ul');
    var listRight = new Element('ul');
    
    cols.inject(prospectlist);
    hr.inject(prospectlist);
    colLeft.inject(cols);
    colRight.inject(cols);
    clearer.inject(cols);
    
    listLeft.inject(colLeft);
    listRight.inject(colRight);

    var left = true;
    $each(ziphouses, function(housearray, houseName) {
      var house = "";
      $each(housearray, function (housePath, key)
      {
        house = housePath;
      });
      
      var li = new Element('li');
      var link = new Element('a', {'href' : 'javascript:void(0)', 'text' : houseName.replace(/__ae__/g, "ä").replace(/__ue__/g, "ü").replace(/__ss__/g, "ß").replace(/__oe__/g, "ö")  });
      link.addEvent('click', function(e) {
    		MOOdalBox.open(
    		"/fileadmin/templates/moodalbox/hausprospekt.php?store=" + house,
    		"Prospekt",
    		"960 660" );
      });
      
      link.inject(li);
      
      if (left)
      {
        li.inject(listLeft);
      }
      else
      {
        li.inject(listRight);
      }
      
      left = !left;
    });
  });
}


function initFormCheck()
{
    $$('form').each(function(formEl, index){
        formEl.addEvent('submit', (function(e)
        {
            var selects = $$(this.getElementsByTagName('select'));
            if (selects)
            {
                $each(selects, function(selectEl){
                    if (selectEl.options[selectEl.selectedIndex].value == "noselect")
                    {
                        new Event(e).stop();
                        var oldStyle = selectEl.getStyle("border");
                        selectEl.setStyle("border", "1px solid red");
                        selectEl.oldStyle = oldStyle;
                        selectEl.addEvent('change', function() {
                            if (this.oldStyle)
                                this.setStyle('border', this.oldStyle);
                        });
                        
                        alert("Das Formular konnte nicht abgeschickt werden.\nBitte wählen Sie zunächst einen Eintrag aus der Liste.");
                    }
                });
            }
            
            return true;
            
        }).bind(formEl));
    });
}



function initStartBoxes() {
  var autoDelay = 3000;
   
  var leftBox = $$('#container_start_dynamic .center_items .left');
  
  if (leftBox.length > 0)
  {
    var link = leftBox[0].getElements('h3 a')[0];
  
    makeSlideBox(link, leftBox[0]);
    
    link.autoEvent = (function() { this.fireEvent('click') }).bind(link).delay(autoDelay - 300);
  }

  var rightBox = $$('#container_start_dynamic .center_items .right');
  
  if (rightBox.length > 0)
  {
    var link = rightBox[0].getElements('h3 a')[0];
    
    makeSlideBox(link, rightBox[0]);

    link.autoEvent = (function() { this.fireEvent('click') }).bind(link).delay(autoDelay);
  }
}


function makeSlideBox(link, box)
{
  link.setProperty('href', 'javascript: void(0)');
  box.setStyle('overflow', 'hidden');
  box.primaryHeight = box.getSize().y;
  link.addEvent('click', function() {
    if ($defined(link.autoEvent))
    {
      $clear(link.autoEvent);
    }

    if (box.getSize().y > 100)
    {
      box.morph({height:28});
      link.setProperty('class', 'down');
    }
    else
    {
      box.morph({height:box.primaryHeight});
      link.setProperty('class', 'up');
    }
  });
}


function initTabBoxes() {
  var tabBoxes = $$('div.tabbox');

  if (tabBoxes.length > 0)
  {
    var tabNavigation = new Element('div', 
    {
      'class' : 'tab-navigation reiter'
    });
    
    tabNavigation.inject(tabBoxes[0], 'before');
    var tabContent = new Element('div', 
    {
      'class' : 'tab-content box_grau'
    });
    
    tabNavigation.inject(tabBoxes[0], 'before');
    
    tabContent.inject(tabBoxes[0], 'before');

    var preselectLink = null;
    
    
    tabBoxes.each(function(tabBox, index)
    {
      tabContent.grab(tabBox);
      
      var headerText = tabBox.getElements('.tabheader').get('text');
      
      tabBox.getElements('.tabheader').dispose();
      
      var header = new Element('div', 
      {
        'class' : index == 0 ? 'item current' : 'item'
      });
      
      var tabSelectorLink = new String(window.location.pathname + '#tabselector' + index);
      
      var tabLink = new Element('a', 
      {
        'text' : headerText,
        'href' : tabSelectorLink
      });
      
      tabLink.inject(header);

      if (window.location.hash && tabBox.getElements('a' + window.location.hash).length > 0 || window.location.hash == '#tabselector' + index)
      {
        preselectLink = tabLink;
      }
      
      header.inject(tabNavigation);
      
      if (index != 0)
      {
        tabBox.setStyle('display', 'none');
      }
      
      tabLink.addEvent('click', function() {
        tabBoxes.each(function(boxToHide) {
          boxToHide.setStyle('display', 'none');
        });
        tabBox.setStyle('display', 'block');
        
        tabNavigation.getElements('.current')[0].setProperty('class', 'item');
        header.setProperty('class', 'item current');
      });
      
    });
    
    if (preselectLink) {
      preselectLink.fireEvent('click');
      window.scrollTo(0,0);
    }
  }
  
}





function fadeReplaceImage(oldImage, newImage, linkTarget)
{
  newImage.setStyle('display', 'none');

  newImage.inject(oldImage.getParent(), 'bottom');
  newImage.setStyles({
    'position' : 'absolute',
    'top' : 0,
    'left' : 0,
    'opacity' : 0,
    'display' : 'inline',
    'z-index' : '17'
  });


  var effect = new Fx.Morph(newImage, {
    duration : 700,
    onComplete : function() {
      oldImage.setProperties({
        'src' : newImage.getProperty('src'),
        'title' : newImage.getProperty('title'),
        'alt' : newImage.getProperty('alt')
      });
      (function() { newImage.dispose() }).delay(250);

      var pdfLink = $('pdflink');

      if (oldImage != null && pdfLink == null && linkTarget)
      {
        pdfLink = new Element('a', {'href' : linkTarget, 'id' : 'pdflink'})
        newImage.inject(pdfLink);
        pdfLink.wraps(oldImage);
      }
      else if(linkTarget == null && pdfLink != null)
      {
        oldImage.inject(pdfLink.getParent());
        pdfLink.dispose();
      }
    }
  });

  effect.start({
  'opacity' : [0, 1]
  });
}





function initStartImage(linkList, index, productName, productDescription, imageSrc, linkTarget)
{
	  var link = new Element('a', {'href' : "javascript:void(0)", "title" : productName});
	  link.set('text', index + 1);
	  link.inject(linkList);
	  
    link.addEvent("click", (function(e)
    {
      if(!$('mb_overlay') || $('mb_overlay').getStyle('visibility') == "hidden") {
      var links = $$("div#headline div.counter a");
      
      if ($defined(e))
      {
        links.each(function(link)
        {
          if ($defined(link.autoSwitchTimer))
          {
            $clear(link.autoSwitchTimer);
          }
          if ($defined(link.autoSwitchDelayTimer))
          {
            $clear(link.autoSwitchDelayTimer);
          }
        });
      }
      
    	links.each(function(item) {
    	 item.setProperty("class", "noclass");
      });
    	
    	this.setProperty("class", "current");
    	    	
      var startImage = $$("#container_start_dynamic .magenta img")
      
      if (startImage.length == 0)
      {
        startImage = new Element('img', {'src' : imageSrc});
        
        startImage.inject($$("#container_start_dynamic .magenta")[0]);
      }
      else
      {
        startImage = startImage[0];
      }

      var preloadedImages = new Asset.images([imageSrc], {
        onComplete: function() {
          var preloadedImage = preloadedImages[0];
          preloadedImage.setProperties({
            'alt' : link.getProperty("title"), 
            'title' : link.getProperty("title") 
          }); 

          fadeReplaceImage(startImage, preloadedImage, linkTarget);

          var visibilityStyle = (linkTarget != null ? 'hidden' : 'visible');
                    
          $$('.productdetails')[0].setStyle('visibility', visibilityStyle);
        	$$('.productdetails .box .head h3')[0].set('text', productName);
        	$$('.productdetails .box .inner')[0].set('html', productDescription);
        	
        	var displayStyle = $$('.productdetails .box .inner')[0].get('text').clean() != "" ? "block" : "none";
        	
          $$('.productdetails')[0].setStyle("display", displayStyle);
        }
      });
    }}).bind(link));
}

function initStartImages() {

  var linkList = $$("div#headline div.counter");
  var productData = $('productdata');

  if (!productData || linkList.length == 0) return;
  
  linkList = linkList[0];
  
  var products = productData.getElements('div.product');
  var index = 0;
  
  $$('#startpdflinks .item').each(function(item) 
  {
	  var imageSrc = item.getElement("img").getProperty("src");
	  
	  var link = "";
	  
	  if(item.getElement("a"))
	  {
	    link = item.getElement("a").getProperty("href");
	  }
	  
	  var title = item.getElement("h4").get("html");
	  
    initStartImage(linkList, index, title, null, imageSrc, link);
    index++;	  
  });
  
	products.each(function(product)
	{
	  var productName = product.getElement("h4").get('text');
	  var productDescription = product.getElement(".inner").get('html');
	  var imageSrc = product.getElement(".imagehref").getProperty("href");
	  
    initStartImage(linkList, index, productName, productDescription, imageSrc, null);
    index++;	  
  });
  
  linkList.getElements("a")[0].fireEvent('click');
  (function () {
  linkList.getElements("a").each(function(link, index) {
    // autoswitch
    var period = 9000;
    var linkCount = $$("div#headline div.counter a").length;
    link.autoSwitchDelayTimer = (function(){ 
      link.fireEvent('click');
      link.autoSwitchTimer = (function() {
        link.fireEvent('click');
      }).periodical(linkCount * period);
    }).delay(period * index);
  });
  }).delay(2000);
}




function checkHistory() {
  if (window.historyHash != window.location.hash)
  {
    window.historyHash = window.location.hash;
    
    $$('a').each(function(link){
      if (link.getProperty('href') == new String(window.location.pathname + window.historyHash)
      || (window.location.hash == "" && link.getProperty('href') == new String(window.location.pathname + "#tabselector0")))
      {
        link.fireEvent('click');
      }
    });
  }
}




function initDescriptionToggler()
{
  var toggler = $$('.productdetails .button a');
  
  if (toggler.length == 0)
  {
    return;
  }
  else
  {
    toggler = toggler[0];
  }
  
  toggler.setProperty('href', 'javascript:void(0)');
  
  var box = $$('.productdetails')[0];
  box.setStyles({'overflow' : 'hidden'});
  box.tempHeight = box.getSize().y;
    
  toggler.addEvent('click', function(e){
    if ($defined(e))
    {
      $$("div#headline div.counter a").each(function(link)
      {
        if ($defined(link.autoSwitchTimer))
        {
          $clear(link.autoSwitchTimer);
        }
        if ($defined(link.autoSwitchDelayTimer))
        {
          $clear(link.autoSwitchDelayTimer);
        }
      });
    }    

    var minimizeHeight = 29;
    var height = minimizeHeight;
    var className = "maximize";
    var text = "+";
    
    if (box.getSize().y == minimizeHeight)
    {
      height = box.tempHeight;
      className = "minimize";
      text = "-";
    }
    
    $each([".shadow_l", ".shadow_bl"], function(className, index) {
      var el = $$(className);
      if (el.length > 0)
      {
        el = el[0];
        if (!el.tempBackground) el.tempBackground = el.getStyle('background-image');
        var bg = el.tempBackground;
        var delay = 0;
        
        if (box.getSize().y != minimizeHeight)
        {
          bg = 'none';
          delay = 500;
        }
          
        (function() { el.setStyle('background-image', bg); }).delay(delay);
      }
    });

    toggler.setProperty('class', className);
    toggler.set('text', text);
    box.morph({'height' : height});
  });
}




window.addEvent('domready', function () 
{
 // TODO: not working in >= ie6
  // initFormCheck();
  window.historyHash = window.location.hash;
  
  checkHistory.periodical(200);
  
  initTabBoxes();
  
  initStartBoxes();
  
  initDescriptionToggler();
  
  // STRETCHERS RIGHT
	var stretchToggles  = $$('div.right_items a.stretchtoggle');
	var stretchers      = $$('div.right_items div.stretcher');
	if (stretchToggles && stretchToggles.length > 0)
	{
	  if (window.location.pathname != "/" && window.location.pathname != "/start.html")
	  {
		  var accordion = new Accordion(stretchToggles, stretchers, {show: 0});
		}
	}

  // STRETCHERS CONTENT
	var stretchTogglesContent = $$('div.content_main .stretchtoggle');
	var stretchersContent     = $$('div.content_main .stretcher');
	if (stretchTogglesContent && stretchTogglesContent.length > 0)
	{
	  if (window.location.pathname != "/" && window.location.pathname != "/start.html")
	  {
		  new Accordion(stretchTogglesContent, stretchersContent, {show : 0});
		}
	}

  // SCROLLER SERVICE
	this.scrollerService = new DiomexScroller(
    $$("div#service_center div.frame")[0],
    $$("div#service_center div.frame a"),
    $$("div#service_center a.right")[0],
    $$("div#service_center a.left")[0],
	  "horizontal",
  	true,
	  false
  );

	this.scrollerService.scrollToRandom(true);
	
	// BOTTOM SCROLLER
	if ($("bottom_scroller_wrapper"))
	{
  	this.scrollerProductsBottom = new DiomexScroller(
      $$("div#bottom_scroller_wrapper div.scroller_frame")[0],
      $$("div#bottom_scroller_wrapper div.product"),
      $$("div#bottom_scroller_wrapper div#linkright")[0],
      $$("div#bottom_scroller_wrapper div#linkleft")[0],
  	  "horizontal",
    	false,
  	  false
    );
    
    this.scrollerProductsBottom.scrollMode = "page";
    
    this.scrollerProductsBottom.items.each(function(item) {
      
      var foundLink = item.getElement("a");
      
      if (foundLink && window.location.href.contains(foundLink.getProperty("href")))
      {
        this.scrollerProductsBottom.scrollTo(this.scrollerProductsBottom.items.indexOf(item) + 1, true);
      }
    });
  }
  
	if ($("right_scroller"))
	{

  	this.rightScroller = new DiomexScroller(
      $$("div#right_scroller div.scroller_frame")[0],
      $$("div#right_scroller div.product"),
      $$(".right_items .angebote. .navigation div.right a")[0],
      $$(".right_items .angebote. .navigation div.left a")[0],
  	  "horizontal",
    	false,
  	  false 
    );
  
  	this.rightScroller.scrollToRandom(true);
  }  
  
  // BLUR LINKS & SET TOP-TARGET
	var links = $$('a');
	for(var i = 0; i < links.length; i++)
	{
		links[i].onfocus = function(){this.blur();};
		if (links[i].getProperty('href') == '#top')
		{
		  links[i].setProperty('href', window.location.pathname + '#top');
    }
	}
	
  initStartImages();	

  initProspectList();

  selectZIP(null);

});





var DiomexScroller = new Class({

	initialize: function(scrollerFrame, items, linkForward, linkBackward, direction, startTicker, currentInfoElement)
	{
		this.valid = true;

		if ( scrollerFrame == null ||
		items.length == 0)
		{
			this.valid = false;
			return;
		}

		this.items = items;
		
		var contentWidth = 0;
		
    items.each(function(item) {
		  contentWidth += item.getSize().x;
		  contentWidth += item.getStyle("margin-left").toInt();
		  contentWidth += item.getStyle("margin-right").toInt();
    });
		
		this.scrollerContent = new Element("div");
		
		this.scrollerFrame = scrollerFrame;
		this.scrollerFrame.setStyle("position", "relative");
		this.scrollerContent.inject(this.scrollerFrame);
    this.items.inject(this.scrollerContent);

		if (direction == "horizontal")
		{
		  this.scrollerContent.setStyles({
		    "position" : "absolute",
		    "left" : 0,
		    "width" : contentWidth
      });
    }
    else {
		  this.scrollerContent.setStyles({
		    "position" : "absolute",
		    "top" : 0,
		    "height" : contentWidth
      });
    }
		
		this.linkForward = linkForward;
		this.linkBackward = linkBackward;
		this.direction = direction;
		this.currentInfoElement = currentInfoElement;

		this.curItem = 0;
		this.itemCount = items.length;

		this.scrollDirection = "forward";
		this.scrollMode = "item";
		this.lock = 0;
		this.ticker = null;
		this.tickerEnabled = startTicker;
		this.duration = 800;

		this.backSource;
		this.forwardSource;
		this.backImage;
		this.forwardImage;
		this.linkForward = linkForward;
		this.linkBackward = linkBackward;
		
		this.prevLeft = null;

    if (this.linkBackward && this.linkBackward.get('tag') == "a")
    {
      this.linkBackward.setProperty("href", "javascript:void(0)");
    }
    
    if (this.linkForward && this.linkForward.get('tag') == "a")
    {
      this.linkForward.setProperty("href", "javascript:void(0)");
    }

		if (this.linkBackward && this.linkBackward.getElement('img') != null)
		{
			this.backImage = this.linkBackward.getElement('img');
			this.backSource = this.backImage.getProperty("src");
		}

		if (this.linkForward && this.linkForward.getElement('img') != null)
		{
			this.forwardImage = this.linkForward.getElement('img');
			this.forwardSource = this.forwardImage.getProperty("src");
		}

		this.fx = new Fx.Morph(this.scrollerContent, {
			duration: this.duration,
			transition: Fx.Transitions.Cubic.easeInOut,

			onStart: function() {
				if (this.onScrollBegin)
				{
					this.onScrollBegin.bind(this);
					this.onScrollBegin();
				}

				this.lock = 1;
			}.bind(this),

			onComplete: (function()
			{
				this.fx.options["duration"] = this.duration;

				this.updateButtonStates();

				this.lock = 0;

				if (this.onScrollComplete)
				{
					this.onScrollComplete.bind(this);
					this.onScrollComplete();
				}

			}).bind(this)
		});

		if (this.linkForward) this.linkForward.addEvent('mouseup', (function(){ this.scroll("forward"); }).bind(this));

		if (this.linkBackward) this.linkBackward.addEvent('mouseup', (function(){ this.scroll("backward"); }).bind(this));

		if (this.linkForward)
		{
			this.linkForward.addEvent('mouseover', (function(){ this.clearTicker(); }).bind(this));
			this.linkForward.addEvent('mouseout', (function(){ this.createTicker(); }).bind(this));
		}

		if (this.linkBackward)
		{
			this.linkBackward.addEvent('mouseover', (function(){ this.clearTicker() }).bind(this));
			this.linkBackward.addEvent('mouseout', (function(){ this.createTicker() }).bind(this));
		}

		scrollerFrame.addEvent('mouseover', (function() { this.clearTicker(); }).bind(this));
		scrollerFrame.addEvent('mouseout', (function() { this.createTicker(); }).bind(this));

		this.createTicker.bind(this);
		this.createTicker();

    	this.updateButtonStates();
	},



	updateButtonStates: function()
	{
		if (this.backImage)
		{
			if (this.curItem == 0)
			{
				var newSrc = this.backSource.substr(0, this.backSource.length - 4) + "_off.png";
				this.backImage.setProperty("src", newSrc);
				this.backImage.setStyle("cursor", "default");
			}

			else
			{
				this.backImage.setProperty("src", this.backSource);
				this.backImage.setStyle("cursor", "pointer");
			}
		}

		if (this.forwardImage)
		{
			if(this.endReached())
			{
				var newSrc = this.forwardSource.substr(0, this.forwardSource.length - 4) + "_off.png";
				this.forwardImage.setProperty("src", newSrc);
				this.forwardImage.setStyle("cursor", "default");
			}

			else
			{
				this.forwardImage.setProperty("src", this.forwardSource);
				this.forwardImage.setStyle("cursor", "pointer");
			}
		}

		if (this.currentInfoElement)
		{
			this.currentInfoElement.innerHTML = (this.curItem + 1) + ' von ' + this.itemCount;
		}
	},



	endReached: function() {
		if (this.direction == "horizontal")
		{
			return this.items[this.items.length - 1].getCoordinates().right <= this.scrollerFrame.getCoordinates().right;
		}
		else
		{
			return this.items[this.items.length - 1].getCoordinates().top <= this.scrollerFrame.getCoordinates().top;
		}
	},



	scroll: function(direction) {
		if (!this.valid) return;

		if (this.lock == 1)
		{
			return;
		}

		if (direction)
		{
			this.scrollDirection = direction;
		}
		else
		{
			if (this.endReached())
			{
				this.scrollDirection =  "backward";
			}

			if (this.curItem == 0)
			{
				this.scrollDirection = "forward";
			}
		}

		if ((this.curItem == 0 && this.scrollDirection == "backward") || this.endReached() && this.scrollDirection == "forward")
		{
			return;
		}


		if(this.scrollDirection == "forward")
		{
			this.curItem ++;
		}
		else
		{
			this.curItem --;
		}


		if (this.direction == "horizontal")
		{
			var curPos = this.scrollerContent.getCoordinates().left;
			var left = 0;
			var frameWidth = this.scrollerFrame.getStyle('width').toInt();
			var leftOffSet = this.scrollerFrame.getCoordinates().left;

			var lastItem = this.items[this.items.length - 1];
			
			if (this.scrollDirection == "forward")
			{
				if (this.scrollMode == "item")
				{
					left = curPos - this.items[this.curItem].getCoordinates().left;
					this.prevLeft = null;
				}
				else if (this.scrollMode == "page")
				{

					this.prevLeft = curPos - leftOffSet;
					 
					left = curPos - frameWidth - leftOffSet;
					
					if (lastItem.getCoordinates().right - frameWidth < this.scrollerFrame.getCoordinates().right - 1)
					{
					    left = curPos - lastItem.getCoordinates().left - lastItem.getStyle('width').toInt() + frameWidth;
					}
				}
			}
			else if (this.scrollDirection == "backward")
			{
				if (this.scrollMode == "item")
				{
					left = curPos - this.items[this.curItem].getCoordinates().left;
				}
				else if (this.scrollMode == "page")
				{
					left = curPos + frameWidth - leftOffSet;
					
					if (this.prevLeft != null)
					{
						left = this.prevLeft;
						this.prevLeft = null;
					}
				}
			}

			this.fx.start({
			"left": [left]
			});
		}
		else
		{
			var curPos = this.scrollerContent.getCoordinates().top;

			if (this.scrollDirection == "forward")
			{
				this.fx.start({
				"top": [curPos - this.items[this.curItem].getCoordinates().top]
				});
			}
			else
			{
				this.fx.start({
				"top": [curPos - this.items[this.curItem].getCoordinates().top]
				});
			}
		}
	},

	scrollTo: function(index, noDuration)
	{
		if (!this.valid || this.endReached()) return;

		index -= 1;

		if (index > this.items.length - 1)
		{
			return;
		}

		if (noDuration)
		{
			this.fx.options["duration"] = 0;
		}

		var frameWidth = this.scrollerFrame.getStyle('width').toInt();
		var lastItem = this.items[this.items.length - 1];


		if (this.direction == "horizontal")
		{
  		var curPos = this.scrollerContent.getCoordinates().left;
			var itemPos = this.items[index].getCoordinates().left;

			if (this.scrollMode == "item")
			{
				var left = curPos - itemPos;
    			this.curItem  = index;
	    	}
			else
			{
				var page = (-1) * ((curPos - itemPos - 10) / frameWidth).toInt();
				var left = curPos - frameWidth * page - this.scrollerFrame.getCoordinates().left;
				
				if (lastItem.getCoordinates().right - frameWidth * page < this.scrollerFrame.getCoordinates().right - 1)
				{
					this.prevLeft = left + frameWidth;
	
				    left = curPos - lastItem.getCoordinates().left - lastItem.getStyle('width').toInt() + frameWidth;
				}
				
				this.curItem = page;
		}

		this.fx.start({
			"left": [left]
			});
		}
		else
		{
			var curPos = this.scrollerContent.getCoordinates().top;
			var top = curPos - this.items[index].getCoordinates().top;

		    this.curItem = index;
		    
			this.fx.start({
			"top": [top]
			});
		}

	},


	scrollToRandom: function(noDuration)
	{
		if (!this.valid) return;

		this.scrollTo($random(1, this.itemCount).toInt(), noDuration);
	},


	clearTicker: function() {
		if (this.ticker)
		{
			$clear(this.ticker);
			this.ticker = null;
		}
	},


	createTicker: function() {
		if (this.ticker == null && this.tickerEnabled)
		{
			this.ticker = this.tickerFunction.periodical(12000, this);
		}
	},

	tickerFunction: function()
	{
		if (!this.tickerEnabled)
		{
			this.clearTicker();
			return;
		}

		if (this.curItem <= 0)
		{
			this.scrollDirection = "forward";
		}

		if (this.endReached())
		{
			this.scrollDirection = "backward";
		}

		this.scroll();
	}
});



function debugOut(message)
{
	var debugBox = $('debugBox');
	
	if (!debugBox) return;
		
	debugBox.setStyles(
	{
		'position'  :'absolute',
		'bottom' : '0px',
		'right' : '0px',
		'z-index' : '999',
		'width' : '300px',
		'height' : '200px',
		'opacity' : '0.7',
		'background-color' : '#ffffff',
		'border' : '1px solid #bbbbbb',
		'padding' : '10px',
		'overflow' : 'auto'
	});        
	
	debugBox.inject($$('body')[0]);
	
	debugBox.grab(new Element('p', {text: message}), 'top');
}