// ==========================================================================
// Adds events to be executed after the document is loaded.
// By Simon Willison (See http://simonwillison.net)
// ==========================================================================

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


// ===========================================================================
// FAKE MULTI-PAGES
// ===========================================================================

// Add a line that checks if a page transition is under way when clicking. (use if :animated)

function setMultipage() {
  var whiteCurtain = "<div class=\"white-curtain\"></div>";
  
  // Remove all "Return to top" links
    $("#full-page p.return").remove();
  
  // Add the white curtain (work around IE bug)
    $("#full-page .page")
      .append(whiteCurtain);
  
  if (window.location.hash) {
    // If there's a hash in the URL, display that fake-page instead of the first
      var hash = window.location.hash;
      hash = hash.replace(/#/, '');
      $("#full-page .page")
        .not("#" + hash)
          .hide();
    
    // Mark that page in the navigation
      $("#sections ." + hash + " a")
        .addClass("active");
  } else {
    // Mark first menu element
      $("#sections li:first a:first")
        .addClass("active");
      
    // Hide all fake-pages but the first
      $("#full-page .page")
        .not(":first")
          .hide();
  }
  
  // Hide the curtain on the visible page
    $("#full-page .page:visible div.white-curtain")
      .css("opacity", "0");
  
  // Assign switchPage event to Summary links
    $("#sections li a").click(function(e) {
      e.preventDefault();
      var newPageId = $(this).parent().attr("class");
      if ($("#full-page .page:animated").length >= 1 || newPageId == $("#full-page .page:visible:first").attr("id")) {
        return false;
      } else {
        window.location.hash = newPageId;
        resetSummary(this);
        switchToPage(newPageId);
      }
    });
}

function switchToPage(newPage) {
  $("#full-page .page:visible")
    // In the markup, move new page after old page
      .after($("#" + newPage))  
    // Hide the visible page
      .hide()
      .find("div.white-curtain")
        .show()
        .css("opacity", "1");
  
  // Show the new page
    $("#" + newPage)
      .show()
      .find("div.white-curtain")
        .show()
        .animate({
            opacity: "0"
          },
          1250,
          function() {
            $(this).hide();
          });
}

function resetSummary(newLink) {
  // Reset Summary links
    $("#sections a.active").removeClass("active");
  
  // Mark the new page as "Active"
    $(newLink).addClass("active");
}


// ===========================================================================
// HOMEPAGE ANIMATION
// ===========================================================================

var homepageAnimation = null;
var firstTransition = null;

function startAnimation() {
  // Timings...
    var transitionSpeed = 1000;
    var timeOnSlide = 5000;
  
  // Building the menu
    var menuWidth = $("ul#slider li").length * 22;
    if ($("ul#slider-switcher").length == 0) {
      $("<ul id=\"slider-switcher\"></ul>").insertAfter("ul#slider");
      $("ul#slider li").each(function(index) {
        $("<li>" + (index + 1) + "</li>").appendTo("ul#slider-switcher");
      });
      $("ul#slider-switcher")
        .css("width", menuWidth + "px")
        .find("li:first")
          .addClass("active");
    }
  
  // Stops/restarts when slider is hovered.
    var enteredSlider = false;
    $("ul#slider")
      .mouseenter(function() {
        enteredSlider = true;
        resetSliderTimer();
      })
      .mouseleave(function() {
        if (enteredSlider == true && pausedSlider == false) {
          sliderTimer(transitionSpeed, timeOnSlide);
          enteredSlider = false;
        }
      });
  
  // Adding click event on menu items
    var pausedSlider = false;
    $("ul#slider-switcher li").click(function() {
      // If a transition in is the works, cancel this switch...
        if ($("ul#slider li:animated").length >= 1) return false;
      
      // Otherwise, go ahead...
        pausedSlider = true;
        var indexToShow = $("ul#slider-switcher li").index(this);
        var slideToShow = $("ul#slider li").eq(indexToShow);
        switchSlides(transitionSpeed, slideToShow);
        resetSliderTimer();
    });
  
  // Starting the animation
    sliderTimer(transitionSpeed, timeOnSlide);
}

function switchSlides(transitionSpeed, nextSlide) {  
  // Basic variables
    var activeSlide = $("ul#slider li:visible:first");
    var activeSlideIndex = $("ul#slider li").index(activeSlide);
    if (nextSlide == null) var nextSlide = $(activeSlide).next();
    var nextSlideIndex = $("ul#slider li").index(nextSlide);
    
    // If next slide is the active slide, forget that switch.
      if (activeSlideIndex == nextSlideIndex) return false;
    
    // If you're the last slide, the next one is the first one
      if (!$(nextSlide).length) {
        nextSlide = $("ul#slider li:first");
      }
  
  // Adjusting CSS for transition..
    $(activeSlide).css("z-index", "50");
    $(nextSlide).css({
      "display": "block",
      "z-index": "40",
      "opacity": "0"
    });
  
  // Spark the animation
    $(nextSlide).animate({ opacity: "1" }, transitionSpeed);
    $(activeSlide).animate({ opacity: "0" }, transitionSpeed, function() {
      $(this).css("display", "none");
    });
  
  // Adjust the menu
    var indexToActivate = $("ul#slider li").index(nextSlide);
    $("#slider-switcher li.active").removeClass("active");
    $("#slider-switcher li").eq(indexToActivate).addClass("active");
}

function sliderTimer(transitionSpeed, timeOnSlide) {
  // Lock first transition inside a specific timer to make sure the slide is displayed the same amount of time as the others
    var timeOnFirstSlide = timeOnSlide - transitionSpeed;
    firstTransition = setTimeout(function() {
    
      clearTimeout(firstTransition);
      firstTransition = null;
      switchSlides(transitionSpeed);
      
      // Launching the real timer
        homepageAnimation = window.setInterval(function() {
          switchSlides(transitionSpeed);
        }, timeOnSlide);
    
    }, timeOnFirstSlide);
}

function resetSliderTimer() {
  if (firstTransition != null) {
    clearTimeout(firstTransition);
    firstTransition = null;
  }
  if (homepageAnimation != null) {
    clearTimeout(homepageAnimation);
    homepageAnimation = null;
  }
}


// ===========================================================================
// GALLERY ANIMATION (Fallback for those without CSS3 capabilities)
// ===========================================================================

function setGalleryImages() {
  var thumbDisplayWidth = $("#content div.gallery ul.images li:first").width();
  
  // Binding function on rollover.
    $("#content div.gallery ul.images li")
      .click(function(e) {
        $("#active-image").attr("id","");
        setActiveImage(this, thumbDisplayWidth);
      });
}

function setActiveImage(imageToShow, thumbDisplayWidth) {
  var fullDisplayWidth = $("#content div.gallery ul.images li.default:first").width();
  $(imageToShow).attr("id", "active-image");
  $("#content div.gallery ul.images li").not(".default")
    .animate(
      { "width" : thumbDisplayWidth + "px" },
      500,
      function() {
        if (!$(imageToShow).hasClass("default")) {
          $(imageToShow)
            .animate(
              { "width" : fullDisplayWidth + "px" },
              500
            );
        }
      }
    );
}


// ===========================================================================
// NEWSLETTER SUBSCRIPTION FORM SETUP
// ===========================================================================

function setNewsletterButton() {
  // Appending a cancel link
    if ($("body:first").hasClass("en")) {
      var cancelLink = "or <a id=\"newsletter-abort\" href=\"#\">Cancel</a>";
    } else {
      var cancelLink = "ou <a id=\"newsletter-abort\" href=\"#\">Annuler</a>";
    }
    
    $("#subForm p.button").append(cancelLink);
    $("#newsletter-abort").click(function(e) {
      e.preventDefault();
      $("#subForm").css({
        height: "0",
        overflow: "hidden",
        padding: "0"
      });
    });  
  
  $("#newsletter-trigger").click(function() {
    $("#subForm").css({
      height: "auto",
      overflow: "visible",
      padding: "1.5em"
    });
  });
}


function setIntuitionTest() {
  $("#acceptance").click(function() {
    $("#test-answer-container").slideToggle();
  });
}


// ===========================================================================
// FIND PAGE LANGUAGE
// Find page language based on the index link on the logo
// ===========================================================================

function findPageLanguage() {
  var pageLanguage = $("#content").attr("class");
  return pageLanguage;
}


// ===========================================================================
// LANGUAGE SWITCH
// Shows a temporary pop-up asking to change the language if needed.
// ===========================================================================

function toggleLanguagePopup(cookied) {
  if (cookied == true) {
    if(readCookie("davidgoliathLang") == "fr") {
      // If cookied language = french
        var mainQuestion = "Vous naviguez habituellement sur ce site en fran&ccedil;ais. Voulez-vous changer de langue&nbsp;?";
        var secQuestion = "You usually browse this site in french. Would you like to switch language?";
        
        var yes = "Oui | Yes";
        var no = "Non | No";
        var close = "Fermer | Close";
    } else {
      // If cookied language = english
        var mainQuestion = "You usually browse this site in english. Would you like to switch language?";
        var secQuestion = "Vous naviguez habituellement sur ce site en anglais. Voulez-vous changer de langue&nbsp;?";
        
        var yes = "Yes | Oui";
        var no = "No | Non";
        var close = "Close | Fermer";
    }
  } else {
    var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;
    userLang = userLang.substring(0,2);
      
    if (userLang == "fr") {
      // If user language = french
        var mainQuestion = "Ce site est aussi offert en fran&ccedil;ais. Voulez-vous changer de langue&nbsp;?";
        var secQuestion = "This site is also offered in english. Would you like to switch language?";
        
        var yes = "Oui | Yes";
        var no = "Non | No";
        var close = "Fermer | Close";
    } else {
      // If user language = english
        var mainQuestion = "This site is also offered in english. Would you like to switch language?";
        var secQuestion = "Ce site est aussi offert en anglais. Voulez-vous changer de langue&nbsp;?";
        
        var yes = "Yes | Oui";
        var no = "No | Non";
        var close = "Close | Fermer";
    }
  }

  var link = $("a.language-switch:first").attr("href");

  $("body:first").append("<div id=\"language-popup\" style=\"display: none\"><div id=\"overlay\" style=\"display: none\"></div><div id=\"dialog\" style=\"display: none\"><span class=\"fr\">" + mainQuestion + "</span> <span class=\"en\">" + secQuestion + "</span><a href=\"" + link + "\" id=\"change-lang\" class=\"button\">" + yes + "</a><a href=\"#\" class=\"button close\">" + no + "</a><a href=\"#\" class=\"invisible close\">" + close + "</a></div></div>")

  $("#language-popup div#overlay").css("opacity","0.75");

  $("#change-lang").click(function() {
    if (findPageLanguage() == "en") {
      var newLang = "fr";
    } else {
      var newLang = "en";
    }
    createCookie("davidgoliathLang",newLang,365);
  });

  $("#language-popup a.close").click(function(e) {
    e.preventDefault();
    toggleHomeLanguageSwitch();
  });

  var pageLoadDelay = setTimeout("toggleHomeLanguageSwitch()", 2000);
}

function toggleHomeLanguageSwitch() {
  if ($("#language-popup").is(":visible")) {
    createCookie("davidgoliathLang",findPageLanguage(),365);
    $("#language-popup div#dialog").fadeOut("slow", function() { $("#language-popup div#overlay").fadeOut("slow") });
    $("#language-popup").hide();
    $("body:first").css("overflow","inherit");
  } else {
    $("body:first").css("overflow","hidden");
    $("#language-popup").show().css("top", $(window).scrollTop() + "px");
    $("#language-popup div#overlay").fadeIn("slow", function() { $("#language-popup div#dialog").fadeIn("slow") });
  }
}

function setLang() {
  // Language control verifications and setup
    if (readCookie("davidgoliathLang")) {
      if (readCookie("davidgoliathLang") != findPageLanguage()) {
        toggleLanguagePopup(true);
      }
    } else {
      var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;
      userLang = userLang.substring(0,2);
      
      if (findPageLanguage() != userLang) {
        toggleLanguagePopup(false); 
      } else {
        createCookie("davidgoliathLang",findPageLanguage(),365);
      }
    }
    
    $("a.language-switch").click(function() {
      if (findPageLanguage() == "fr") {
        var newLang = "en";
      } else {
        var newLang = "fr";
      }      
      createCookie("davidgoliathLang",newLang,365);
    });
}


// ===========================================================================
// COOKIE MANAGEMENT
// Functions that help managing cookies.
// See http://www.quirksmode.org/js/cookies.html for more info.
// ===========================================================================

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
