//—Copyright (c) 2007 wollzelle GmbH, (http://www.wollzelle.com). All Rights Reserved.

if(Prototype.Browser.IE){
  try {
    document.execCommand("BackgroundImageCache", false, true);
  } catch(e) {}
}

var Site = {
  MIN_WIDTH:        600,
  MIN_HEIGHT:       453,
  MAX_HEIGHT:       790,
  MAX_WIDTH:        1045,
  MAX_PAGE_HEIGHT:  1024,
  MAX_PAGE_WIDTH:   1280,
  
  initialize: function() {
    this.logo           = $('logo');
    this.container      = $('container');
    this.navigation     = $('navigation');
    this.lightbox       = $('lightbox');
    this.curtain        = $('curtain_white');
    this.thumbs         = $('thumbs');
    this.thumbsCurtain  = $('thumbs_curtain');
    this.currentSection = $('section_beauty');
    this.impressumOpen  = false;
    this.lbSpinner      = new Spinner('lightbox_spinner', 12);
    this.curtainBlackOpen = false;
    this.activeBiography = 'en';
    
    if(Prototype.Browser.Gecko) {
      $('active_item_indicator').setStyle({top:'16px'});
      $$('div.contact').invoke('setStyle', {top:'-300px'});
    }
        
    $('link_en').addClassName(Prototype.Browser.IE ? 'active_ie' : 'active');
        
    Site.registerEvents();
    
    this.SCALE   = this.MAX_WIDTH/this.MAX_HEIGHT;
    this.H_SCALE = this.MAX_WIDTH/this.MAX_PAGE_WIDTH;
    this.V_SCALE = this.MAX_HEIGHT/this.MAX_PAGE_HEIGHT;

    this.oneMoreScale = true;

		if (screen.width >= 1024 && screen.height >= 768) {
			$('openInPopup').show();
		}
    
    //if (Prototype.Browser.IE && screen.width <= 1024 && screen.height <= 768)
    //  this.viewFullscreen();
    
    Site.loadClientLists();
    Site.resize();
  },
  
  resize: function() {
    pageSize = Position.getPageSize();

    if(pageSize.page.width < 900 || pageSize.page.height < (Prototype.Browser.IE ? 630 : 635))
			$('error_message').show();
		else
			$('error_message').hide();
			
    var width = (pageSize.page.width*this.H_SCALE);
    var height = (pageSize.page.height*this.V_SCALE);
		
    var sizeFromHeight = {
      width: height*this.SCALE,
      height: height
    }
    var sizeFromWidth = {
      width:width,
      height: width/this.SCALE
    }
    
    var height = (sizeFromHeight.width < sizeFromWidth.width) ? sizeFromHeight.height.round() : sizeFromWidth.height.round();
    var width = (sizeFromHeight.width < sizeFromWidth.width) ? sizeFromHeight.width.round() : sizeFromWidth.width.round();
		            
    if(height >= this.MAX_HEIGHT && width >= this.MAX_WIDTH) { 
      height = this.MAX_HEIGHT;
      width = this.MAX_WIDTH;
    }
              
    if(height <= this.MIN_HEIGHT && width <= this.MIN_WIDTH) {
      height = this.MIN_HEIGHT;
      width = this.MIN_WIDTH;
    }          
                          
    marginLeft = -(width/2).round()-20; //20px border
    marginTop = -(height/2).round()-21; //21: +1px for our special friend IE
    
    navigationTopMarginOffset = (Prototype.Browser.IE ? 20 : (Prototype.Browser.Gecko ? 15 : 12));
        
    this.logo.setStyle({marginTop:marginTop-16+'px', marginLeft:marginLeft+20+'px'});
    this.navigation.setStyle({marginTop:marginTop-navigationTopMarginOffset+'px', marginRight:marginLeft-(Prototype.Browser.IE ? 22 : -8)+'px'});
        
    this.container.setStyle({width:width+'px', height:height+'px', marginLeft:marginLeft+'px', marginTop:marginTop+35+'px'});
    this.lightbox.makeClipping().setStyle({height:(height*0.85-40).round()+'px'});
      
    this.curtain.setStyle({width:(this.lightbox.getWidth()+20)+'px'});
    this.thumbs.setStyle({height:(height*0.15-20).round()+'px'});
    
    if(Prototype.Browser.IE) {
      this.thumbs.down('div.clip-region').makeClipping().setStyle({width:width+'px'});
    }
    
    this.thumbsCurtain.setStyle({width:this.lightbox.getWidth()+(Prototype.Browser.IE ? 45 : 40)+'px', height:(height*0.15-20).round()+'px'});
    
    if(!this.curtainBlackOpen) {
      // do not resize height, when curtain_black is open
      $('curtain_black').setStyle({height:this.thumbs.getHeight()+'px'});
    }
    if(this.curtainBlackOpen) $('curtain_black').setStyle({marginTop:(Site.thumbs.getHeight())+'px'});
    $('curtain_black').setStyle({top:this.container.offsetTop+this.container.getHeight()-this.thumbs.getHeight()+'px'});
    
    $('permanent_legal_notice').setStyle({marginLeft:(-width/2)+'px', marginTop:'5px', width:width+'px'});
    $('content_contact').setStyle({marginLeft:width-195+'px'});
    $('content_impressum').setStyle({marginLeft:width-195+'px'});
    
    if(this.impressumOpen) {
      // corrects offset between two divs onresize (only when impressum is open)
      var resizeCorrector = $('content_contact').offsetLeft;
      var originalLeft = parseInt($('content_contact').getStyle('left'));
      var resizedLeft = originalLeft-resizeCorrector+20;
      $('content_contact').setStyle({left:resizedLeft+'px'});
    }
    $('spinner').setStyle({marginTop:(this.thumbs.getHeight()/2)+'px'});
    
    // margin between client list cols
    
    if(pageSize.page.width < 1100 || pageSize.page.height < 760) {
      var correctedWidth = Prototype.Browser.IE ? '145px' : '170px';
      $$('div#section_clients ul').invoke('setStyle', {width:correctedWidth});
      var marginVariator = 20;
    }
    else {
      $$('div#section_clients ul)').invoke('setStyle', {width:'180px'});
      var marginVariator = 0;
    }
    
    $$('div#section_clients ul:not([class=first])').invoke('setStyle', {marginLeft:((width-4*180)/3+marginVariator)+'px'});
    
    $$('div.section').each(function(section){
      section.setStyle({width:width+41+'px', height:(height-this.thumbs.getHeight()+43)+'px', marginLeft:marginLeft+'px', marginTop:marginTop+'px'});
    }.bind(this));
     
    $$('.resizeable').each(function(image) {
      Site.resizeImage(image);
    });
        
    if(Lightbox.beautyThumbs)
      Lightbox.beautyThumbs.resize();
    
    var canvasHeight = $('canvas').up('.parent').getHeight();
    var canvasWidth = (canvasHeight*(1005.0/632.0)).round();
    
    $('canvas').setStyle({width:canvasWidth+'px', height:canvasHeight+'px', marginLeft:-(canvasWidth/2)+'px'});
    $('caption').setStyle({width:canvasWidth+'px', marginLeft:-(canvasWidth/2)+'px'});
    
    // top offset of paragraphs
    var bioTop = canvasHeight-(canvasHeight/3-80-20);

    $('bio_en', 'bio_de').invoke('setStyle', { 
      top: bioTop+'px', 
      width: canvasWidth + 38 + 'px' 
    });
        
    $('language').setStyle({
      top: bioTop + 70 + 'px',
      width: canvasWidth + 38 + 'px'
    });
    
    if (Prototype.Browser.IE)
      $('language', 'bio_en', 'bio_de').invoke('setStyle', {
        left: '50%',
        marginLeft: -canvasWidth/2 - 24 + 'px'
      });
    
    $('biography_photo').setStyle({width:(canvasWidth+40)+'px', height:(canvasHeight)+'px', marginTop:'20px'});
    if (Prototype.Browser.IE) {      
      if ($('biography_photo').__filter || /empty\.gif$/.test($('biography_photo').src)) return;
      $('biography_photo').style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$('biography_photo').src+"',sizingMethod='scale')";
      $('biography_photo').src = 'images/empty.gif';      
      $('biography_photo').__filter = true;
    }
    
    Canvas.resize();
    
    window.scrollTo(0,0);
  },
  
  resizeImage: function(image) {
    var scale, variator, thumb = false;
    if(image.hasClassName('wide')) { thumb = true; scale = 1005.0/632.0; variator = 0; }
    if(image.hasClassName('thumb')) { thumb = true; scale = 77.0/100.0; variator = 20.0; }
    if(image.hasClassName('thumb-semi')) { thumb = true; scale = 118.0/100.0; variator = 20.0; }
    if(image.hasClassName('thumb-wide')) { thumb = true; scale = 159.0/100.0; variator = 20.0; }
    if(image.hasClassName('thumb-extra-wide')) { thumb = true; scale = 201.0/100.0; variator = 20.0; }
        
    var height = image.up('div.parent').getHeight()-variator;
    var width = (height*scale).round();
    
    if(!image.__src) image.__src = image.src;
    
    if (thumb && Prototype.Browser.IE) {      
      if (image.__filter || /empty\.gif$/.test(image.src)) return;
      image.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+image.src+"',sizingMethod='scale')";
      image.src = 'images/empty.gif';      
      image.__filter = true;
    }
    
    image.width = width; image.height = height;
  },
  
  registerEvents: function() {
    Event.observe(window, 'resize', function() {
      Site.resize();
    }.bind(this));
  },
  
  loadClientLists: function() {
    var maxPerList = 18;
    var lists = $$('div#section_clients ul');
    var file = Prototype.Browser.WebKit ? 'clients.php' : 'clients.txt';
    new Ajax.Request('content/'+file, {
      method: 'get',
      onSuccess: function(transport) {        
        var sanitizedList = transport.responseText;
        var lines = sanitizedList.split('\n');
        lists.each(function(list) {
          var counter = 0;
          while(counter <= maxPerList) {
            if(lines.length == 0)
              break;
            var li = new Element('li');
            line = lines.shift();
            
            li.innerHTML = line;
            list.appendChild(li);
            line.length > 30 ? counter += 2 : counter++;
          }
        });
        
      }
    });
  },

  showBiography: function(language) { // 'en' || 'de'
    if (this.activeBiography == language) return;
    
    $('bio_'+this.activeBiography).morph('opacity:0.001');
    $('bio_'+language).morph('opacity:0.999');
    
    var className = Prototype.Browser.IE ? 'active_ie' : 'active';
    
    $('link_'+this.activeBiography).removeClassName(className);
    $('link_'+language).addClassName(className);
    
    this.activeBiography = language;
  },

  showContentSection: function(section_name) {
    section = $('section_'+section_name);

    if(this.currentSection == section) return;

    if(this.currentSection)
			this.currentSection.fade();
			
    if(Lightbox.beautyThumbs)
			Lightbox.beautyThumbs.flyOut();
			
    this.slideOutThumbs();
		section.appear({duration:1.0, afterFinish: function() {
			// after content appeared, hide the lightbox stuff so that fading
			// between content sections doesn't show lightbox
			this.hideLightbox();
			if(section_name == 'about') Site.resize(); //needed to get proper offsetHeight of #bio_en
    }.bind(this)});
		this.currentSection = section;
		this.currentLightbox = null;
  },

	showLightboxSection: function(section_name) {
		section = $('section_'+section_name);
		
		this.showLightbox();
		
    if(this.currentSection)
			this.currentSection.fade();
			
		this.currentSection = null;
		this.currentLightbox = section_name;
		
		Lightbox.beautyThumbs.changeItems('items' + section_name.capitalize(), this.thumbsVisible());
		
		this.slideInThumbs();
	},
	
	hideLightbox: function() {
    this.lightbox.setOpacity(0.001);
    if (Prototype.Browser.IE) $('canvas').setOpacity(0);
		this.container.setStyle({background:'#000'});
		$('caption').setOpacity(0.001);
	},
	
	showLightbox: function() {
		// before fading away a content section, restore the view of the lightbox
    this.lightbox.setOpacity(0.999);
		if (Prototype.Browser.IE) $('canvas').setOpacity(1);
		this.container.setStyle({background:'#fff'});
		$('caption').setOpacity(0.999);
	},
  
  slideInThumbs: function() {
    if(this.curtainBlackOpen) return;
    $('curtain_black').morph('margin-top:'+(Site.thumbs.getHeight())+'px; height:15px;', {
      afterFinish: function(effect) {
        effect.element.setStyle({backgroundColor:'transparent'});
      }
    }); // 15px: stops Safari 2.0 from unwanted resize
    this.curtainBlackOpen = true;
  },
  
  slideOutThumbs: function() {
    $('curtain_black').morph('margin-top:0; height:'+
    Site.thumbs.getHeight()+'px', {duration:0.5, delay:1.0, beforeStart: function(effect) {
      effect.element.setStyle({backgroundColor:'#000'});
    }});
    Lightbox.riseThumbs();
    this.curtainBlackOpen = false;
  },

	// checks wether the thumbs are visible or the curtain is before them
	thumbsVisible: function() {
		return parseInt($('curtain_black').getStyle('margin-top')) != 0;
	},
  
  goHome: function() {
    if(Lightbox.beautyThumbs)
      Lightbox.beautyThumbs.flyOut();
    Menu.hideIndicator();

    this.displayRandomImage();
    
		this.showLightbox();
    if(this.currentSection) {
      this.currentSection.fade();
      this.currentSection = null;
    }
		
    Site.slideOutThumbs();
  },
  
  displayRandomImage: function(dontFade) {
    image = this.randomImage(true);
		highRes = image.image_url.gsub('-low','');
		Loader.load(image.image_url,{
			onComplete: function() {
	    	Lightbox.swapImages({image_url:image.image_url, captionText:image.caption,
													 captionAlignment:image.alignment, dontFade:dontFade, queue: {scope: 'highresload', position:'end'}});			
			}
		});
										
    if(Prototype.Browser.IE)
      $('lightbox_spinner_wrapper').show();
    else
      $('lightbox_spinner_wrapper').appear({duration:1.5, queue: {scope:'lbspinner', limit:2}});

    Loader.load(highRes, { onComplete: function() {
    	Lightbox.swapImages({image_url:highRes, captionText:image.caption,
    											 captionAlignment:image.alignment, queue: {scope: 'highresload', position:'end'}});      
      if(Prototype.Browser.IE)
        $('lightbox_spinner_wrapper').hide();
      else
        $('lightbox_spinner_wrapper').fade({duration:1.5, queue: {scope:'lbspinner', limit:2, position:'end'}});
    }});
    Lightbox.currentImage = image;
  },

	randomImage: function() {
	  //returns low version of image if arguments[0] true
	  
    var random = (Math.random()*10).round();
    var randomImage = (random % 3)+1;

    var imageCaptions = ['Christof Wagner', 'Thomas Schauer', 'Christof Wagner'];
    var alignments = ['left', 'left', 'left'];
    /* currently inactive, Sarira wants only 1 image to be displayed
		return { image_url:'images/random/'+randomImage+(arguments[0] ? '-low' : '')+'.jpg',
		 				 caption: 'photographed by '+imageCaptions[randomImage-1],
						 alignment: alignments[randomImage-1] };
	  */
	  return { image_url: 'images/random/4'+(arguments[0] ? '-low' : '')+'.jpg',
	           caption: 'photographed by Thomas Schauer',
	           alignment: 'left' };
	  
	},
  
  toggleImpressum: function() {
    if(!this.impressumOpen) {
      $('content_contact').morph('left:-'+($('content_contact').offsetLeft-20)+'px', {duration:0.5});
      $('content_impressum').morph('width:300px;', {duration:0.5});
      this.impressumOpen = true;
    }
    else {
      $('content_impressum').morph('width:0px;', {duration:0.5});
      $('content_contact').morph('left:0px', {duration:0.5});
      this.impressumOpen = false;
    }
  },

	viewFullscreen: function() {
	  var x = screen.availWidth;
	  var y = screen.availHeight;
		var w = window.open('index.html', "title", "width="+x+",height="+y+",menubar=no,resizable=yes");
		w.moveTo(0,0);
		w.focus();
	}
}

Event.observe(window, Prototype.Browser.IE ? 'load' : 'contentloaded', function() {
  if(Prototype.Browser.IE) PNGImages.load();
  Site.initialize();
  Lightbox.initialize();
	Canvas.initialize();
	  
	$('spinner').hide();
	$('hide_all').hide();
	Site.displayRandomImage(true);
	
	// disable right click on site
	Event.observe(document, 'contextmenu', function(event) { Event.stop(event); }, false);
});

Position.getPageSize = function() {
  var xScroll, yScroll;

  if (window.scrollMaxX) {  
    xScroll = window.innerWidth  + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else {
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } 
  
  var windowWidth, windowHeight;
  if (self.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  pageHeight = Math.max(windowHeight, yScroll);

  // for small pages with total width less then width of the viewport
  pageWidth = Math.max(windowWidth, xScroll);

  return { page: { width: pageWidth, height: pageHeight }, window: { width: windowWidth, height: windowHeight } };
}

var PNGImages = {
  load: function() {
    for (var i = document.images.length - 1, img = null; (img = document.images[i]); i--) {
  		if (img.src.match(/\.png$/i) != null) {
  			var src = img.src;
  			var div = new Element('div');
  			div.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizing='scale')"
  			div.style.width = img.width + "px";
  			div.style.height = img.height + "px";
  			img.replaceNode(div);
  		}
  		img.style.visibility = "visible";
  	}
  }
}
