$(document).ready(function(){
  
  /* Main menu drop down */
    $("ul.dropdown li").hover(function() {
      $(this).addClass("hover");
      $('ul:first',this).css('visibility', 'visible');
    }, function(){
      $(this).removeClass("hover");
      $('ul:first',this).css('visibility', 'hidden');
    });
    $("ul.dropdown li ul li:has(ul)").find("a:first").append(" &raquo; ");

  /* Slider used in POURQUOI section */
    $("#slider").easySlider({
      continuous: true,
      nextId: "sliderNext",
      prevId: "sliderPrev"
    });

  /* Create playlist for media (youtube and images)*/
    $("ul.playlist").ytplaylist({
      addThumbs: true,
      autoPlay: true,
      holderId: 'mediaHolder'
    });

  // lightbox for images (and video, in Portfolio section)
    $("a[rel^='prettyPhoto']").prettyPhoto({social_tools: false});
  
  // Checking for scrollable menus
    if ($(".scroll-menu").length) {
      $(".scroll-menu").each(function() {
        setScrollMenu(this);
      });
    }
  
  // Checking for homepage slider
    if ($("#home-slides").length) {
      setHomeSlider();
    }
    
    // Clear contents of textfield when clicked on
    $(".input-clear").focus(function(){
      this.value = "";
    });
  
  // Content Lightbox
    if ($("#careers-handle").length) {
      $("#careers-handle").click(function() {
        contentBox("#careers");
      });
    }
});


// ===========================================================================
// SCROLLABLE MENUS SETUP
// Creates a scrollable menu in the direction specified in the element's class attribute
// ===========================================================================

function setScrollMenu(menu) {
  // Some basic variables
    menu = $(menu); // Makes the menu a jquery object
    list = $(menu).find("ul:first");
    var direction = null;
    var incrementation = null;
    var noOfPages = null;
    var listEnd = null;
  
  // Defining the direction of the scroll
    if (menu.hasClass("vertical") == true) orientation = "vertical";
    if (menu.hasClass("horizontal") == true) orientation = "horizontal";
  
  // Wrapping the menu inside a "window"
    if ($(menu).attr("id") == "mediaHolder") {
      var wrapper = $("<div class=\"wrapper\"><div class=\"menus\"></div></div>").appendTo(menu);
      $(menu).find("ul").appendTo(wrapper.find("div.menus"));
      wrapper.find("div.menus").width($(menu).find("ul").length * $(menu).find("ul:first").outerWidth(true));
    } else {
      var wrapper = $("<div class=\"wrapper\"></div>").appendTo(menu);
      $(menu).find("ul").appendTo(wrapper);
    }
  
  // Appending arrows to the markup and styling them
    var prevArrow = $("<div class=\"prev\">Prev</div>").insertBefore(wrapper);
    var nextArrow = $("<div class=\"next\">Next</div>").insertAfter(wrapper);

  // If the menu is vertical...
    if (orientation == "vertical") {
      // Defining the end and incrementation of the list
        incrementation = list.parents(":first").outerHeight(true) - 1;
        noOfPages = Math.ceil(list.outerHeight(true) / incrementation);
        listEnd = (noOfPages - 1) * incrementation;
      
      // Adding function to the arrows
        $(prevArrow)
          .click(function() {
            // Defining some basic variables
              var newPosition = (parseFloat(list.css("top")) + incrementation) + "px";
              var button = $(this);

            // Show Next button if it's hidden
              if (button.siblings("div.next:first").is(":hidden")) button.siblings("div.next:first").show();

            // Move the list, hide the button if reaching the end
              if (parseFloat(newPosition) > 0) {
                return false;
              } else {
                list.animate({
                  top: newPosition
                }, 500, function() {
                  if (parseFloat(newPosition) >= 0) button.fadeToggle();
                });
              }
          });

        $(nextArrow)
          .click(function() {
            // Defining some basic variables
              var newPosition = (parseFloat(list.css("top")) - incrementation) + "px";
              var button = $(this);

            // Show Prev button if it's hidden
              if (button.siblings("div.prev:first").is(":hidden")) button.siblings("div.prev:first").show();

            // Move the list, hide the button if reaching the end
              if (Math.abs(parseFloat(newPosition)) > listEnd) {
                return false;
              } else {
                list.animate({
                  top: newPosition
                }, 500, function() {
                  if (Math.abs(parseFloat(newPosition)) == listEnd) button.fadeToggle();
                });
              }
          });
    }
  
  // If the menu is horizontal...
    if (orientation == "horizontal") {
      // Defining the end and incrementation of the list
        incrementation = list.outerWidth(true);
        noOfPages = $(menu).find("ul").length;
        listEnd = (noOfPages - 1) * incrementation;
      
      // Adding function to the arrows
        $(prevArrow)
          .click(function() {
            // Defining some basic variables
              var newPosition = (parseFloat(list.parents("div.menus:first").css("left")) + incrementation) + "px";
              var button = $(this);

            // Show Next button if it's hidden
              if (button.siblings("div.next:first").css("opacity","0.25")) button.siblings("div.next:first").animate({
                  opacity: "1"
                }, 500);

            // Move the list, disable the button if reaching the end
              if (parseFloat(newPosition) > 0) {
                return false;
              } else {
                list.parents("div.menus:first").animate({
                  left: newPosition
                }, 500, function() {
                  if (Math.abs(parseFloat(newPosition)) == 0) button.animate({opacity: "0.25"}, 500);
                });
              }
          });

        $(nextArrow)
          .click(function() {
            // Defining some basic variables
              var newPosition = (parseFloat(list.parents("div.menus:first").css("left")) - incrementation) + "px";
              var button = $(this);

            // Show Prev button if it's hidden
              if (button.siblings("div.prev:first").css("opacity","0.25")) button.siblings("div.prev:first").animate({
                  opacity: "1"
                }, 500);

            // Move the list, disable the button if reaching the end
              if (Math.abs(parseFloat(newPosition)) > listEnd) {
                return false;
              } else {
                list.parents("div.menus:first").animate({
                  left: newPosition
                }, 500, function() {
                  if (Math.abs(parseFloat(newPosition)) == listEnd) button.animate({opacity: "0.25"}, 500);
                });
              }
          });
    }
}


// ===========================================================================
// HOMEPAGE SLIDER SETUP
// Creates a slider and its associated menu
// ===========================================================================

var homepageAnimation = null;
var firstTransition = null;
var homeSlideTime = 5000;
var homeSlideTransitionTime = 2000;
var homeFirstSlideTime = 5000;

function setHomeSlider() {
  // Adjust the layout to make images full size
    resizeHomeImages();
  
  // Set page to resize images when window is resized
    $(window).resize(function() {
      resizeHomeImages();
    });
  
  // Create the slider menu if it doesn't exist
    if ($("#nav-slider").length == 0) setSliderMenu();
  
  // Starting the animation
    firstTransition = setTimeout(function() {
      var nextSlide = $("#home-slides div.slide:visible:first").next();
      var newActiveItem = $("#nav-slider li.active").next();
      
      slideTransition(nextSlide,newActiveItem);
      startAnimation();
      
      firstTransition = null;
    }, homeFirstSlideTime);
}

function resizeHomeImages() {
  // Define some basic variables
    var homeMinImageWidth = $("#main-content").width();
    var homeMinImageHeight = 666;
    var homeMaxImageWidth = 1645;
    var homeMaxImageHeight = 1000;
  
    var viewportWidth = $(window).width();
    var viewportHeight = $(window).height();
  
  $("#home-slides div.slide p.image img")
    .css({
      left: '',
      marginLeft: '',
      top: '',
      marginTop: ''
    });
    
  if (viewportWidth < homeMaxImageWidth || viewportHeight < homeMaxImageHeight) {
    // Define new sizes based on full-width of the screen
      var resizeRatio = viewportWidth / homeMaxImageWidth;
      var newWidth = viewportWidth;
      var newHeight = Math.round(resizeRatio * homeMaxImageHeight);
    
    // Make the image full height if it's to be smaller than the viewport
      if (newHeight < homeMaxImageHeight && viewportHeight >= homeMaxImageHeight) {
        newWidth = homeMaxImageWidth;
        newHeight = homeMaxImageHeight;
      } else {
        resizeRatio = viewportHeight / homeMaxImageHeight;
        newWidth = Math.round(resizeRatio * homeMaxImageWidth);
        newHeight = viewportHeight;
      }
    
    // Apply those sizes to the images
      if (newWidth < homeMaxImageWidth || newHeight < homeMaxImageHeight) {
        $("#home-slides div.slide p.image img")
          .width(newWidth)
          .height(newHeight);
      }
    
    // Center the image
      // If image is larger than the viewport...
        if ($("#home-slides div.slide p.image img:first").width() > viewportWidth) {
          var horOffset = "-" + ($("#home-slides div.slide p.image img:first").width() / 2) + "px";
          $("#home-slides div.slide p.image img")
            .css({
              left: "50%",
              marginLeft: horOffset
            });
        }
    
    // Adjust display of main content
      if (newWidth < homeMaxImageWidth || newHeight < homeMaxImageHeight) {
        $("#home-slides").height(viewportHeight);
        $("#main").css("padding-top", (viewportHeight - 87) + "px");
      }
  } else {
    // Resize and position just like originally
      $("#home-slides div.slide p.image img").each(function() {
        // Apply full size and adjust centering code
          $(this).width(homeMaxImageWidth);
          $(this).height(homeMaxImageHeight);
          $(this).css({
            left: "auto",
            marginLeft: "auto",
            top: "auto",
            marginTop: "0"
          });
      });
      
      $("#home-slides").height(996);
      $("#main").css("padding-top", "911px");
  }
}

function setSliderMenu() {
  // Creating the container
    var menuContainer = $("<ul id=\"nav-slider\"></ul>").appendTo("#home-slides");
  
  // Populating the container with menu items
    var numberOfSlides = $("#home-slides div.slide").length;
    for (i = 1; i <= numberOfSlides; i++) {
      var menuItem = "<li id=\"nav-slide-" + (i - 1) + "\">" + i + "</li>";
      $("#nav-slider").append(menuItem);
      if (i == 1) $("#nav-slide-" + (i - 1)).addClass("active");
    }

    var playPauseItem = "<li class=\"pause\">Play/Pause</li>";
    $("#nav-slider").append(playPauseItem);
  
  // Applying functions to menu items
    $("#nav-slider li").click(function() {
      if(!$(this).hasClass('active')) {
        // If a transition is under way, let the animation finish
        if ($("#home-slides div.slide:animated").length >= 1) $("#home-slides div.slide").stop(false,true);
        
      // If the Play/Pause button has been clicked, just pause/play or else, switch to another slide
        if ($(this).hasClass("play") || $(this).hasClass("pause")) {
          // #TODO : Test this shit
          playPauseSlider();
        } else {
          // Defining the next slide
            var nextSlidePosition = ($(this).attr("id")).replace("nav-slide-","");
            var nextSlide = $("#home-slides div.slide")[nextSlidePosition];
            var newActiveItem = $(this);

          // Triggering the transition
            $("#home-slides div.slide").stop(true, true);
            if (homepageAnimation != null || firstTransition != null) playPauseSlider();
            slideTransition(nextSlide,newActiveItem);
        }
      }
    });
}

function slideTransition(nextSlide,newActiveItem) {
  // If there's no nextslide, then the animation should restart
    if (!$(nextSlide).length || $(nextSlide).attr("id") == "nav-slider"){
      nextSlide = $("#home-slides div.slide:first");
      newActiveItem = $("#nav-slider li:first");
    }
  
  // Preparing the slides
    var activeSlide = $("#home-slides div.slide:visible:first");
    $(activeSlide).css("z-index", "1");
    $(nextSlide).css({
      "display": "block",
      "z-index": "10",
      "opacity": "0"
    });
  
  // Start the animation
    $(nextSlide).animate({ opacity: "1" }, homeSlideTransitionTime);
    $(activeSlide).animate({ opacity: "0" }, homeSlideTransitionTime, function() {
      // Hiding the 'old' slide
        $(this).css("display", "none");

      // Updating slider menu
        $("#nav-slider li.active").removeClass("active");
        $(newActiveItem).addClass("active");
    });
}

function playPauseSlider() {  
  // If homepageAnimation is playing, stop the animation.
    if (homepageAnimation != null || firstTransition != null) {
      if (firstTransition != null) {
        clearTimeout(firstTransition);
        firstTransition = null;
      }
      
      if (homepageAnimation != null) {
        clearInterval(homepageAnimation);
        homepageAnimation = null;
      }
      
      $("#nav-slider li.pause").attr("class","play");
      return false;
    }
  
  // If homepageAnimation is paused, switch to the next slide then start the animation
    if (homepageAnimation == null || firstTransiton == null) {
      // Replace play with pause button
        $("#nav-slider li.play").attr("class","pause");
      
      // Show the next slide already
        var nextSlide = $("#home-slides div.slide:visible:first").next();
        var newActiveItem = $("#nav-slider li.active").next();
        slideTransition(nextSlide,newActiveItem);
      
      // Trigger the first transition
        firstTransition = setTimeout(function() {
          var nextSlide = $("#home-slides div.slide:visible:first").next();
          var newActiveItem = $("#nav-slider li.active").next();
          slideTransition(nextSlide,newActiveItem);
          startAnimation();
          
          firstTransition = null;
        }, homeSlideTime);
    }
}

function startAnimation() {
  homepageAnimation = window.setInterval(function() {
    // Prepare the slides
      var activeSlide = $("#home-slides div.slide:visible:first");
      var nextSlide = $(activeSlide).next();
      var newActiveItem = $("#nav-slider li.active").next();
      
    // Show the next slide
      slideTransition(nextSlide,newActiveItem);
  }, homeSlideTime);
}


// ===========================================================================
// CONTENT BOX
// Displays the content of a container in a lightbox
// ===========================================================================

function contentBox(contentId) {
  // Put content in a variable
    var boxContent = $(contentId).html();
    var boxTitle = $(contentId).find("h2").text();
  
  // Build the markup
    var overlay = $("<div id=\"box-overlay\"></div>")
      .click(function() {
        toggleContentbox();
      })
      .css("opacity","0.8");
    var contentBox = $("<div id=\"content-box\"></div>");
    var contentWrapper = $("<div class=\"wrapper\"></div>")
    var contentContainer = $("<div class=\"container\">" + boxContent + "</div>");
    var contentHeader = $("<div class=\"header\"></div>");
    var contentTitle = $("<p class=\"title\">" + boxTitle + "</p>");
    var boxClose = $("<p class=\"close\">Close</p>")
      .click(function() {
        toggleContentbox();
      });
    
    overlay.appendTo("body:first");
    contentHeader.append(contentTitle);
    contentHeader.append(boxClose);
    contentWrapper.append(contentContainer);
    contentBox.append(contentWrapper);
    contentBox.append(contentHeader);
    contentBox.appendTo("body:first");
  
  // Start the show
    $("body:first").css("overflow","hidden");
    toggleContentbox();
}

function toggleContentbox() {
  $("#box-overlay, #content-box").fadeToggle();
  $("body:first").css("overflow","auto");
}
;

