var Site = {
	
	start: function(){
		if ($('display')) Site.fadeImages();
		if ($('arbeitsplattenSortiment')) Site.showChooser();
		if ($('frontenToggle')) Site.toggleFrontenMenu();
		if ($('arbeitsplattenToggle')) Site.toggleArbeitsplattenMenu();
		if ($('arbeitsplattenToggle')) Site.showArbeitsplattenCategory();
		if ($('frontenToggle')) Site.showFrontenCategory();
	  if ($('dealers')) Site.showDealers();
	  if ($('muster-toggle')) Site.showMusterBestellung();
	  if ($('submit')) Site.validateForm();
	  // Offerte
	  if ($('featureIcons')) Site.mouseoverMenus();
		if ($('info')) Site.toolTips();
		// Dealers
		if ($('scrollArea')) Site.scrollButtons();
	},
	
	fadeImages: function() {
    var imageHolder = $('display');	
		var thumbs = $$('.thumbs a');
		var timeFade = 450;
		var contentDiv = $('content');
		// var loader =$('loader');
		// 
		// loader.style.visibility="hidden";
		 
		var timer = 0; 
		var thumbInfo= $('info');
		
		infoFxs = new Fx.Style(thumbInfo, 'left', {
			duration: 1200,
			transition: Fx.Transitions.backOut,
			wait: false
		});
  },
  
  popUpSample: function(el){
    // var url = el.href;
    // var sample = window.open(el.href, 'muster', "width=380, height=380, location=0, menubar=0");
    // sample.document.title = "New Title"
    
    sample = window.open('', el.title,'height=400,width=400');
    var tmp = sample.document;
    tmp.write('<html><head><title>Worky | ' + el.title + '</title>');
    tmp.write('<link rel="stylesheet" href="/stylesheets/sample.css">');
    tmp.write('</head><body>');
    tmp.write('<div id="sample"><img src="' + el.href + '" /></div>');
    tmp.write('</body></html>');
    tmp.close();
  },
  
  fadePhoto: function(el, url) {
    var picTitle = el.firstChild.alt
    var picClass = el.className
    
    var imageHolder = $('display');	
		var timeFade = 450;
		var contentDiv = $('content');
    
    //function that changes image
    function changeImage(picURL, picClass, picTitle){								
			imgPreloader = new Image();				
			imgPreloader.onload = function(){ //once the image is loaded:
			  // var loadingStatus = loader.style.visibility;
				// if (loadingStatus == "visible") {loader.style.visibility = "hidden";} // Hide the loading text
				var newImage = new Element('img').injectInside(contentDiv);
    		var imageFade = newImage.effect('opacity',{duration:timeFade}); //create effect 
				newImage.setStyle('opacity', '0');
				newImage.setProperty('src', picURL);
				newImage.setProperty('id', picTitle);
				newImage.addClass(picClass);
				imageFade.custom(0,1);// fade the image back to 100%			
			}
			imgPreloader.src = picURL;
			var imgComplete = imgPreloader.complete;				
			// if (!imgComplete){
			//	loader.style.visibility="visible"; // show some text saying "loading"
			// }
		}
      
   // var imageFadeMouseOver = imageHolder.effect('opacity',{duration:timeFade, onComplete:function(){changeImage(picURL);}});
		// imageFadeMouseOver.custom(1,0);
		changeImage(url, picClass, picTitle);
  },
  
  showChooser: function() {
    var el = $('frontenList');
    var chooserLink = $('fronten');
    var chooserCloser = $('arbeitsplatten');
    var timer = 0;
    el.setStyle('display', 'block');
    
    slideFxs = new Fx.Style(el, 'left', {
			duration: 1200,
			transition: Fx.Transitions.backOut,
			wait: false
		});
    
    chooserLink.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      infoFxs.start.delay(timer, infoFxs, 270); // Closes the info element. Need to make sure that it is open first. 
      slideFxs.start.delay(timer, slideFxs, 1);
      chooserLink.setStyle('background-position','0 -24px');
      chooserCloser.setStyle('background-position','0 0');    
      
      $('search_form').setStyle('display','none');  
      $('fronten_search_form').setStyle('display','block'); 
    });
    chooserCloser.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      infoFxs.start.delay(timer, infoFxs, 270); // Closes the info element. Need to make sure that it is open first. 
      slideFxs.start.delay(timer, slideFxs, 270);
  
      chooserLink.setStyle('background-position','0 0');
      chooserCloser.setStyle('background-position','0 -24px'); 
      
      $('search_form').setStyle('display','block');  
      $('fronten_search_form').setStyle('display','none');
    });
  },
  
  showArbeitsplattenCategory: function() {
    var catLinks = $$('#arbeitsplattenMenu a');
    var menu = $('arbeitsplattenMenu');
    var container = $('arbeitsplattenThumbnails');
    
    catLinks.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      var catName = this.title;
      var catUrl = this.href
      var thumbContainer = $(catName);
      var timer = 0

      menu.setStyle('display','none');
      
      // Moves the thumbnails to the right and hides them
      var pos = container.getStyle('left');
      slideInFx = new Fx.Style(container, 'left', {
  			duration: 1200,
  			transition: Fx.Transitions.backOut,
  			wait: false
  		});
  		slideOutFx = new Fx.Style(container, 'left', {
    		duration: 1200,
    		transition: Fx.Transitions.backOut,
    		wait: false
    	});
      // alert(pos);
      if (pos == '0px'){
        // First hides the element
        slideInFx.start.delay(timer, slideInFx, 270);
        // Shows the element again after a delay. Ajax update goes here
        var ajaxRequest = new Ajax(catUrl, {
        	method: 'get',
        	update: container,
        	onComplete: function(){
        	  slideOutFx.start.delay(500, slideOutFx, 0);
        	}
        });
        (function(){ajaxRequest.request();}).delay(1000);
      }
      //if (pos != '0px'){slideOutFx.start.delay(timer, slideOutFx, 0);}   
    });
  },
  
  showFrontenCategory: function() {
    var catLinks = $$('#frontenMenu a');
    var menu = $('frontenMenu');
    var container = $('frontenThumbnails')
    container.setStyles({
      'left':'24px',
      'position':'absolute',
      'width':'230px'
    })
  
    catLinks.addEvent('click', function(e) {
      e = new Event(e).stop();
      
      var catName = this.title;
      var catUrl = this.href
      // var thumbContainer = $(catName);
      var timer = 0
      
      menu.setStyle('display','none');
      
      // Moves the thumbnails to the right and hides them
      var pos = container.getStyle('left');
      slideInFx = new Fx.Style(container, 'left', {
  			duration: 1200,
  			transition: Fx.Transitions.backOut,
  			wait: false
  		});
  		slideOutFx = new Fx.Style(container, 'left', {
    		duration: 1200,
    		transition: Fx.Transitions.backOut,
    		wait: false
    	});
      // alert(pos);
      if (pos == '24px'){
        // First hides the element
        slideInFx.start.delay(timer, slideInFx, 270);
        // Shows the element again after a delay. Ajax update goes here
        var ajaxRequest = new Ajax(catUrl, {
        	method: 'get',
        	update: container, 
        	onComplete: function(){
        	  slideOutFx.start.delay(500, slideOutFx, 24);
        	}
        });
        (function(){ajaxRequest.request();}).delay(1000);
      }
      //if (pos != '0px'){slideOutFx.start.delay(timer, slideOutFx, 0);}        
    });
  },
  
  toggleFrontenMenu: function() {
    var toggle = $('frontenToggle');
    var container = $('frontenSortiment');
    var menu = $('frontenMenu');
    
    menu.setStyle('display','none');
    
    // Controls "fronten" menu
    toggle.addEvent('mouseenter', function(e) {
      menu.setStyle('display','block');
    });
    container.addEvent('mouseleave', function(e) {
      menu.setStyle('display', 'none')
    });
  },
  
  toggleArbeitsplattenMenu: function() {    
    var toggle1 = $('arbeitsplattenToggle');
    var container1 = $('arbeitsplattenSortiment');
    var menu1 = $('arbeitsplattenMenu');

    menu1.setStyle('display','none');
    
    // Controls "arbeitsplatten" menu
    toggle1.addEvent('mouseenter', function(e) {
      menu1.setStyle('display','block');
    });
    container1.addEvent('mouseleave', function(e) {
      menu1.setStyle('display', 'none')
    });
  },
  
  showInfo: function(el) {
    var url = el.href;
    new Ajax(url, {
    	method: 'get',
    	update: $('info'),
    	onComplete: function(){
    	  infoFxs.start.delay('500', infoFxs, 1); 
    	  // $('lawyer_colors').setStyle('display', 'block');
    	}
    }).request();
  
  },
  
  hideInfo: function(el) {
    // alert(el.href);
    var container = $('info');
    var timer = 0;
    testFxs = new Fx.Style(container, 'left', {
			duration: 1200,
			transition: Fx.Transitions.backOut,
			wait: false
		});
		testFxs.start.delay(timer, testFxs, 270);
		// $('lawyer_colors').setStyle('display', 'none');     
  },
  
  showDealers: function() {
    var links = $$('ul#dealers a');
    
    links.addEvent('click', function(e) {
      e = new Event(e).stop();
      url = this.href;

      new Ajax(url, {
      	method: 'get',
      	update: $('dealerInfo')
      }).request();
    });
  },
  
  showMusterBestellung: function() {
    var toggle = $('muster-toggle');
    var closer = $('close')
    var bestellForm = $('muster-bestellung');
    
    toggle.addEvent('click', function(e) {
      bestellForm.style.visibility="visible";
    }); 
    
    closer.addEvent('click', function(e) {
      bestellForm.style.visibility="hidden";
    });
  }, 
  
  
  mouseoverMenus: function() {
    var buttons = $$('#featureIcons img');
    var featureLists = $$('.featuresMenu')
    var featureBoxes = $$('.feature')
    var links = $$('.featuresMenu a')
    
    featureLists.each(function(item){
      item.addEvent('mouseleave', function() {
        var parent = item.parentNode;
        parent.setStyle('z-index','10');
        item.setStyle('display','none');
      });
    });
    
    featureBoxes.each(function(item){
      item.addEvent('mouseleave', function() {
        var menus = $$(this.getElementsByTagName('p'));
        menus.each(function(menu){
          // alert(item.className)
          menu.setStyle('display','none');
        });
        item.setStyle('z-index','10');
      });
    });
    
    links.addEvent('click', function(link) {
      var parent = this.parentNode
      var grandparent = parent.parentNode

      var localLinks = $$(parent.getElementsByTagName('a'));
      // This will need to be changed to get just the buttons in the active element.
      localLinks.each(function(element){
        element.removeClass('active')
      });
      
      var name = this.className;
      if (grandparent.id == "winkel_2"){
        name = name + "_right";
      };
      newSrc = "/images/offerte/" + name + ".png"
      images = $$(grandparent.getElementsByTagName('img'));
      images.each(function(image) {
        image.setProperty('src', newSrc);
      });
      this.addClass('active');
      
      var fields = $$(grandparent.getElementsByTagName('input'));
      fields.each(function(item){
        item.setProperty('value', name)
        // alert(item.value);
      });
      parent.setStyle('display','none');
    });
    
    buttons.each(function(item){
      item.addEvent('mouseover', function() {
        var parent = item.parentNode;
        parent.setStyle('z-index','10000');
        var menus = $$(parent.getElementsByTagName('p'));
        menus.each(function(item){
          item.setStyles({
            'display':'block',
            'z-index':'10001'
          })
        });
      });
    });
    
  },
  
  toolTips: function() {
    // Tooltips
    var buttons = $$('.tooltip')
    
    // buttons.each(function() {
    //   alert(this.className + " reporting, Sir!");
    // });
    
    var Tips1 = new Tips(buttons, {
      timeOut: 700,
    	maxTitleChars: 50, /*I like my captions a little long*/
    	maxOpacity: .9 /*let's leave a little transparancy in there */
    });
  },
  
  validateForm: function() {
  	var fields = $$(".required");
    var counter = 0;
  	var errors = Array();
  	var button = $('submit');
    
  	button.addEvent('click', function(e) {
      
      fields.each(function(f) {
    	  var labelName = f.id + '_p'
        if (f.value.length == 0) {
          errors[counter] = f;
    			$(labelName).setStyle('color', 'red');
    			counter = counter + 1;
    			e = new Event(e).stop();
    		} else {
    			$(labelName).style.color = "#fff";
    		};
      });
    });

  },
  scrollButtons: function(){ 
 	  var textarea = $('scrollArea');
 	  var content = $('dealers');
 	  var scrollControls = $('scroll-controls');

 	  var upButton = $('scroll-up');
 	  var downButton = $('scroll-down');

 	  var pos1 = 0;

 	  upButton.setStyle('cursor','pointer');
 	  downButton.setStyle('cursor','pointer');

 	  contentHeight = content.offsetHeight;
 	  textHeight = textarea.offsetHeight;
 	  offset = contentHeight-textHeight;


 	  function getHeight() {
     	return textarea.offsetHeight;
     }

 	  function scrolldown(speed) {
 	    //alert(parseInt(textarea.getStyle('top')) - parseInt(speed) + 'px')
     	if ( getHeight() + parseInt(textarea.getStyle('top')) > contentHeight ) {
     		textarea.setStyle('top', parseInt(textarea.getStyle('top')) - 1 + 'px');
     	}
     }

     function scrollup(speed) {
       // alert(parseInt(textarea.getStyle('top')) + parseInt(speed) + 'px')
     	if ( parseInt(textarea.getStyle('top')) < 0 ) {
     		textarea.setStyle('top', parseInt(textarea.getStyle('top')) + 1 + 'px');
     	}
     }

     function fastscrolldown(speed) {
     	if ( getHeight() + parseInt(textarea.getStyle('top')) > contentHeight ) {
     		textarea.setStyle('top', parseInt(textarea.getStyle('top')) - 5 + 'px');
     	}
     }

     function fastscrollup(speed) {
     	if ( parseInt(textarea.getStyle('top')) < 0 ) {
     		textarea.setStyle('top', parseInt(textarea.getStyle('top')) + 5 + 'px');
     	}
     }
     function stopscroll() {
       // alert('Scroll Stop');
       $clear(periodical);
     }

     function faststopscroll() {
       $clear(periodical);
       $clear(fastperiodical);
     }

 	  if(offset < 0){
 	    scrollControls.setStyle('display','block');

 	    upButton.addEvent('mouseover', function() {
   	    //alert('This moves up');
   	    scrollup(1);
   	    periodical = scrollup.periodical(1);
   	  });
   	  upButton.addEvent('mousedown', function() {
   	    fastscrollup(5);
         fastperiodical = fastscrollup.periodical(1);
   	  });
   	  upButton.addEvent('mouseout', function() {
   	    stopscroll();
   	  });
   	  upButton.addEvent('mouseup', function() {
   	    faststopscroll();
   	  });

   	  downButton.addEvent('mouseover', function() {
   	    //alert('This moves down');
   	    scrolldown(1);
   	    periodical = scrolldown.periodical(1);
   	  });
   	  downButton.addEvent('mousedown', function() {
   	     fastscrolldown(5);
   	     fastperiodical = fastscrolldown.periodical(1);
   	  });
   	  downButton.addEvent('mouseout', function() {
   	    stopscroll();
   	  });
   	  downButton.addEvent('mouseup', function() {
   	    faststopscroll();
   	  });

 	  };
 	}
};


window.addEvent('load', Site.start);
