var footer_active = false;
var maxHeight = 0;

function positionDivs(){
  maxHeight = 0; // reset maxHeight
  // calculate height of vertical resizable elements
  $$('#page div.h0').each(function(el){
    var parentId = el.getProperty('id');
    var parentTop = el.getCoordinates().top;
    var maxEl = null;
    var containerHeight = 0;
    var children = el.getChildren();
    children.each(function(child){
      var pos = child.getCoordinates();
      if ((pos.top + pos.height - parentTop) > containerHeight) {
        var offset = (typeof(backendUrl)=='undefined')?0:2; // -2 for border in backend
        containerHeight = pos.top + pos.height - parentTop - offset; 
      }
    });
    el.setStyle('height', pixelsToEm(containerHeight, 9)+'em');
  });

  // position pageTitleWrapper at bottom of pageTitleRow
  if($('pageTitleRow') && $('pageTitleWrapper')){ 
    var pPos = $('pageTitleRow').getCoordinates();
    var wPos = $('pageTitleWrapper').getCoordinates();
    var pix = pPos.height - wPos.height - 5;
    $('pageTitleWrapper').setStyle('margin-top', pixelsToEm(pix)+'em');
  }
 
  // position content under mainNavigation
  var mPos = ($('pageTitleRow'))?$('pageTitleRow').getCoordinates():$('mainNavigation').getCoordinates();
  // $('content').setStyle('top', pixelsToEm(mPos.bottom, 1.125)+'em');
  
  // set maxHeight
  var maxEl = null;
  $('content').getChildren().each(function(el){
    var pos = el.getCoordinates();
    if ((pos.top + pos.height) > maxHeight)
    {
      maxEl = el;
      maxHeight = pos.top + pos.height;
    }
  });
  
  var content_height = maxHeight - $('content').getCoordinates().top;
  $('content').setStyle('height', pixelsToEm(content_height, 1.125)+'em');
  
  // position footer
  $$('#footerNavigation a').each(function(el){
    if(el.hasClass('selected')){
      footer_active = true;
    }
  });
  if (footer_active){ 
    // set alternate body color
    $(document.body).addClass('white'); 
    // set alternate subNavigation color
    if ($('subNavigation')){
      $('subNavigation').addClass('c1');
    }
    // pageTitle
    if ($('pageTitleRow') && $('pageTitleRow').hasClass('c3')){
      $('pageTitleRow').removeClass('c3');
      $('pageTitleRow').addClass('c2');
    }
    
    // position footerNavigation
    if ($('pageTitleRow')){
      // reposition footerNavigation under Mainnavigation content
      $('footerNavigation').injectAfter($('mainNavigation'));
      $('footerNavigation').setStyle('position', 'absolute');
    }
    else{
      // reposition footerNavigation above content 
      $('footerNavigation').injectBefore($('content'));
    }
  }
  else{
    // vertical resize
    $('footerNavigation').addClass('h-50');
    $$('#footerNavigation li').each(function(el){
      el.addClass('h-50');
    });
    $$('#footerNavigation a').each(function(el){
      el.addClass('h-50');
    });
  }
}

function drawGrid(){
  // return; // disable grid
  
  // draw grid as background
  if ($('gridcontainer')){ $('gridcontainer').erase(); }
  var gridHeight = (footer_active)?maxHeight:$('footerNavigation').getCoordinates().bottom;
  gridHeight = pixelsToEm(gridHeight);
  // var gridcontainer = new Element('div', {'id': 'gridcontainer'}).setStyle('width', window.getWidth()+'px').injectInside(document.body);
  var gridcontainer = new Element('div', {'id': 'gridcontainer'}).setStyle('width', window.getWidth()+'px').inject($('page'),'after');
  if ($('pageTitleRow')){
    gridcontainer.setStyles({'margin-top': '-4.5em', 'height': gridHeight + 4.5 + 'em'}); 
  }
  else{
    gridcontainer.setStyles({'margin-top': '-2.25em', 'height': gridHeight + 2.25 + 'em'}); 
  }
  
  var cols = Math.ceil(window.getWidth()/16/9) + 1;
  var emW = cols*9;
  var grid = new Element('div', {'id': 'grid'}).setStyles({'width': emW + 'em', 'height': gridHeight + 9 + 'em'});
  grid.injectInside(gridcontainer);
  
  var emH = Math.ceil((maxHeight/16)/1.125) * 1.125; // use quarter blocks
  emH = Math.ceil(emH*1000)/1000 + 4.5;
  var blocks = cols * (Math.ceil(emH/9)+1);
  var gridDiv;
  var c;
  for (var i=1;i<blocks;i++){
    c = 'c'+Math.ceil(Math.random()*4);
    gridDiv = new Element('div').addClass(c).injectInside(grid);
  }
}

/**
 * Initialize image info divs
 */
function initImageInfoDivs(){
  $$('#content div.info').each(function(el){
    var parentPos = el.getParent().getCoordinates();
    var pos = el.getCoordinates();
    
    el.setStyles({
       top: parentPos.height-pos.height
    });
    el.setOpacity(0);
    
    // mouseover on img
    el.getParent().addEvents({
      'mouseover': function(e){
        el.setOpacity(0.8);
      },
      'mouseout': function(e){
        el.setOpacity(0);
      } 
    });
  });
}

/**
 * Initialize page_item links
 */
function initPageItemLinkDivs(){
  $$('#content div.link').each(function(el){
    var leaveClass = '';
    var overClass = '';
    for (var i=1;i<11;i++){
      if (el.hasClass('c'+i)){
        overClass  = 'c'+(11-i);
        leaveClass = 'c'+i;
      }
    }
    // overClass = (el.hasClass('c1'))?'c10':'c1';
    el.addEvents({
			'mouseover': function(){
        this.removeClass(leaveClass);
        this.removeClass(leaveClass + '_link');
        this.addClass(overClass);
        this.addClass(overClass + '_link');
			},
      'mouseleave': function(){
        this.removeClass(overClass);
        this.removeClass(overClass + '_link');
        this.addClass(leaveClass);
        this.addClass(leaveClass + '_link');
      }
    });
    // init
    el.addClass(leaveClass);
    el.addClass(leaveClass + '_link');
  });
}

/**
 * Initialize image info divs
 */
function initEmbeddedVideoDivs(){
	$$('#content div.embed_code').each(function(el){
	  // use page_item div for width and height
	  var pos = el.getParent().getCoordinates();
	  el.getElements('object').each(function(el_obj){
		  el_obj.setProperty('width', pos.width);
		  el_obj.setProperty('height', pos.height);
	  });
	  // only set attributes on embed tag when not in IE... it crashes.
	  // IE listens to css width / height ... where ff doesn't do that correctly
	  if(!Browser.Engine.trident){
		  el.getElements('embed').each(function(el_embed){
			  el_embed.setProperty('width', pos.width);
			  el_embed.setProperty('height', pos.height);
		  });
	  }
//	  else{
//		  el.setStyles({width:'100%', height:'100%'});
//	  }
  });
}

/**
 * Calculate em from pixels
 */
function pixelsToEm(pix, block){
  var em = (block > 0) ? Math.ceil((pix/16)/block) * block : pix/16;
  return Math.ceil(em*1000)/1000; // 3 decimals when using blocks
}


/**
 * make mainnavigation LI UL in good shape
 */
function mainNav(){
	
	lis = $$('li.parent');
	
	lis.each(function(el, i){		
	
		var widthLi = el.getStyle('width').toInt(); 
		
		el.addEvents({
			'mouseover': function(e){

				ul = el.getElement('ul');
	    		ul.setStyle('display', 'block');
	    		widthUl = ul.clientWidth;
	    		
				if(widthUl < widthLi ) {
					ul.setStyle('width', widthLi+'px');
				}    		
    		},
    		'mouseleave': function(){
    		
    			ul.setStyle('display', 'none');
    		}  			
		});		
	});
}

/** 
 * DomReady Event fires when all Elements are ready, but not images. 
 */
window.addEvent('domready', function() {
  
  if (!$('content')){ return; }
  
  // position divs in page
  positionDivs();
  
  // draw grid behind page content
  drawGrid();
  
  // initialize image info divs
  initImageInfoDivs();
  
  // initialize youtube video divs
  initEmbeddedVideoDivs();
  
  // set styles for page_item that has an url
  initPageItemLinkDivs();
  
  mainNav();

});
