var main = new Main();

$(document).ready(function() {
    main.initHeader();
    $(window).trigger("resize"); 
    $('.slider').randomize("a");
});

function Main () {

  /* Methods */

  /**
   *
   */
  this.initHeader = function() {
    var _this = this;
    $("header .submenu").hide();
    $("header .link").mouseover(function() {
	$(".submenu").hide();
	var submenu = $(this).next().find(".submenu");
	var sub = $(this).next();
	submenu.fadeIn();
	sub.mouseleave(function() {	    submenu.fadeOut();
	});
	
    });
  } 

  /**
   *
   */
  this.updateVideoBackgrounds = function() {
    var win = $(window);  
    $(".video-background").each(function() {
	$(this).css("position", "absolute");
	$(this).css("zIndex", "-10");
	var ratio = $(this).width() / $(this).height();      
	$(this).css("width", "100%");      
      });      
  }
  
  /**
   *
   */
  this.updateImagesBackgrounds = function() {
    var win = $(window);  
    $(".image-background").each(function() {
	$(this).css("position", "absolute");
	$(this).css("top", "0px");
	$(this).css("left", "0px");
	$(this).css("zIndex", "-1");
	var ratio = $(this).width() / $(this).height();      
	if ( (win.width() / win.height()) < ratio ) {	  
	  $(this).css("width", "auto");
	  $(this).css("height", "100%");
	} else {
	  $(this).css("width", "100%");
	  $(this).css("height", "auto");
	}
      });    
  }
  
  /**
   *
   */
  this.updateFooter = function() {
    if ( $("#global").innerHeight() > $(window).height() ) {
      var height = $("#global").innerHeight();
      $("footer").css("top", height);
    } else {
      $("footer").css("top", "100%");
    }
  } 
  
  /**
   *
   */
  this.callServerAsHtml = function(url, okHandler, errorHandler) {
    $.ajax({
      url: url,
	  cache: false,
	  success: function(data, textStatus, XMLHttpRequest){	
	  if ( !data || !(typeof data == "string") ) {
	    alert("Error: invalid data");
	    if ( errorHandler )
	      errorHandler(null);
	    return;
	  }
	  if ( okHandler )
	    okHandler(data);
	}, error: function(XMLHttpRequest, textStatus, errorThrown) {
	  alert("" + errorThrown);
	  if ( errorHandler )
	    errorHandler(null);
	}    
      });
  }

}

$(window).resize(function() {    
    main.updateVideoBackgrounds();
    main.updateImagesBackgrounds();
    main.updateFooter();
});


(function($) {

$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);

      elems.sort(function() { return (Math.round(Math.random())-0.5); });  

      $this.remove(childElem);  

      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      

  });    
}
})(jQuery);

