$(document).ready(function(){


  // if you want to ignore some sections then add them a ignore class here or in the html
  $("#top").addClass("ignore");
  $("section, footer, hr").each(function(){
    if ( !$(this).hasClass("ignore") ) {
      $(this).css("margin-top","8px"); // comment out if you dont like the move during animation
    }
  })

  if ( $("body").hasClass("delay") ) {

    $("section:not('.ignore'), footer, hr").each(function(i) {
    $(this).delay((i++) * 300).animate({
      "margin-top": 0, // comment out if you dont like the move during animation
      "opacity": 1
    }, 600); 

  })

  }


function drops() {
  var screen_width = $(window).width();

  if ( screen_width > 1200 ) {
    $(".dropdown").mouseenter(function(){
      $(this).addClass("open");
    });
    $(".dropdown").mouseleave(function(){
      $(this).removeClass("open");
    })
    $(".dropdown > .dropdown-menu > li.stack").mouseenter(function(){
      $(this).addClass("open");
    });
    $(".dropdown > .dropdown-menu > li.stack").mouseleave(function(){
      $(this).removeClass("open");
    })
  }

  if ( screen_width < 1200 ) {
    $(".dropdown").unbind("mouseenter mouseleave");
    $(".dropdown-menu li.stack").unbind("mouseenter mouseleave");

   $(".dropdown").click(function(){
    $(this).find("li.stack").removeClass("open");
   })

   $("html").click(function(){
    $(".dropdown li.stack").removeClass("open");
   })

   $(".dropdown > .dropdown-menu > li.stack > a").click(function(){
      $(this).parent().addClass("open");
      return false;
   });

  }
}

drops();

$(window).resize(function(){
  drops();
})

  if ($(".widget-carousel").length) {

    function deployFred() {

      $(".widget-carousel .init").each(function(){

        $(this).carouFredSel({
          auto: false,
          prev: '.widget-carousel .widget-nav .prev',
          next: '.widget-carousel .widget-nav .next',
          mousewheel: false,
          scroll: 1,
          responsive: false,
          height: "auto",
          scroll: {
            items: 1,
          },
          items: {
            visible: 3,
            min: 3,
            filter: ".item"
          },
          swipe: {
            onMouse: true,
            onTouch: true
          }
        });
      });  
    }


    deployFred();

    function destroyFred() {
      $(".widget-carousel .init").each(function(){
        $(this).trigger("destroy", true);
      });
    }

    function redeployFred() {
      destroyFred();
      deployFred();
    }

    $(window).resize( $.throttle( 100, redeployFred) );

  }
      


  if ($(".widget-accordion").length) {

    $(".widget-accordion .item .toggle").click(function(){

      var item = $(this).parent();
      var pane = item.find(".data .inner");

      if ( item.hasClass("active") ) {
        pane.slideUp(function(){
          item.removeClass("active");
        });
      }
      else {
        pane.slideDown(function(){
          item.addClass("active");
        });

        item.prevAll(".item.active").find(".data .inner").slideUp(function(){ $(this).closest(".item").removeClass("active"); });
        item.nextAll(".item.active").find(".data .inner").slideUp(function(){ $(this).closest(".item").removeClass("active"); });
      }

    });

  }

  // ##########
  // Flickr photo stream
  // Our very special jQuery JSON fucntion call to Flickr, gets details of the most recent 20 images         
  $.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=998875@N22&lang=en-us&format=json&jsoncallback=?", getFlickrImages);
  
  function getFlickrImages(data) {                                                                   
    // Randomly choose where to start. A random number between 0 and the number of photos we grabbed (20) minus 9 (we are displaying 9 photos).
    var iStart = Math.floor(Math.random()*(11));  
    
    // Reset our counter to 0
    var iCount = 0;               
    
    // Start putting together the HTML string
    var htmlString = "<ul>";          
    
    // Now start cycling through our array of Flickr photo details
    $.each(data.items, function(i,item){
                  
      // Let's only display 6 photos (a 2x3 grid), starting from a random point in the feed         
      if (iCount > iStart && iCount < (iStart + 7)) {
        
        // I only want the ickle square thumbnails
        var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");    
        
        // Here's where we piece together the HTML
        htmlString += '<li><a href="' + item.link + '" target="_blank">';
        htmlString += '<figure><img src="' + sourceSquare + '" alt="' + item.title + '" title="' + item.title + '"></figure>';
        htmlString += '</a></li>';
      }
      // Increase our counter by 1
      iCount++;
    });   
    
    // Pop our HTML in the #images DIV  
    $('#flickr-photos').html(htmlString + "</ul>");
    // Close down the JSON function call
  }
  // #########


  if ( $("#contact-form").length ) {
    //contact form init
    var options = {target: "#alert"}
    $("#contact-form").ajaxForm(options);
  }

  $(".slideshow").each(function(){
    $(this).cycle();
  })


  if ( $(".portfolio .isotope").length ) {

    /**
     * Isotope init
     */

    function isotopeInit() {
      
  
      var $container = $('.isotope'),
      $select = $('.header-isotope select');
      filters = {};

      $container.imagesLoaded(function(){
        $container.isotope({
          itemSelector: '.item',
          layoutMode: 'fitRows'
        });
      });

      $select.change(function() {
      var $this = $(this);

      var $optionSet = $this;
      var group = $optionSet.attr('data-filter-group');
      filters[group] = $this.find('option:selected').attr('data-filter');

      var isoFilters = [];
      for (var prop in filters) {
      isoFilters.push(filters[prop])
      }
      var selector = isoFilters.join('');

      $container.isotope({
      filter: selector
      });

      return false;
      });      

      // update columnWidth on window resize
      $(window).smartresize(function(){
        $container.isotope({
          // options
          itemSelector : '.item',
          layoutMode : 'fitRows'
        });
      });

    }

    isotopeInit();

  }

  if ( $(".selectpicker").length ) {
    $(".selectpicker").selectpicker();
  }

  // custom lightbox
  function modal() {

    var $container = $(".md-container");
    var $overlay = $(".md-overlay");
    var $modal = $(".md-modal");
    var $trigger = $(".md-trigger");
    var $close = $modal.find(".md-close");
    var $placeholder = $modal.find(".md-image");

    function hide() {

      $modal.removeClass("md-show");
      $overlay.removeClass("md-show", function(){
        $placeholder.find("img").remove();
      });

      $container.removeClass("md-show");
      $modal.find(".md-title").html("");
      $modal.find(".md-subtitle").html("");
      $("html").removeClass("md-perspective");

    }

    $trigger.each(function(){
      $(this).click(function(){

          $modal.addClass("md-show");
          $container.addClass("md-show");
          $overlay.addClass("md-show");
          var $image = $(this).attr("href");
          $placeholder.html("<img src='"+$image+"' alt='' />");
          $("html").addClass("md-perspective");

          var $title = $(this).data("title");
          var $subtitle = $(this).data("subtitle");
          $modal.find(".md-title").html($title);
          $modal.find(".md-subtitle").html($subtitle);

          return false;

      })
    });

    $close.click(function(){

      hide();
      return false;
    })

  }

  modal();


  if ( $(".important").length ) {
    $lightsbreakpoint = 600;


    //------------------------------
    // Mesh Properties
    //------------------------------
    var MESH = {
      width: 1.3,
      height: 1.4,
      depth: 5,
      segments: 12,
      slices: 6,
      xRange: 0.37,
      yRange: 0.29,
      zRange: 1.3,
      ambient: '#ebedf0',
      diffuse: '#FFFFFF',
      speed: 0.0003
    };

    //------------------------------
    // Light Properties
    //------------------------------
    var LIGHT = {
      count: 1,
      xyScalar: 3,
      zOffset: 0,
      ambient: '#FFFFFF',
      diffuse: '#f0f0f0',
      speed: 0.0002,
      gravity: 0,
      dampening: 1,
      minLimit: 0,
      maxLimit: 0,
      minDistance: 0,
      maxDistance: 0.5,
      autopilot: true,
      draw: false,
      bounds: FSS.Vector3.create(),
      step: FSS.Vector3.create(
        Math.randomInRange(0.0, 0.5),
        Math.randomInRange(0.0, 0.5),
        Math.randomInRange(0.0, 0.5)
      )
    };

    //------------------------------
    // Render Properties
    //------------------------------
    var WEBGL = 'webgl';
    var CANVAS = 'canvas';
    var SVG = 'svg';
    var RENDER = {
      renderer: CANVAS
    };


    //------------------------------
    // Global Properties
    //------------------------------
    var $light = "light";
    var now, start = Date.now();
    var center = FSS.Vector3.create();
    var attractor = FSS.Vector3.create();
    var container = document.getElementById($light);
    var output = document.getElementById($light);
    var renderer, scene, mesh, geometry, material;
    var webglRenderer, canvasRenderer, svgRenderer;
    var gui, autopilotController;

    //------------------------------
    // Methods
    //------------------------------
    function initialise() {
      createRenderer();
      createScene();
      createMesh();
      createLights();
      addEventListeners();
      resize(container.offsetWidth, container.offsetHeight);
      animate();
    }

    function createRenderer() {
      webglRenderer = new FSS.WebGLRenderer();
      canvasRenderer = new FSS.CanvasRenderer();
      svgRenderer = new FSS.SVGRenderer();
      setRenderer(RENDER.renderer);
    }

    function setRenderer(index) {
      if (renderer) {
        output.removeChild(renderer.element);
      }
      switch(index) {
        case WEBGL:
          renderer = webglRenderer;
          break;
        case CANVAS:
          renderer = canvasRenderer;
          break;
        case SVG:
          renderer = svgRenderer;
          break;
      }
      renderer.setSize(container.offsetWidth, container.offsetHeight);
      output.appendChild(renderer.element);
    }

    function createScene() {
      scene = new FSS.Scene();
    }

    function createMesh() {
      scene.remove(mesh);
      renderer.clear();
      geometry = new FSS.Plane(MESH.width * renderer.width, MESH.height * renderer.height, MESH.segments, MESH.slices);
      material = new FSS.Material(MESH.ambient, MESH.diffuse);
      mesh = new FSS.Mesh(geometry, material);
      scene.add(mesh);

      // Augment vertices for animation
      var v, vertex;
      for (v = geometry.vertices.length - 1; v >= 0; v--) {
        vertex = geometry.vertices[v];
        vertex.anchor = FSS.Vector3.clone(vertex.position);
        vertex.step = FSS.Vector3.create(
          Math.randomInRange(0.2, 1.0),
          Math.randomInRange(0.2, 1.0),
          Math.randomInRange(0.2, 1.0)
        );
        vertex.time = Math.randomInRange(0, Math.PIM2);
      }
    }

    function createLights() {
      var l, light;
      for (l = scene.lights.length - 1; l >= 0; l--) {
        light = scene.lights[l];
        scene.remove(light);
      }
      renderer.clear();
      for (l = 0; l < LIGHT.count; l++) {
        light = new FSS.Light(LIGHT.ambient, LIGHT.diffuse);
        light.ambientHex = light.ambient.format();
        light.diffuseHex = light.diffuse.format();
        scene.add(light);

        // Augment light for animation
        light.mass = Math.randomInRange(0.5, 1);
        light.velocity = FSS.Vector3.create();
        light.acceleration = FSS.Vector3.create();
        light.force = FSS.Vector3.create();

        // Ring SVG Circle
        light.ring = document.createElementNS(FSS.SVGNS, 'circle');
        light.ring.setAttributeNS(null, 'stroke', light.ambientHex);
        light.ring.setAttributeNS(null, 'stroke-width', '0.5');
        light.ring.setAttributeNS(null, 'fill', 'none');
        light.ring.setAttributeNS(null, 'r', '10');

        // Core SVG Circle
        light.core = document.createElementNS(FSS.SVGNS, 'circle');
        light.core.setAttributeNS(null, 'fill', light.diffuseHex);
        light.core.setAttributeNS(null, 'r', '4');
      }
    }

    function resize(width, height) {
      renderer.setSize(width, height);
      FSS.Vector3.set(center, renderer.halfWidth, renderer.halfHeight);
      createMesh();
    }

    function animate() {
      now = Date.now() - start;
      update();
      render();
      requestAnimationFrame(animate);
    }

    function update() {
      var ox, oy, oz, l, light, v, vertex, offset = MESH.depth/2;

      // Update Bounds
      FSS.Vector3.copy(LIGHT.bounds, center);
      FSS.Vector3.multiplyScalar(LIGHT.bounds, LIGHT.xyScalar);

      // Update Attractor
      FSS.Vector3.setZ(attractor, LIGHT.zOffset);

      // Overwrite the Attractor position
      if (LIGHT.autopilot) {
        ox = Math.sin(LIGHT.step[0] * now * LIGHT.speed);
        oy = Math.cos(LIGHT.step[1] * now * LIGHT.speed);
        FSS.Vector3.set(attractor,
          LIGHT.bounds[0]*ox,
          LIGHT.bounds[1]*oy,
          LIGHT.zOffset);
      }

      // Animate Lights
      for (l = scene.lights.length - 1; l >= 0; l--) {
        light = scene.lights[l];

        // Reset the z position of the light
        FSS.Vector3.setZ(light.position, LIGHT.zOffset);

        // Calculate the force Luke!
        var D = Math.clamp(FSS.Vector3.distanceSquared(light.position, attractor), LIGHT.minDistance, LIGHT.maxDistance);
        var F = LIGHT.gravity * light.mass / D;
        FSS.Vector3.subtractVectors(light.force, attractor, light.position);
        FSS.Vector3.normalise(light.force);
        FSS.Vector3.multiplyScalar(light.force, F);

        // Update the light position
        FSS.Vector3.set(light.acceleration);
        FSS.Vector3.add(light.acceleration, light.force);
        FSS.Vector3.add(light.velocity, light.acceleration);
        FSS.Vector3.multiplyScalar(light.velocity, LIGHT.dampening);
        FSS.Vector3.limit(light.velocity, LIGHT.minLimit, LIGHT.maxLimit);
        FSS.Vector3.add(light.position, light.velocity);
      }

      // Animate Vertices
      for (v = geometry.vertices.length - 1; v >= 0; v--) {
        vertex = geometry.vertices[v];
        ox = Math.sin(vertex.time + vertex.step[0] * now * MESH.speed);
        oy = Math.cos(vertex.time + vertex.step[1] * now * MESH.speed);
        oz = Math.sin(vertex.time + vertex.step[2] * now * MESH.speed);
        FSS.Vector3.set(vertex.position,
          MESH.xRange*geometry.segmentWidth*ox,
          MESH.yRange*geometry.sliceHeight*oy,
          MESH.zRange*offset*oz - offset);
        FSS.Vector3.add(vertex.position, vertex.anchor);
      }

      // Set the Geometry to dirty
      geometry.dirty = true;
    }

    function render() {
      renderer.render(scene);

      // Draw Lights
      if (LIGHT.draw) {
        var l, lx, ly, light;
        for (l = scene.lights.length - 1; l >= 0; l--) {
          light = scene.lights[l];
          lx = light.position[0];
          ly = light.position[1];
          switch(RENDER.renderer) {
            case CANVAS:
              renderer.context.lineWidth = 0.5;
              renderer.context.beginPath();
              renderer.context.arc(lx, ly, 10, 0, Math.PIM2);
              renderer.context.strokeStyle = light.ambientHex;
              renderer.context.stroke();
              renderer.context.beginPath();
              renderer.context.arc(lx, ly, 4, 0, Math.PIM2);
              renderer.context.fillStyle = light.diffuseHex;
              renderer.context.fill();
              break;
            case SVG:
              lx += renderer.halfWidth;
              ly = renderer.halfHeight - ly;
              light.core.setAttributeNS(null, 'fill', light.diffuseHex);
              light.core.setAttributeNS(null, 'cx', lx);
              light.core.setAttributeNS(null, 'cy', ly);
              renderer.element.appendChild(light.core);
              light.ring.setAttributeNS(null, 'stroke', light.ambientHex);
              light.ring.setAttributeNS(null, 'cx', lx);
              light.ring.setAttributeNS(null, 'cy', ly);
              renderer.element.appendChild(light.ring);
              break;
          }
        }
      }
    }

    function addEventListeners() {
      window.addEventListener('resize', onWindowResize);
    }


    //------------------------------
    // Callbacks
    //------------------------------

    function onWindowResize(event) {

      resize(container.offsetWidth, container.offsetHeight);
      render();

      $ww = $(window).width();
      $breakpoint = $lightsbreakpoint;

      if ( $ww < $breakpoint ) {
        resize(1, 1); // not 0, 0 because this would complicate few things.
        $("#light").addClass("hidden");
      }

      if ( $ww > $breakpoint ) {
        $("#light").removeClass("hidden");
        resize(container.offsetWidth, container.offsetHeight);
        render();
      }

    }

    // check for window width and if it's heigher than breakpoint then fire the lights
    // if user deployed in smaller window and then maximized then fire the initialise but do it only once since we dont want to overload anybody's browser

    $ww = $(window).width();
    $breakpoint = $lightsbreakpoint;

    if ( $ww > $breakpoint ) {
      initialise();
    }

    var $lightenabled = false;

    $(window).resize(function(){
      $ww = $(window).width();
      $breakpoint = $lightsbreakpoint;

      if ( !$lightenabled ) {
        if ( $ww > $breakpoint ) {
          initialise();
          $lightenabled = true;
        }
      }
    })
  }






});