/**
 * some default jquery actions need on every page
 * applied if document is ready
 */
$(function() {
  var hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('#');
  if(hashes[1]) {
    window.location = hashes[1];
  }
});
$(document).ready(function(){
	movibox();
});
$(function() 
{
  // fix hover flicker on left footer navi
  $('#footer ul.left li').each(function(index) {
    $(this).css('width', $(this).outerWidth());
  });
});
/*
Movibox
*/
movibox = function()
{
	var movibox = $('.movibox'),
		arrPageSizes = ___getPageSize();

	$('#fade').remove();
	$('body').append('<div id="fade"><a href="#" class="fade-close"></a><div id="fadeinner"></div></div>');
	$('#fade').hide();
	
	$(window).resize(function () {
		var arrPageSizes = ___getPageSize();
		if(!$('#fade').is(':hidden')) {
			$('#fade').css({'height':(arrPageSizes[1]-80),'width':arrPageSizes[0]});
			if(arrPageSizes[0]>680) {
				$('#fade #fadeinner').css({'width':(arrPageSizes[0]-180),'height':(arrPageSizes[3]-80-180)});
			}
		}
	});

	movibox.each(function(index,e) {
		if($(this).attr('href')!='#') {
			$(this).attr('rel',$(this).attr('href'));
		}
		$(this).attr('id','movib'+index);
		var _this = $('#movib'+index),fade_width,link;
		var _this_link = _this.attr('rel'),fade_width;
			_this.attr('href','#');
		
		_this.append('<span class="play"></span>');
		_this.find('.play').css({'width':_this.width(),'height':_this.height()});
		
		_this.click(function() {
			arrPageSizes = ___getPageSize();
			
			if(arrPageSizes[2]<680) {
				fade_width = arrPageSizes[2];
			} else {
				fade_width = arrPageSizes[0];
			}
			
			var video_mp4 = _this_link.replace(/f4v/g, 'm4v');
			
			$('#fade #fadeinner').html('<div id="flashplayer"><video width="100%" height="100%" controls="controls" src="' + video_mp4 + '"></video></div>');
		//	$('#fade').css({'filter':'alpha(opacity=1)','height':(arrPageSizes[1]-80),'width':arrPageSizes[2]}).fadeIn(function() {
			$('#fade').css({'height':(arrPageSizes[1]-80),'width':arrPageSizes[2]}).fadeIn(function() {
				swfobject.embedSWF("/files/layout/swf/AirLuxVideoplayer.swf", "flashplayer", "100%", "100%", "9.0.115", null,
					{ autoPlay: 1, language: "", videoPath: _this_link },
					{ wmode: "transparent", scale: "exactFit", quality: "high", bgcolor: "#000000" },
					{ id: "videoplayer", name: "videoplayer" }
				);
			});
			$('#fade #fadeinner').css({'width':(fade_width-180),'height':(arrPageSizes[3]-80-180)});
		    return false;
		});
		
		$('#fade .fade-close').live('click', function() {
			$('#fade #fadeinner').html('');
			$('#fade').fadeOut();
		});
	});
	
}
/**
/ THIRD FUNCTION
* getPageSize() by quirksmode.com
*
* @return Array Return an array with page width, height and window width, height
*/
function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			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
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
/**
/ THIRD FUNCTION
* getPageScroll() by quirksmode.com
*
* @return Array Return an array with x,y page scroll values.
*/
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};


/**
 * complete panel handler
 * animates panel in and out
 * handles ajax requests inside the panel
 * @see requires jquery special load event
 * @see http://api.jquery.com/load-event/
 * @see http://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js
 * 
 */
AirLuchsPanel = function()
{
  var main =  $('#main-wrapper');
  var footer = $('#footer-wrapper');
  var wrapper = $('#panel-wrapper');
  var panel = $('#panel');
  var navi = panel.find('.navi');
  var links = navi.find('a');
  var label = wrapper.find('div.label');
  
  var ajaxContainer = $('#panel-ajax-container');
  var contentHeight = ajaxContainer.outerHeight(true);
  var panelPaddingTop = parseInt(panel.css('padding-top'), 10);
  var panelPaddingLeft = parseInt(panel.css('padding-left'), 10);

  var busy = false; // to block all input while animating
  var lefts = { close: 0, navi: 0, open: 0 }; // set in resize()
  var states = { close: "close", navi: "navi", open: "open" };
  var state = states.close; // initial state
  
  links.each(function(){
    $(this).attr('href', function(i) {
      var hashes = this.href.replace(location.protocol + '//' + location.hostname + '/','').split('#'), href;
      for(var i = 0; i < hashes.length; i++) {
        href = '#/' + hashes[i];
      }
      return href.replace('//','/');
    });
  });
  
  
  // toggle the panel navigation by clicking on label
  label.click(function() {
    if(state != states.close && state != states.navi) return false;
    else var newstate = (state == states.close) ? states.navi : states.close;
    animate(newstate, 'fast', this, function(link) { $(link).toggleClass('close'); });
    return false;
  });
  
  // close the panel and call reset() thereafter
  wrapper.find('a.close').click(function() {
    var duration = (state == states.navi) ? 'fast' : 'slow';
    animate(states.close, duration, this, function(link) { reset(); });
    return false;
  });
  
  // open the panel and make ajax call, or just do an ajax call if already open
  links.click(function() {
    if(state == states.open) load(this);
    else animate(states.open, 'slow', this, function(link) { load(link); });
    // return false;
  });
  
  // keyboard handler for esc
  $(document).keyup(function(e) { 
    if(e.keyCode == 27) wrapper.find('a.close').click(); // esc
    return false;
  });  
  
  //trigger resizing on browser resize and on first call
  $(window).resize(resize);
  resize();
  

  /**
   * simply animate the panel by its css left property
   * execute a given callback function thereafter pass the link scope
   * @param   String the state to change into
   * @param   String/Number animation duration, see jQuery animate()
   * @param   Object a scope object passed to the callback function
   * @param   Function callback function
   * @return  Void
   */
  function animate(newstate, duration, link, callback)
  {
    // are there any other thing running, so skip here
    if(busy) return false;
    else busy = true;
    
    // animate panel container, execute callback thereafter
    wrapper.animate({ left: lefts[newstate] }, duration, 'easeInOutCubic', function() {
      state = newstate;
      busy = false;
      if($.isFunction(callback)) callback(link);
    });
  }
  
  
  /**
   * set the panels height, depending on its content and the underlaying content
   * adjust the footer position to keep it sticked below the panel
   * set and save panel container positions for the various panel states: close, open & navi
   * @return  Void
   */
  function resize()
  {
    // reset main height to let the footer 'jump' back
    main.css('height', '');
    
    // calculate minimal height (based on underlaying content), then choose and set the panel height
    var minHeight = footer.position().top - footer.height() - wrapper.position().top; 
    var panelHeight = Math.max(contentHeight + panelPaddingTop, minHeight); // panel content bigger than underlaying content?
    panel.height(panelHeight - panelPaddingTop);

    // adjust main container, expand page for scrollbars and push the footer down
    main.height(panelHeight + wrapper.position().top + footer.height());
    
    // save various horizontal container positions and set the current one
    lefts.close = $(window).width();
    lefts.navi = $(window).width() - navi.outerWidth(true) - panelPaddingLeft;
    lefts.open = 0;
    wrapper.css('left', lefts[state]);
  }
  
  
  /**
   * reset the panel, used after closing the panel
   * @return  Void
   */
  function reset()
  {
    label.toggleClass('close');
    links.filter('.selected').toggleClass('selected');
    ajaxContainer.empty();
    contentHeight = 0;
    resize();
  }
  
  
  /**
   * load an url via ajax by the given link
   * @return  Void
   */
  function load(link)
  {
    if(busy) return false;
    else busy = true;
        
    var update = function() {
      contentHeight = ajaxContainer.outerHeight();
      resize();
      ajaxContainer.fadeTo('fast', 1);
    }
    
    var geturl = link.href + '?&ajax=1';
    var hashes = link.href.slice(link.href.indexOf('/') + 1).split('#');
    var wlocation = hashes[0].replace(location.hostname + '/','');
    
    geturl = geturl.replace(wlocation + '#','');
    
    if ($.browser.msie && jQuery.browser.version.substring(0,1) < '8') {
      geturl = geturl.replace('#','');
    }
    
    // execute ajax call
    jQuery.get(geturl, function(data) 
    {
      // set loaded content and content height
      ajaxContainer.fadeTo(0, 0);
      ajaxContainer.html(data);
      
      // set highlight selected link
      links.filter('.selected').toggleClass('selected');
      links.filter(link).toggleClass('selected');
      
      // add anchor scrolling to subnavi and h2 links
      panel.find('.subnavi, h2').localScroll({ easing: 'easeInOutCubic', duration: 'slow' });
      
      // wait until all images are laoded
      if(ajaxContainer.find('img').length) {
        ajaxContainer.find('img').imagesLoaded(function() {
          // add image zoom icon and functions  
          $(this).filter('img[longdesc]').each(function(index) {
            var image = $(this);
            var overlay = image.before('<span class="plus"></span>').prev();
            overlay.css({ width: image.width(), height: image.height() });
            overlay.click(function() { zoom(image); });
          });
          // update and fade in
          update();
        });
      }
      // we have no images just update and fade in
      else update();
      
      busy = false;
    });
  }
  
  

  /**
   * zoom an image from the panel
   * @param   Object usally an image tag
   * @return  Void
   */
  function zoom(image)
  {
    var oimage = $(image);
    var orginal = $(oimage).parent();
    
    // remove any other zoom images
    ajaxContainer.find('.image-zoomed').remove();
    
    // create the zoomed image and attach it
    var zimage = $('<img></img>');
    zimage.attr('src', oimage.attr('longdesc'));
    zimage.attr('alt', oimage.attr('alt'));
    zimage.width(ajaxContainer.width() - 2);
    zimage.height('auto');
    
    // create the zoomed container, wrap araound zoomed image
    var zoomed = zimage.wrap('<span class="image-zoomed"></span>').parent();
    zoomed.fadeTo(0, 0);
    ajaxContainer.prepend(zoomed);
    
    // create image overlay with zoom back sign
    var overlay = zimage.before('<span class="minus"></span>').prev();
    overlay.addClass(orginal.hasClass('left') ? 'left' : 'right');
    
    // wait for image load, than we have a height, position and fade in
    zimage.imagesLoaded(function() {
      overlay.css({ width: zimage.width(), height: zimage.height() });
      zoomed.css({ width: zimage.width(), height: zimage.height() });
      zoomed.css('top', (orginal.position().top - zoomed.height()) + orginal.height());
      zoomed.fadeTo('fast', 1);
    });
    
    // fade out and remove zoomed image on click
    zoomed.click(function() {
      $(this).fadeTo('fast', 0, function() { 
        ajaxContainer.find('.image-zoomed').remove();
      });
    });
  }
  
}






/**
 * handles images in #gallery container,
 * also performs ajax calls to for the companys references
 * @param   Object for options 'singleImage' and 'useNavigation'
 */
AirLuchsGallery = function(options)
{
  // set all default values
  var defaults = {
    singleImage: false,
    useNavigation: false
  };  

  //merge defaults with given options values
  var options = $.extend(defaults, options);
  
  var gallery = $('#gallery');
  var footer = $('#footer-wrapper');
  
  var container = gallery.find('.container');
  var navi = gallery.find('.navi');
  var desc = gallery.find('.desc');
  var images = gallery.find('img');
  var links = navi.find('.select a');
  
  var imageIndex = 0; // index of current image
  var objectIndex = 0; // index of select reference object/house
  var busy = false; // to block all input while animating

  // firefox 3.6 bugfix: @font-face css font replacement if not fast enough, 
  // so resize() calculates a wrong gallery height, we need to wait a bit
  // also ff calculates the document height based on the standard font 
  // (here arial) which has serious consequences caused by line wrappings
  var ival;
  var main = $('#main-wrapper');
  var title = $('#title');
  var titleHeight = title.height(); 
  if($.browser.mozilla) {
    ival = setInterval(function() {
      if(titleHeight != title.height()) {
        window.clearInterval(ival);
        resize();
      }
    }, 30);
    window.setTimeout(function() { 
      window.clearInterval(ival); 
    }, 3000);
  }
  
  // remove the default padding below the body
  $('#body').css('padding-bottom', 0);
  
  //trigger resizing on browser resize
  $(window).resize(resize);

  // we use navi, so init and load first object
  if(options.useNavigation) initnavi();
  // its a simple gallery, adjust dimensions 
  else {
    imageTransitions(images);
    resize();
  }
  
  
  
  /**
   * initialize the navigation, 
   * attach click and key handlers
   * @return  Void
   */
  function initnavi()
  {
    //click handler for ajax calls on project select links
    links.click(function(item) 
    {
      // save reference for update on ajax success
      var link = $(this);

      if($(this).height()>17) {
	      $('#gallery .navi div.select').css({'height':($(this).height()+12)+'px'});
	      $('#gallery .navi span.title').css({'height':$(this).height()+'px'});
      } else {
	      $('#gallery .navi div.select').css({'height':'30px'});
	      $('#gallery .navi span.title').css({'height':'18px'});
      }
   
      // break if the already selected is clicked
      if(navi.find('.title').text() == link.text()) return false;
      // hide description container
      switchDescription(false);
      // ajax request for url in this links href
      $.get(this.href+'?&ajax=1', function(data) {
        $('#gallery-ajax-container').html(data);
        // restore jquery references
        container = gallery.find('.container');
        images = gallery.find('img');
        desc = gallery.find('.desc');
        imageIndex = 0;
        imageTransitions(images);
        resize();
        // update select box title
        navi.find('.title').html(link.text());
        // save the object index
        objectIndex = links.index(link);
      });
      return false;
    });
    
    //click handler arrow navigation right/next image
    navi.find('.next a').click(function() {
      animate(imageIndex+1);
      return false;
    });

    // click handler arrow navigation left/previous image
    navi.find('.prev a').click(function() {
      animate(imageIndex-1);
      return false;
    });
    
    //click handler for project description container
    navi.find('.info a').bind('click', switchDescription);
    desc.live('click', switchDescription);
    
    // some key events
    $(document).keyup(function(e) { 
      if(e.keyCode == 32) switchDescription(); // space
      if(e.keyCode == 39) animate(imageIndex+1); // right arrow
      if(e.keyCode == 37) animate(imageIndex-1); // left arrow
      if(e.keyCode == 38) if(objectIndex > 0) links.eq(objectIndex-1).click(); // up arrow
      if(e.keyCode == 40) if(objectIndex < links.length-1) links.eq(objectIndex+1).click(); // down arrow
      return false;
    });  
    
    // load the first object via ajax
    links.eq(0).click();
  }
  
  
  /**
   * animate the container to move and 
   * show image at given index
   * @param   Number
   * @return  Void
   */
  function animate(index)
  {
    if (busy || !images.length) return false;
    else busy = true;

    // update index number on edge cases
    if(index > images.length - 1) index = 0;
    if(index < 0) index = images.length - 1;
    
    // disable ie7 image interpolation for smooth animation
    ie7ImageInterpolation(false);
    
    // move image container
    var xpos = "-" + Math.ceil(images.eq(index).position().left + 2) + "px";
    container.animate({ left: xpos }, 'slow', 'easeInOutCubic', function() { 
      imageIndex = index; busy = false; ie7ImageInterpolation(true); 
    });
  }
  
  
  function imageTransitions(arr) 
  {
    // no image tags given, do nothing
    if(!arr.is('img')) return;
    // filter for image tags only
    arr = arr.filter('img');
    // hide at first
    arr.hide();
    // fade in when loaded
    arr.load(function() { 
      $(this).fadeIn('slow', 'easeInOutCubic');
    });
  }
  
  
  /**
   * show/hide the description container
   * @param   Boolean optional, if not given toogles
   * @return  Void
   */
  function switchDescription(bool)
  {
    // check for boolean type
    if(bool === true || bool === false) {
      desc.toggle(bool);
      navi.find('.info').toggleClass('active', bool);
    } else {
      desc.toggle();
      navi.find('.info').toggleClass('active');
    }
    return false;
  }
  
  
  /**
   * triggered if browser windows gets resized
   * handles gallery images sizes and navigation
   * @return  Void
   */
  function resize()
  {
    // calculate the new gallery height
    var minHeight = parseInt(gallery.css('min-height'), 10);
    var galleryHeight = $(window).height() - (gallery.position().top + footer.height());
    // apply gallery height only if more space than gallery's min-height available
    galleryHeight = (galleryHeight < minHeight) ? minHeight : galleryHeight;

    // firefox bug, resize the main wrapper, to force correct document height 
    if($.browser.mozilla && titleHeight > title.height()) {
      main.height(main.height() - (titleHeight - title.height()));
    }

    // centers a single image inside the gallery container "proportional outside"-style 
    // (image gets vertically or horizontally cropped)
    if(options.singleImage) 
    {
      var image = images.eq(0);
      // adjust container sizes
      container.height(galleryHeight);
      container.width($(window).width());
      // calculate aspect ratios of container and image 
      var ratioContainer = container.width() / container.height();
      var ratioImage = image.width() / image.height();
      // adapt either witdh or height of image
      if(ratioContainer > ratioImage) {
        var imageWidth = container.width() + 4; // 4px buffer
        var imageHeight = Math.ceil(image.width() / ratioImage);
      } else {
        var imageHeight = container.height() + 4; // 4px buffer
        var imageWidth = Math.ceil(image.height() * ratioImage);
      }
      // set image dimensions
      image.width(imageWidth);
      image.height(imageHeight);
      // center the image in container, ipad fix here
      image.css('left', container.width() / 2 - imageWidth / 2);
      image.css('top', container.height() / 2 - imageHeight / 2);
    }
    
    // we have multiple images 
    else
    {
      // just adjust their height
      images.height(galleryHeight);
      // start loading the images
      triggerImageLoading(images);
    }
    
    // if desc container exists, set its dimensions
    if(options.useNavigation) {
      desc.width($(window).width() - parseInt(desc.css('padding-left'), 10) * 2);
      desc.height(galleryHeight);
    }
    
    // add clean image interpolation class if ie7
    ie7ImageInterpolation(true);
  }
  
  
  /**
   * trigger browser image loading of images in given array
   * by simply copying the image's rel attribute to src attribute
   * @param Array
   */
  function triggerImageLoading(arr)
  {
    // no image tags given, do nothing
    if(!arr.is('img')) return;
    
    // simply copy rel attribute to src attribute
    arr.slice('[longdesc]').each(function(index, image) {
      image.src = $(image).attr('longdesc'); 
    });
  }  
  
  
  /**
   * toogles a class on all image tags to update
   * the image interpolation on ie7 browser to 'bicubic'
   * @param   Boolean
   * @return  Void
   */
  function ie7ImageInterpolation(bool)
  {
    if($.browser.msie && $.browser.version.substr(0,1) == '7') {
      images.toggleClass('iemage', bool);
    }
  }
  
}




/**
 * contact form handling
 * and error validation
 */
AirLuchsForm = function()
{
  var form = $('#contact-form');
  var submit = form.find('a.submit');
  var radios = form.find('div.select input');
  var texts = form.find('input[type=text], textarea');
  
  var defaults = new Array();
  
  // focus and blur handling for text inputs
  texts.each(function(index) {
    defaults.push($(this).val());
    $(this).focus(function() {
      $(this).parent().addClass('valid');
      $(this).parent().removeClass('error');
      if($(this).val() == defaults[index]) $(this).val('');
    });
    $(this).blur(function() {
      if($(this).val() == '') {
        $(this).val(defaults[index]);
        $(this).parent().removeClass('valid');
      }
    });
  });
  
  // handle language radio buttons
  radios.each(function(index) {
    $(this).css('opacity', 0.01);
    $(this).click(function() {
      $(this).parent().parent().children().removeClass('active');
      $(this).parent().parent().children().removeClass('error');
      $(this).parent().addClass('active');
    });
  });
  
  // submit handler and error validation
  submit.click(function() {
    var valid = true;
    // no radio button selected
    if(!radios.is(':checked')) {
      radios.parent().addClass('error');
      valid = false;
    }
    // empty mandatory fields
    texts.each(function(index) {
      var str = defaults[index]; // .substr() is buggy in IE, use substring() instead!
      if(str.substring(str.length-1, str.length) == "*" && $(this).val() == defaults[index]) {
        $(this).parent().addClass('error');
        valid = false;
      }
    });
    // email address is not valid via regex
    var regex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    if(!regex.test(texts.filter('[name=email]').val())) {
      texts.filter('[name=email]').parent().addClass('error');
      valid = false;
    }
    // send or return false
    if(valid) form.submit();
    return valid;
  });
}




/**
 * google map for contact
 * with center marker
 */
AirLuchsMap = function()
{
  var mapContainer = $("#google-map");
  var coords = new google.maps.LatLng('47.448566', '9.348979');
  
  //create the map
  var map = new google.maps.Map(mapContainer.get(0), {
    center: coords,
    mapTypeId: google.maps.MapTypeId.ROADMAP,      
    zoom: 12,
    mapTypeControl: true,
    mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
    navigationControl: true,
    navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
    streetViewControl: false
  });
  
  //create marker
  var marker = new google.maps.Marker({
    position: coords,
    icon: new google.maps.MarkerImage('/files/layout/css/img/google-marker.png',
        new google.maps.Size(21, 34),
        new google.maps.Point(0,0),
        new google.maps.Point(16, 16)),
    map: map
  });
}

