jQuery.fn.onImagesLoaded = function(_cb) { 
  return this.each(function() {
 
    var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
        _cont = this,
            i = 0,
    _done=function() {
      if( typeof _cb === 'function' ) _cb(_cont);
    };
 
    if( $imgs.length ) {
      $imgs.each(function() {
        var _img = this,
        _checki=function(e) {
          if((_img.complete) || (_img.readyState=='complete'&&e.type=='readystatechange') )
          {
            if( ++i===$imgs.length ) _done();
          }
          else if( _img.readyState === undefined ) // dont for IE
          {
            $(_img).attr('src',$(_img).attr('src')); // re-fire load event
          }
        }; // _checki \\
 
        $(_img).bind('load readystatechange', function(e){_checki(e);});
        _checki({type:'readystatechange'}); // bind to 'load' event...
      });
    } else _done();
  });
};

function vimeo(video_id, width, height) {
  var result = '';
  
  result += '<a href="" class="videoclose" onclick="return closeVideo()">Cerrar video</a>';
  result += '<object width="' + width + '" height="' + height + '">';
  result += '<param name="allowfullscreen" value="true" />';
  result += '<param name="allowscriptaccess" value="always" />';
  result += '<param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' + video_id + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=cc0000&amp;fullscreen=1&amp;autoplay=1" />';
  result += '<embed src="http://vimeo.com/moogaloop.swf?clip_id=' + video_id + '&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=cc0000&amp;fullscreen=1&amp;autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' + width + '" height="' + height + '">';
  result += '</embed>';
  result += '</object>';

  return result;
}

function closeVideo() {
  target = $("#videoplayer");
  overlay = $("#overlay");
  $(target).fadeOut(1000);
  $(overlay).fadeOut(1000);
  $(target).remove();
  $(overlay).remove();
  return false;
}

function extractVimeoId(url) {
  return url.match(/\d+/)[0];
}

function getScrollBarWidth () {
	var inner = document.createElement('p');
	inner.style.width = "100%";
	inner.style.height = "200px";

	var outer = document.createElement('div');
	outer.style.position = "absolute";
	outer.style.top = "0px";
	outer.style.left = "0px";
	outer.style.visibility = "hidden";
	outer.style.width = "200px";
	outer.style.height = "150px";
	outer.style.overflow = "hidden";
	outer.appendChild (inner);

	document.body.appendChild (outer);
	var w1 = inner.offsetWidth;
	outer.style.overflow = 'scroll';
	var w2 = inner.offsetWidth;
	if (w1 == w2) w2 = outer.clientWidth;

	document.body.removeChild (outer);

	return (w1 - w2);
};

var lowLoadedAt;
var loadedBg = "0";

function updateBackground() {
  screenWidth = $(window).width();
  screenHeight = $(window).height();
  bg = $("#background");
  ratio = 1.6
  
  if (screenWidth/screenHeight > ratio) {
    $(bg).height("auto");
    $(bg).width("100%");
  } else {
    $(bg).width("auto");
    $(bg).height("100%");
  }

  if ($(bg).width() > 0) {
    $(bg).css('left', (screenWidth - $(bg).width()) / 2);
  }
  if ((loadedBg > screenHeight) && (loadedBg*ratio > screenWidth)) {
    return false;
  }
  
  if ((screenHeight > 1050) || (screenWidth > 1680)) {
    $(bg).attr("src", images_url + "/background.jpg");
    loadedBg = 2000;
  } else if ((screenHeight > 900) || (screenWidth > 1440)) {
    $(bg).attr("src", images_url + "/background1050.jpg");
    loadedBg = 1050;
  } else if ((screenHeight > 600) || (screenWidth > 800)) {
    $(bg).attr("src", images_url + "/background900.jpg");
    loadedBg = 900;
  } else {
    $(bg).attr("src", images_url + "/background600.jpg");
    loadedBg = 600;    
  }
}
$(document).ready(function() {
  updateBackground();
  $(window).bind("resize", function() {
    updateBackground();
  });
  $('img#backgroundlow').onImagesLoaded(function(_this){
    lowLoadedAt = new Date().getTime();
  });
  $('img#background').onImagesLoaded(function(_this){
    elapsed = new Date().getTime() - lowLoadedAt;
    if (elapsed > 100) {
      $(_this).fadeIn(500);
    } else {
      $(_this).show();
    }
  });
});

// Parse video links
$(document).ready(function() {
  $('a.video').each(function(idx,link) {
    link.onclick = function() {
      video_id = extractVimeoId(this.href);
      width = 885;
      height = 496;
      $('#content').prepend("<div id='videoplayer'></div>");
      target = $("#videoplayer");
      target.hide();
      target.css('top', ($(window).height() - height)/2 + 'px');

      $('body').prepend("<div id='overlay'></div>");
      overlay = $("#overlay");
      overlay.hide();
      overlay.height($(document).height());
      overlay.width($(document).width());
      overlay.css("position", "absolute");
      overlay.css("top", "0");
      overlay.css("z-index", "10");

      overlay.click(function() {
        closeVideo();
      });

      target.html(vimeo(video_id, width, height));
      overlay.fadeIn(1000);
      target.fadeIn(1000);
      
      return false;
    }
  });
});

// Auto fold/unfold text boxes
$(document).ready(function() {
  
  $('.text').each(function(idx,box) {
    if ($(box).height() > 210 || $(box).hasClass('compress')) {
      if ($(box).height() < 325 || $(box).hasClass('compress')) {
        $(box).addClass('compressed');
        $(box).prepend("<div class='more'></div>");
        $(box).mouseenter(function() {
          more = $(box).children("div.more").first();
          inner = $(box).children("div").last();
          $(more).animate({
            "top" : "+=" + ($(inner).height() - $(box).height() + 50)
          }, "fast");
          $(box).animate({
            "height" : ($(inner).height() + 30) + 'px'
          }, "fast");
        });
        $(box).mouseleave(function() {
          more = $(box).children("div.more").first();
          inner = $(box).children("div").last();
          if ($(box).hasClass("half")) {
            $(box).animate({
              "height" : "98px"
            }, "fast");
            $(more).animate({
              "top" : "63px"
            }, "fast");
          } else {
            $(box).animate({
              "height" : "210px"
            }, "fast");
            $(more).animate({
              "top" : "175px"
            }, "fast");
          }
        });
      } else if ($(box).height() < 435) {
        $(box).addClass('dh');
      }
    }
  });

  if ((-1 == document.referrer.indexOf(base_url))) {
    $("#header").css("overflow", "hidden");
    $("#header").width(200);
    $("#content").hide();
    $("#submenu").hide();
    $("#footer").hide();
    $("#header").animate({"background-color" : "#000000"}, 500)
                .animate({"width" : "915px"}, 1500).animate({"background-color" : "#000000"}, 500, "linear", function() {
      $("#header").css("overflow", "visible");
      $("#submenu").show();
      $("#content").show();
      $("#footer").show();
    });
  } else {
    $(".block1,.block2,.block3,.block4").css("opacity", "0");
    $(".block1,.block2,.block3,.block4").animate({"opacity": "1"}, 600);
  }
});
