var fixed = false;
var bannerImageLoaded = false;

$(document).ready(function() {
  resizeContact();

  $('.navbar a:not(.btn-navbar)').click(function(e) {
    hideNavCollapse();
    var url = $(this).attr('href');
    var hash_pos = url.indexOf('#');
    var target_id = hash_pos >= 0 ? url.substring(hash_pos+1, url.length) : null;
    if (target_id) {
      var target_pos = $("#"+target_id).offset().top
      if ($('.fill').css('position') == 'static' && !isMobileSafari()) {
        target_pos -= 34;
      }

      $("html, body").clearQueue().animate({
        scrollTop: target_pos
      }, 500, function() {
        return window.location.hash = target_id;
      });

      return false;
    }
    
  });

  $('#request-form-modal').on('shown', function () {
    $("body").css("overflow-y","hidden");
  });

  $('#request-form-modal').on('hide', function () {
    $("body").css("overflow-y","auto");
  });
  
});

$(window).scroll(function() {
  if (!isMobileSafari()) {
    if( $(this).scrollTop() >= $('div.top').height()) {
      if( !fixed ) {
        fixed = true;
        $('.fill').css({position:'fixed',top:0});
        $('.small-logo').stop().animate({marginLeft: '0px'});
      }
      hideNavCollapse();
    } else {
      if( fixed ) {
        fixed = false;
        $('.fill').css({position:'static'});
        $('.small-logo').stop().animate({marginLeft: '-100px'});
      }
    }   
  }
});

$(window).resize(viewPortResize(function(e){
  resizeTop();
  resizeContact();
}));

$(window).click(function(e){
  if (!($(e.target).hasClass('fill') || $(e.target).parents(".fill").size())) { 
    hideNavCollapse();
  }  
});

function viewPortResize(fn, context){
  context = context || window;
  var $window = $(window);
  var winWidth = $window.width();
  var winHeight = $window.height();

  return function(e){
    var oldW = winWidth;
    var oldH = winHeight;
    winWidth = $window.width();
    winHeight = $window.height();
    if (winWidth != oldW || winHeight != oldH){
      fn.apply(context, [e]);
    }
  }
}

function resizeTop(){
  if (bannerImageLoaded) {
    $('div.top').height($('.welcome div.overlay img').height());    
  }
}

function topBannerReady(){
  bannerImageLoaded = true;
  resizeTop();
}

function resizeContact() {
  $("#contact").css('min-height', $(window).height() - 120);
}

function isMobileSafari() {
  return navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/);
}

function hideNavCollapse(){
  if ($('a.btn-navbar:visible').length) {
    $('.nav-collapse').height(0);
    $('.nav-collapse').removeClass('in');
  };
}

// Easter Egg
easterEggRunning = false;
(function (callback, code, listener) {
  if (code == null)
    code = "38,38,40,40,37,39,37,39,66,65";

  return $(this).each(function () {
    var k = [];
    var lastMatched = 0;

    $(window).bind("keydown", function (e) {
      k.push(e.keyCode);
      while (k.length > code.split(',').length) {
        k.shift();
      }

      if (k.slice(k.length - lastMatched - 1, k.length).join(',') == code.split(',').slice(0, lastMatched + 1).join(',')) {
        lastMatched++;
      } else {
        lastMatched = 0;
      }
      listener(lastMatched);

      if (!(k.toString().indexOf(code) < 0)) {
        k = [];
        listener(0);
        callback(e);
      }
    })
  });
})(function () {
  // Thank you mrdoob for his three.js!
  // Code adapted and modified from mrdoob's cloud demo
  // See the original here: http://mrdoob.com/lab/javascript/webgl/clouds/
  if (!Modernizr.webgl && !THREE)
    return;

  // Guarding mutex, one canvas a time
  if (!easterEggRunning) {
    canvas = document.createElement('canvas');

    var size = function () {
      return { w: $(".top").width(), h: $(".top").height() };
    };

    var container = $(".top");

    $(window)
    .bind("resize", function() {
      var context, gradient;
      canvas.width = 32;
      canvas.height = size().h;
      context = canvas.getContext('2d');
      gradient = context.createLinearGradient(0, 0, 0, canvas.height);
      gradient.addColorStop(0, "#73bfe1");
      gradient.addColorStop(0.5, "#78c4e8");
      context.fillStyle = gradient;
      context.fillRect(0, 0, canvas.width, canvas.height);

      container.addClass("easteregg").css({
        background: "url(" + canvas.toDataURL('image/png') + ") fixed repeat-x top left !important"
      });
    })
    .trigger("resize");

    var camera = new THREE.PerspectiveCamera(30, size().w / size().h, 1, 3000);
    camera.position.y = 20;
    camera.position.z = 6000;
    camera.useTarget = true;

    var scene = new THREE.Scene();
    var geometry = new THREE.Geometry();

    var texture = THREE.ImageUtils.loadTexture("img/cloud10.png");
    texture.magFilter = texture.minFilter = THREE.LinearMipMapLinearFilter;

    var fog = new THREE.Fog(0xffffff, -100, 1000);

    var material = new THREE.ShaderMaterial({
      uniforms: {
        map: {
          type: "t",
          value: 2,
          texture: texture
        },
        fogColor: {
          type: "c",
          value: fog.color
        },
        fogNear: {
          type: "f",
          value: fog.near
        },
        fogFar: {
          type: "f",
          value: fog.far
        }
      },
      vertexShader:
        "varying vec2 vUv;"+
        "void main() {"+
        " vUv = uv;"+
        " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );"+
        "}",
      fragmentShader:
        "uniform sampler2D map;"+
        "uniform vec3 fogColor;"+
        "uniform float fogNear;"+
        "uniform float fogFar;"+
        "varying vec2 vUv;"+
        "void main() {"+
        " float depth = gl_FragCoord.z / gl_FragCoord.w;"+
        " float fogFactor = smoothstep( fogNear, fogFar, depth );"+
        " gl_FragColor = texture2D( map, vUv );"+
        " gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );"+
        " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );"+
        "}",
      depthTest: false
    });

    var plane = new THREE.Mesh(new THREE.PlaneGeometry(64, 64));

    for (i = 0; i < 4000; i++) {
      plane.position.x = Math.random() * 1000 - 500;
      plane.position.y = -Math.random() * Math.random() * 200 + 20;
      plane.position.z = i;
      plane.rotation.z = Math.random() * Math.PI;
      plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
      THREE.GeometryUtils.merge(geometry, plane);
    }

    var mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    var renderer = new THREE.WebGLRenderer({ antialias: false });
    renderer.setSize(size().w, size().h);
    container.append(renderer.domElement);

    $(window).bind("resize", function() {
      camera.aspect = size().w / size().h;
      camera.updateProjectionMatrix();
      renderer.setSize(size().w, size().h);
    });

    var startTime = new Date().getTime();
    var animate = function() {
      var position = ((new Date().getTime() - startTime) * 0.05);
      camera.position.z = 4000 - position;

      if (camera.position.z < 0) {
        container.removeClass("easteregg");
        setTimeout(function () {
          $("canvas").remove();
        }, 3000);
        return;
      }

      renderer.render(scene, camera);

      (window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback, element) {
          return window.setTimeout(callback, 1000 / 60);
        }
      )(animate);
    };

    $("html, body").clearQueue().animate({ scrollTop: 0 });
    animate();
    easterEggRunning = false;
  }
}, null, function (count) {
  if (count > 0) {
    $("#konami div").eq(count - 1).addClass("sel");
  } else {
    $("#konami div").removeClass("sel");$
  }
});

