var companyOfStore = {
  2 : 1,
  5 : 1,
  6 : 1,
  8 : 1,
  9 : 1,
  112 : 10, 
  113 : 10, 
  114 : 10, 
  115 : 10, 
  116 : 10, 
  117 : 10, 
  118 : 10, 
  119 : 10, 
  121 : 10,
  703 : 70, 
  704 : 70, 
  705 : 70, 
  706 : 70, 
  707 : 70, 
  708 : 70, 
  720 : 70, 
  721 : 70, 
  752 : 70, 
  753 : 70 
}



function initNewsletterStoreSelector() {

  var store = $('tx-sremailsubscribe-pi1-building');
  var company = $('tx-sremailsubscribe-pi1-company');
  
  if (store && company)
  {
    store.addEvent('change', function()
    {
      var storeID = store.getProperty('value');
      
      if (storeID)
      {
        storeID = storeID.toInt();
        company.setProperty('value', companyOfStore[storeID]);
      }
      else
      {
        company.setProperty('value', '');
      }
    });
  }
  
}


function initRoomPlannerSelector()
{
    var roomSelect = $('roomplannerroom-select');

    if (roomSelect)
    {
        if (document.URL.contains("/wohnen"))
        {
            roomSelect.selectedIndex = 1;
        }
        if (document.URL.contains("/polster"))
        {
            roomSelect.selectedIndex = 1;
        }
        if (document.URL.contains("/schlafen"))
        {
            roomSelect.selectedIndex = 2;
        }
        if (document.URL.contains("/kueche"))
        {
            roomSelect.selectedIndex = 3;
        }
        if (document.URL.contains("/speisen"))
        {
            roomSelect.selectedIndex = 4;
        }
        if (document.URL.contains("/bad"))
        {
            roomSelect.selectedIndex = 5;
        }
        if (document.URL.contains("/kinder-jugend"))
        {
            roomSelect.selectedIndex = 6;
        }
        if (document.URL.contains("/baby"))
        {
            roomSelect.selectedIndex = 7;
        }
        if (document.URL.contains("/arbeit-buero"))
        {
            roomSelect.selectedIndex = 8;
        }
    }
}


function initStartProspectSelector()
{
        var button = $("openStartProspect");

        if (button == null)
        {
            return;
        }
        
        var boxWrapper = $('startProspectBox');
        var box = $$('#startProspectBox div.prospekt_box_inner')[0];
        var bg = $$('#startProspectBox div.prospekt_box_bg')[0];
        
        box.setStyle("opacity", "0");
        bg.setStyle("opacity", "0");
        boxWrapper.setStyle('display', 'none');
        
        button.addEvent("click", function(e){
          boxWrapper.setStyle('display', 'block');
			     bg.setStyle("visibility", "visible");
	        box.setStyle("visibility", "visible");

            var opacity = box.getStyle("opacity");

            var newOpacity = 1;
            var newBgOpacity = 0.8;
            var newBoxWrapperDisplayStyle = "none";

            if (opacity == 1)
            {
                var newBgOpacity = 0;
                var newOpacity = 0;
                
                button.setProperty("class", null);
            }
            else
            {
                button.setProperty("class", "active");
                newBoxWrapperDisplayStyle = "block";
            }

    		var morph = new Fx.Styles(box, {
    			duration: 500,
    			transition: Fx.Transitions.Cubic.easeInOut,
    			onComplete : function() { boxWrapper.setStyle('display', newBoxWrapperDisplayStyle)}
    			}
    		);

    		var morphBg = new Fx.Styles(bg, {
    			duration: 500,
    			transition: Fx.Transitions.Cubic.easeInOut
    			}
    		);
    		
    		morph.start({
                "opacity" : [newOpacity]
    		});

    		morphBg.start({
                "opacity" : [newBgOpacity]
    		});
    	});
}


function selectStore(storeId)
{
if (!$('store-select') && storeId == null) return
	
    var prospectSelect = $('prospect-select');
    prospectSelect.empty();

	if ($('store-select'))
	{
		var value = $('store-select').options[$('store-select').selectedIndex].value;
	}
	else
	{
		var value = storeId;
	}

    
    var select = new Element("option");
    select.appendText("Prospekt wählen...");
    select.value = "noselect";
    select.inject(prospectSelect);

	if (value != "noselect")
	{
	    if ($defined(prospekte[value]))
	    {
	        $each(prospekte[value], function(prospectPath, prospectName) {
	                var select = new Element("option");
	                select.appendText(prospectName);
	                select.value = prospectPath;
	                select.inject(prospectSelect);
	        });
	    }
	}
	
	prospectSelect.selectedIndex = 0;
}

function openProspect()
{
	var value = $('prospect-select').options[$('prospect-select').selectedIndex].value;
	
	if (value != "noselect")
	{
		MOOdalBox.open(
		"/fileadmin/frame-hausprospekt.php?store=" + value,
		"Prospekt",
		"960 680" );
	}
	else
	{
		var storeSelect = $('store-select');
		
		if (storeSelect == null)
		{
		    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie zunächst einen Prospekt aus.");
		}
		else
		{
			if (storeSelect.options[storeSelect.selectedIndex].value == "noselect")
			{
			    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie zunächst ein Einrichtungshaus und dann einen Prospekt aus.");
			}
			else
			{
			    alert("Der Prospekt konnte nicht angezeigt werden.\nWählen Sie noch einen Prospekt aus.");
			}
		}
	}
}


function initProspectList() {
  var prospectlist = $('prospectlist');
  if (!prospectlist) return;
  $each(prospekte, function(prospects, house) {
    var headline = new Element('h2');
    headline.appendText(house.replace(/__ae__/g, "ä").replace(/__ue__/g, "ü").replace(/__ss__/g, "ß").replace(/__oe__/g, "ö"));
    
    headline.inject(prospectlist);
    
    var hr = new Element('hr');
    var list = new Element('ul');
    
    list.inject(prospectlist);
    hr.inject(prospectlist);
    
    $each(prospects, function(prospectPath, prospectName) {
      var li = new Element('li');
      var link = new Element('a', {'href' : 'javascript:void(0)'});
      link.appendText(prospectName);
      link.addEvent('click', function(e) {
    		MOOdalBox.open(
    		"/fileadmin/frame-hausprospekt.php?store=" + prospectPath,
    		"Prospekt",
    		"960 660" );
      });
      
      link.inject(li);
      li.inject(list);
    });
  });
}



function openRoomPlanner()
{
	var value = $('roomplannerroom-select').options[$('roomplannerroom-select').selectedIndex].value;

	if (value != "noselect")
	{
		MOOdalBox.open(
		"/fileadmin/frame-raumplaner.php?room=" + roomplannerGuids[value],
		"Raumplaner",
		"1100 760" );
	}
	else
	{
		alert("Der Raumplaner konnte nicht gestartet werden.\nWählen Sie zunächst eine Vorlage aus.");
	}
}


function initFormCheck()
{
    var forms = $$('form');
    $each(forms, function(form){
        form.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(form));
    });
}


window.addEvent('domready', function () {

	selectStore(null);
	
	initFormCheck();
	
	initStartProspectSelector();
  
  initRoomPlannerSelector();

  initNewsletterStoreSelector();  
	
	var scrollerPmenuFrame = $('scroller_pmenu');
	var scrollerPmenuContent = $$('#scroller_pmenu .scroller_content');
	var scrollerPmenuItems = $$('#scroller_pmenu ul');

	$('scroller_pmenu').setStyle("visibility", "hidden");
	$$(".pmenu_more")[0].setStyle("visibility", "hidden");

	this.pmenuScroller = new DiomexScroller(
    scrollerPmenuFrame,
	scrollerPmenuItems,
	scrollerPmenuContent[0],
	null,
	null,
	"horizontal",
	false,
	null);
	this.pmenuScroller.scrollMode = "page";
	this.pmenuScroller.onScrollComplete = function()
	{
		scrollerPmenuFrame.setStyle("visibility", "visible");
		$$(".pmenu_more")[0].setStyle("visibility", "visible");

		if (this.curItem == 0)
		{
			$$(".pmenu_more")[0].innerHTML = "...weiter";
		}
		else
		{
			$$(".pmenu_more")[0].innerHTML = "...zur&uuml;ck";
		}
	};
	if ($$(".pmenu_page2 .cursub").length > 0 || $$(".pmenu_page2 .sub").length > 0 || $$(".pmenu_page2 .current").length > 0 || $$(".pmenu_page2 .actsub").length > 0)
	{
		this.pmenuScroller.fx.options["duration"] = 0;
		this.pmenuScroller.scroll();
	}
	else
	{
		$$(".pmenu_more")[0].innerHTML = "...weiter";
		scrollerPmenuFrame.setStyle("visibility", "visible");
		$$(".pmenu_more")[0].setStyle("visibility", "visible");
	}


	var scrollerContent = $$('#bottom_scroller_wrapper div.scroller_content');
	var products        = $$('#bottom_scroller_wrapper div.scroller_content div.product');
	var scrollerFrame   = $$('#bottom_scroller_wrapper div.scroller_frame');
	var linkRight       = $('linkright');
	var linkLeft        = $('linkleft');

	this.bottomScroller = new DiomexScroller( scrollerFrame[0],
	products,
	scrollerContent[0],
	linkRight,
	linkLeft,
	"horizontal",
	true,
	null );

	var scrollerContentRight = $$('#right_scroller div.scroller_content');
	var scrollerFrameRight   = $$('#right_scroller div.scroller_frame');
	var productsRight          = $$('#right_scroller div.scroller_frame div.product');
	var linkUp               = $$('div.button_up');
	var linkDown             = $$('div.button_down');

	this.rightScroller = new DiomexScroller( scrollerFrameRight[0],
	productsRight,
	scrollerContentRight[0],
	linkDown[0],
	linkUp[0],
	"vertical",
	false,
	$$("#right_scroller .current_info")[0] );

	this.rightScroller.scrollToRandom(true);


	var newsLetterNameField = $('tx-sremailsubscribe-pi1-first_name');
	if (newsLetterNameField != null)
	{
		newsLetterNameField.focus();
	}


	var stretchToggles  = $$('div.right_items a.stretchtoggle');
	var stretchers      = $$('div.right_items div.stretcher');
	if (stretchToggles && stretchToggles.length > 0)
	{
		var accordion = new Accordion(stretchToggles, stretchers, {show: 99});

	}

	var salesContractsStretchToggles  = $$('div#sales_contracts div.stretchtoggle');
	var salesContractsStretchers      = $$('div#sales_contracts div.stretcher');
	if (salesContractsStretchToggles && salesContractsStretchers.length > 0)
	{
		var accordionSalesContracts = new Accordion(salesContractsStretchToggles, salesContractsStretchers, {show: 99});

	}

	var links = $$('a');
	for(var i = 0; i < links.length; i++)
	{
		links[i].onfocus = function(){this.blur();};
	}

  initProspectList();
});





var DiomexScroller = new Class({

	initialize: function(scrollerFrame, items, scrollerContent, linkForward, linkBackward, direction, startTicker, currentInfoElement)
	{
		this.valid = true;

		if ( scrollerFrame == null ||
		items.length == 0 ||
		scrollerContent == null)
		{
			this.valid = false;
			return;
		}

		this.items = items;
		this.scrollerContent = scrollerContent;
		this.scrollerFrame = scrollerFrame;
		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.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.Styles(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();
	}
});

