// Global variables
var resizeTimer = null,
    borderSize  = null,
    currentSize = null,
		currentHeights = null,
		currentWidths = null,
    smallWidths = [955, 469, 225, 225],
    smallHeights = [417, 239, 239, 239],
    largeWidths = [1200, 591, 286, 286],
    largeHeights = [524, 301, 301, 301],
    directions = ["left", "left", "left", "left"],
    nextPlaylistThumb = 0,
    featuredIndex = [0, 0 , 0 ,0], 
    biographyIndex = 0,
    emptyPlaylistItem = null,
		facebookPartagerLink,
		size = null;



/************************************************************
 * 
 * Window Resizing Functions
 * 
 ************************************************************/

// Function called when the window is resized
resizeWindow = function(force) {
  $("#container").css("width", "80%");
 
  // Using the max-width css element, container will either be 957px or 1200px
  if ($("#container").width() < 1200) {
    $("#container").width(957);
  }

  // Check if the container size has changed or if these values have not been set yet
  if (currentSize == null || currentSize != $("#container").width() || force) {
    
		$(".video-mask").removeAttr("style");
		
		// This global variable determines whether the current size is small or large
		currentSize = $("#container").width();

    // Check if size is small or large
    if (currentSize == 957) {
			currentHeights = smallHeights;
			currentWidths = smallWidths;
			
      $("#director-carousel img.dynamic").width(633).height(284);
      $("#director-carousel").width(633).height(319);
    }
    else {
      currentHeights = largeHeights;
      currentWidths = largeWidths;
			
      $("#director-carousel img.dynamic").width(873).height(405);
      $("#director-carousel").width(873).height(440);
    }
		
    // Set the widths/heights for each thumbnail size
		if (!$.browser.msie) {
			$("img.three-column-block").each(function(){
				$(this).width(currentWidths[0]);
				$(this).height(currentHeights[0]);
			});
			$("img.two-column-block").each(function(){
				$(this).width(currentWidths[1]);
				$(this).height(currentHeights[1]);
			});
			$("img.one-column-block").each(function(){
				$(this).width(currentWidths[2]);
				$(this).height(currentHeights[2]);
			});
		}
		
		// set all the masks according to the new image size
//		$("#container div.video-mask, #container a.video-holder").each(function() {
//      $(this).width($(this).find("img.dynamic").width());
//      $(this).height($(this).find("img.dynamic").height());
//		});
    
    $("#director-carousel ul").width($("#director-carousel ul li").length * $("#director-carousel ul li").first().width());
     
		// Go through the 4 feature blocks (i = index)
    for (i = 0; i<=3; i++) {
    
      // k = iteration
      var k = i +1;
  
	    // Set all the li widths and heights according to the new image size
	    $("#feature_block_" + k + " li.blue-bottom, #feature_block_" + k + " div.blue-bottom li").each(function() {
	      $(this).width(currentWidths[i]);
	      $(this).height(currentHeights[i] + 35);
	    });
			
      // set all the masks according to the new image size
      $("#feature_block_" + k + " div.video-mask, #feature_block_" + k + " a.video-holder").each(function() {
        $(this).width(currentWidths[i]);
        $(this).height(currentHeights[i]);
      });
			
    // Set all the carousel ul widths or heights according to the new li heights or widths
      $("#feature_block_" + k + " ul").width($("#feature_block_" + k + " ul li").length * $("#feature_block_" + k + " ul li").first().width());
    
		  // Set the feature blocks widths and heights according to current widths/heights
      $("#feature_block_" + k).width(currentWidths[i]);
      $("#feature_block_" + k).height(currentHeights[i] + 35);
      
			// Find the current width or height of the feature block
			if (directions[i] == "top")
        size = parseInt($("#feature_block_" + k + " ul li:eq(0)").height());
			else {
				size = parseInt($("#feature_block_" + k + " ul li:eq(0)").width());
			}
      
			// Set the feature block carousel to have the correct left/top value to show the current item at the right location
      $("#feature_block_" + k + " ul").css(directions[i], size * featuredIndex[i] * -1);
    }
    
		// Set the director carousel to have the correct left value to show the current item at the right location 
    $("#director-carousel ul").css("left", parseInt($("#director-carousel ul li:eq(0)").width()) * biographyIndex * -1);
  } // end if
  
	// Adjust other non-thumbnail related alignments 
	adjustContainer();
  
  // Remove the percentage
  $("#container").width($("#container").width());
  
  $("#container li.blue-bottom").each(function() {
    
    var maxWidth = 0;
    $(this).find(".videoInfo:visible").each(function() {
      if ($(this).width() > maxWidth) {
        maxWidth = $(this).width();
      }
    });
    
    $(this).find(".videoInfo:visible").width(maxWidth);
  });
}; // end resizeWindow()

// Function to adjust alignments with navigation and video details
adjustContainer = function() {
  if ($("#container").width() >= 1200) {
    $(".video-player").addClass("left").addClass("small-margin-right");
    $(".video-details-spacer").removeClass("small").addClass("large");
		$("#big-nav").css("top", "135px");
		$("iframe.facebook").css("margin-top", "10px");
		$(".blue-bottom").addClass("large").removeClass("small");
  }
  else {
    $(".video-player").removeClass("left").removeClass("small-margin-right");
    $(".video-details-spacer").removeClass("large").addClass("small");
    $("#big-nav").css("top", "66px");
    $("iframe.facebook").css("margin-top", "0px");
    $(".blue-bottom").addClass("small").removeClass("large");
  }
  
  // Navigation
  $("#big-nav > li").css("padding-left", $("#container").offset().left + 50 + "px");
  $("#small-nav").css("padding-left", $("#container").offset().left);
}; // end adjustContainer()

// Function that performs the resize on the images. The timeout ensures that the user is done resizing.
doResize = function() {
	// Resize the playlist size
  resizeBorder();
	
	// Wait for 200ms of no-resizing 
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(resizeWindow, 200);
}; // end doResize()

// Re-center the playlist
resizeBorder = function() {
  borderSize = ($(window).width() - 975) / 2;
  $("#playlist-holder").css("border-left", borderSize + "px solid #3945a7").css("border-right", borderSize + "px solid #3945a7");
	$("#empty-playlist-msg").css("left", borderSize + 60);
	$("#edit-playlist-msg").css("left", borderSize + 810);
}; // end resizeBorder()

// Since images are hidden, the accordian will not know its drawer's height until after it's shown
// This function will assign a height to the given drawer
findDrawerHeight = function(drawer) {
	// Count the number of elements, two-column elements count as 2, one-column elements count as 1
  var elementCount = (drawer.find(".two-column-block").length * 2) + (drawer.find(".one-column-block").length);
	
	// Calculate the number of rows
	var rowNum = Math.ceil(elementCount / 3);
	
	// Calculate each row's height
	var heightMultiplier = currentSize == 957 ? smallHeights[1] : largeHeights[1]; 
	
	// Add the bottom border
	heightMultiplier += 55; // 35=blue bottom + 2x10 margins
	
	// Assign the height to the drawer
  drawer.height(rowNum * heightMultiplier );
}; // end findDrawerHeight()

// Function that updates the index of the feature block carousels
// In other words: this contains the current displayed item in each carousel
function updateIndex(carousel){
  if ($(carousel.context).attr("id") == "feature_block_1") {
    featuredIndex[0] = carousel.index();
  }
  else if ($(carousel.context).attr("id") == "feature_block_2") {
    featuredIndex[1] = carousel.index();
  }
  else if ($(carousel.context).attr("id") == "feature_block_3") {
    featuredIndex[2] = carousel.index();
  }
  else if ($(carousel.context).attr("id") == "feature_block_4") {
    featuredIndex[3] = carousel.index();
  }
  else if ($(carousel.context).attr("id") == "director-carousel") {
    biographyIndex = carousel.index();
  }
}; // end updateIndex()



/************************************************************
 * 
 * Playlist Functions
 * 
 ************************************************************/

// Remove the given thumbnail
removePlaylistThumb = function(playlistThumb) {
	var videoId = playlistThumb.find(".id").html();
	
  if (!$("#playlist .playlist_" + videoId).is(":animated")) {
  
  	$("." + videoId).find(".add-to-playlist").show();
  	$("." + videoId).find(".remove-from-playlist").hide();
  	
  	// Fade it out with a callback
			playlistThumb.fadeOut(400, function(){
			
			// Give the next thumnbnail a margin so that it does not immediately move left to replace the one removed
			playlistThumb.next().css("margin-left", "85px");
			
			// Animate the next thumbnail to move to the left
			movePlaylistThumbForward(playlistThumb.next());
			
			// Clear the cookie
			$.cookie("playlist-" + playlistThumb.index(), "", {
				path: '/'
			});
			
			// Adjust the following thumbnail cookies to move up one in line
			playlistThumb.nextAll(":not(.empty)").each(function(){
				$.cookie("playlist-" + (parseInt($(this).index()) - 1), $(this).find(".id").html() + "***" + $(this).find("img").attr("src"), {
					path: '/'
				});
				$.cookie("playlist-" + $(this).index(), "", {
					path: '/'
				});
			});
			
			// Remove the thumbnail from the DOM
			playlistThumb.remove();
			
			resetPlaylistState();
			
			// Change the href of the play-playlist link
			$("#playlist-jouer").attr("href", getPlaylistURL());
		});
	}
}; // end removePlaylistThumb()

// Animate the given thumbnail to clear out its new margin of 112px
movePlaylistThumbForward = function(thumb) {
  if (thumb.length == 0) {
    // Create a new empty thumbnail
    setLastThumbnailToEmpty();
  }
  else {
  	thumb.animate({
  		"margin-left": "1px"
  	}, 500, function(){
  	
  		if ($("#playlist .item.empty").length == 8 && $("#playlist .item:not(.empty)").length > 0) {
  			$("#playlist-left").click();
  			
  			$("#playlist .item.empty").fadeOut(500, function(){
  				$(this).remove();
  				$("#playlist-right").addClass("disabled");
  			});
  		}
  		else {
  			// Create a new empty thumbnail
				setLastThumbnailToEmpty();
			}
		});
	}
}; // end movePlaylistThumbForward()

// Create a new thumbnail and append it in the correct location
setLastThumbnailToEmpty = function() {
	
	// Check if there are any non-empty thumbnails
  if($("#playlist .item:not(.empty)").length > 0){
		
		// Insert empty thumbnail after the last non-empty thumbnail
    $("#playlist .item:not(.empty):last").after($(emptyPlaylistItem).clone());
		
		// Animate it to slide in from the left
    $("#playlist .item.empty:first").animate({width:"84px"});
  }
  else {
		// If there are no non-empty thumbnails, add the new one to the end
    $("#playlist-ul").append($(emptyPlaylistItem).clone());
		
		// Animate it to slide in from the left
    $("#playlist .item.empty:last").animate({width:"84px"});
  }
}; // end setLastThumbnailToEmpty()

// Create a thumbnail with the given information
createRectangle = function(videoId, imageSource) {
	
	// Find the thumbnail location
  var rectangle = $("#playlist .item:eq(" + nextPlaylistThumb + ")");
  
	rectangle.css("width", "86px");
	
	// Remove the white borders
  rectangle.removeClass("empty");
  
	// Give the thumbnail the image source and then fade it in
  rectangle.find(".playlist-thumb").attr("src", imageSource)
                                   .fadeIn(500, function() {
																	 	resetPlaylistState();
																	 });
  
  // if the link is null we are creating the item from a cookie. don't need to make it again
  $.cookie("playlist-" + nextPlaylistThumb, videoId + "***" + imageSource, {path: '/'});
	
  // Increment the thumbnail index                                         
  nextPlaylistThumb++;
  
	// Fade in the link for removing the thumbnail
  rectangle.find(".playlist-thumb-remove").fadeIn();
  
	// Add the id to a hidden span
  rectangle.find(".id").html(videoId);
  rectangle.addClass("playlist_" + videoId);
}; // end createRectangle()

// Set up the playlist from the user's cookies
setupPlaylist = function() {
	
	// Initialize the first cookie
  var i = 0,
      cookieValue = $.cookie("playlist-" + i);
  
	// While there's a valid cookie create a thumbnail from it
  while(cookieValue != "" && cookieValue != null) {
		// The cookie value is set up like "[id]***[imageSource]"
    var videoId = cookieValue.split("***")[0];
    var imageSource = cookieValue.split("***")[1];
    
		// Create the rectangle
    addToPlaylist(videoId, imageSource);
    
		// Increment the cookie index
    i++;
		
		// Get the next cookie
    cookieValue = $.cookie("playlist-" + i);
  }
}; // end setupPlaylist()

// Function called when the user clicks on an add button
addToPlaylist = function(videoId, imageSource){
	if (!$("#playlist .item:eq(" + nextPlaylistThumb + ")").is(":animated")) {
		// Check if this is the 10th, 19th, 28th, ... nth thumbnail.
		if (nextPlaylistThumb > 0 && nextPlaylistThumb % 9 == 0) {
		
			// Add 9 empty thumbnail items
			for (i = 0; i < 9; i++) {
				$("#playlist-ul").append($(emptyPlaylistItem).clone().width(84));
			}
			
			// Check if this is the first time we have more than 9 items.
			if (nextPlaylistThumb == 9 && !$("#playlist-carousel-holder").hasClass("carouselled")) {
				// Create the carousel
				$("#playlist-carousel-holder").addClass("carouselled");
				$("#playlist-carousel-holder").jCarouselLite({
					visible: 9,
					speed: 600,
					btnNext: "#playlist-right",
					btnPrev: "#playlist-left",
					scroll: 9
				});
			}
			else 
				if (nextPlaylistThumb == $("#playlist-carousel-holder ul li").length) {
					// Increase the ul width to hold more items
					$("#playlist-carousel-holder ul").width($("#playlist-carousel-holder ul").width() + ($("#playlist-carousel-holder ul li:eq(0)").width() + 2) * 9);
				}
			
			// Remove disabled class from right arrow
			$("#playlist-right").removeClass("disabled");
			
			// Go to the next set of items
			$("#playlist-right").click();
		}
		
		$("." + videoId + " a.add-to-playlist").hide();
		$("." + videoId + " a.remove-from-playlist").show();
		
		// Create the playlist item
		createRectangle(videoId, imageSource);
		
		// Change the href of the play-playlist link
		$("#playlist-jouer").attr("href", getPlaylistURL());
	}
}; // end addToPlaylist()

// function for retrieve the URL of the link for viewing a playlist
getPlaylistURL = function() {
  var playlistURL = "";
  
	// Go through each playlist item and add the id to the url 
  $("#playlist .item .id").each(function() {
    if ($(this).html().length > 0) {
      playlistURL += $(this).html() + "."
    }
  });
  
	// Return the formatted URL
  return "http://" + window.location.hostname + heap.urlmap['partager'] + "/" + playlistURL.substr(0, playlistURL.length - 1);
}; // end getPlaylistURL()

// Show a message that says that the playlist is empty (and the requested action won't be executed)
showPlaylistEmptyMsg = function () {
	
  // Check if the message is already being displayed
  if ($("#empty-playlist-msg").css("bottom") != "82px" && !$("#empty-playlist-msg").is(":animated")) {
		
    // Show the message, delay for 3 seconds, hide the message
		$("#empty-playlist-msg").animate({
      bottom: "82px"
    }, 300).delay(3000).animate({
      bottom: "50px"
    }, 300);
  }
}; // end showPlaylistEmptyMsg()

// Show a message that says that this is the playlist
showEditPlaylistMsg = function () {
  // Show the message, delay for 3 seconds, hide the message
  $("#edit-playlist-msg").stop().animate({
    bottom: "25px"
  });
}; // end showEditPlaylistMsg()

// Show a message that says that this is the playlist
hideEditPlaylistMsg = function () {
  // Show the message, delay for 3 seconds, hide the message
  $("#edit-playlist-msg").stop().animate({
    bottom: "-10px"
  });
}; // end showEditPlaylistMsg()



/************************************************************
 * 
 * Flash-related Functions
 * 
 ********************s****************************************/

videoFinished = function() {
  //nextVideo();
};

// Switches the active class between two given thumbs and then loads the video of the new active video
switchActiveVideo = function(oldActive, newActive) {
  // Find the next video's id
  var newActiveId = newActive.find("a.scroll").attr("href").split("#")[1];
  
  // Set the active class on the next thumb
  oldActive.removeClass("active");
  newActive.addClass("active");
  
  // Load the next video's id in the url
  window.location = window.location.toString().split("#")[0] + "#" + newActiveId;
  
  var videoSection = newActive.parents("accordian-block").find("video-section");
  
  if (videoSection.length == 0) {
			videoSection = $(".video-section:first");
  }
	
  // Load the next video
  loadVideo(videoSection);
}; // end switchActiveVideo

// When the next button is clicked in the flash video
nextVideo = function() {
	// Find the current video thumb
	var currentVideo = $(".blue-bottom.active");
	
	// Find the next video thumb
	var nextVideo = currentVideo.next();
	
	// Make sure that this is not the last video in the list. Next button should not exist in the flash
	if (nextVideo.length > 0) {
    switchActiveVideo(currentVideo, nextVideo);
  }
}; // end nextVideo()

// When the previous button is clicked in the flash video
previousVideo = function() {
  // Find the current video thumb
  var currentVideo = $(".blue-bottom.active");
  
  // Find the next video thumb
  var prevVideo = currentVideo.prev();
  
  // Make sure that this is not the last video in the list. Next button should not exist in the flash
  if (prevVideo.length > 0) {
    switchActiveVideo(currentVideo, prevVideo);
  }
}; // end previousVideo()

addVideoToPlaylist = function() {
  $(".blue-bottom.active a.add-to-playlist").click();
};

removeCurrentVideoFromPlaylist = function() {
  $(".blue-bottom.active a.remove-from-playlist").click();
};

resetPlaylistState = function() {
	var video_id = $(".video-player > object").attr("id");
  var flash = swfobject.getObjectById(video_id);
	
	if (flash) {
  	var playlistPosition = getPlaylistPosition();
  	var inPlaylist = $(".playlist_" + video_id).length > 0 ? "true" : "false";
  	
		try {
    	flash.resetPlaylistState(playlistPosition, inPlaylist);
    }
		catch (err) {
			
		}
  	
  }
}

pauseVideo = function() {
  var video_id = $(".video-player > object").attr("id");
  var flash = swfobject.getObjectById(video_id);
  
  if (flash) {
    try {
      flash.pauseVideo();
    }
    catch (err) {
      
    }
  }
}

playVideo = function(){
	var video_id = $(".video-player > object").attr("id");
	var flash = swfobject.getObjectById(video_id);
	
	if (flash) {
		try {
			flash.playVideo();
		} 
		catch (err) {
		
		}
	}
}

/************************************************************
 * 
 * Misc Functions
 * 
 ************************************************************/

getPlaylistPosition = function() {
	var playlistPosition = "";
	
  if ($(".blue-bottom.video-thumb").length > 1) {
    playlistPosition = "middle";
    
    if ($(".blue-bottom.video-thumb.active").is(":first-child")) {
      playlistPosition = "first";
    }
    
    if ($("li.blue-bottom.video-thumb.active").is(":last-child")) {
      playlistPosition = "last";
    }
  }
	
	return playlistPosition;
}

// Load a video via ajax
loadVideo = function(videoSection) {
	// Hide the video section with a callback
	var videoId = window.location.toString().split("#")[1];
	var playlistPosition = getPlaylistPosition();
  var videoInfo = $("li." + videoId);
	
  var flash = swfobject.getObjectById($("object").attr("id"));
  
  if (flash) {
    try {
      flash.loadVideo(videoInfo.find(".video-url").html());
			$("#video-details").html(videoInfo.find(".hidden-info").html());
			resetPlaylistState();
    }
    catch (err) {
    }
	}
	else {
		videoSection.load(heap.urlmap['video'] + "?id=" + videoId + "&playlistPosition=" + playlistPosition, function() {
    
		  $(".video-block").css("visibility", "visible");
		  $("#get-flash").css("display", "block");
		  var lastTag = $(".video-tags ul li a.purple-hover:last");
		  
		  if (lastTag.length > 0) {
		    lastTag.html(lastTag.html().substring(0, lastTag.html().length - 2));
		  }
		  
		  // Re-adjust the container to make sure the ajax-loaded content is aligned 
		  adjustContainer();
		  
		  // Everything is ready, slide down the player
		  videoSection.slideDown(1200);
		  
		  $(".videoTitle").each(function() {
		    $(this).attr("href", $(this).attr("href").split(" - ")[0].replace(/&/,"%26"));
		  });
		  
		  // If there's a search form then the margin will have to be shortened a bit
		  $("#search-form").animate({"margin-top": "50px"});
		});
	}
}; // end loadVideo()

function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
        //most browsers
        return pageYOffset;
    }
    else{
        var B= document.body; //IE 'quirks'
        var D= document.documentElement; //IE with doctype
        D= (D.clientHeight)? D: B;
        return D.scrollTop;
    }
}




/************************************************************
 * 
 * jQuery document.ready Function
 * 
 ************************************************************/

// Bind actions
$(function() {

  if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
    $("#playlist-holder, #empty-playlist-msg, #edit-playlist-msg").hide();
  };

	
	if ($.client.os == "Mac") {
		$(".blue-bottom a.videoTitle").css("top","-2px");
	}
	
	// Special fix for Firefox 3.0.
	if ($.client.browser == "Firefox" && $.browser.version.indexOf("1.9.0") == 0) {
		$(".tags li a").css("font-size", "12pt");
		$("#small-nav a.link").css("font-size", "15pt");
		$(".TradeGothicBoldCondTwenty, #header .fadeLink, .cufon, .director-link, .heap-content a.twenty, #partager-div").css("font-weight", "bold");
		$(".blue-bottom .cufon").css("font-weight", "normal");
		$("#search-box").css("padding-top", "5px");
	}
	
	$(".play-button").live("click", function() {
		$(this).parents("a").click();
	});

	$(".videoTitle").each(function() {
		$(this).attr("href", $(this).attr("href").split(" - ")[0].replace(/&/,"%26"));
	})
	
	// When the user clicks on the url for sharing, the text will be selected.
	$("#partager-url").live("click", function() {
		$("#partager-url").select();
	});	
	
	// Toggle the associated drawer once clicked.
	$(".director-link").live("click", function() {
		if (!$(this).hasClass("on")) {
			// Find the associated drawer
			var drawer = $("#" + $(this).attr("href").split("#")[1]);
			
			// Check whether to hide or show the drawer
			if ($(this).hasClass("on")) {
				// Slide the drawer up to hide it
				drawer.slideUp();
			}
			else {
				// Only one link at a time
				$(".director-link").removeClass("on");
				
				// Check if any other drawers are already open
				if ($(".accordian-block:visible").length > 0) {
					// Hide all other drawers
					$(".accordian-block:visible").slideUp(500, function(){
					
            // Slide the drawer down to show it
            drawer.slideDown();
						
						// Set all the image sizes now that they're shown. This function will finish before the drawer even appears to start
						// so the user won't notice.
						resizeWindow(true);
					});
				}
				else {
					// Slide the drawer down to show it
					drawer.slideDown();
					
					// Set all the image sizes now that they're shown. This function will finish before the drawer even appears to start
					// so the user won't notice.
					resizeWindow(true);
				}
			}
			
			$(this).toggleClass("on");
		}
		
		return false;
	});
	
	// The carousel will not roll automatically when it has an "over" class
  $(".carousel-holder ul").live('mouseover mouseout', function(event) {
    if (event.type == 'mouseover') {
      $(this).addClass("over");
    }
    else {
      $(this).removeClass("over");
    }
  });
  
	// When the overlay is clicked the lightbox should hide
  $("#overlay, #annuler").live("click", function(){
    $("#overlay").fadeTo(500, 0, function() {
			// Hide and reset the z-index
      $("#overlay").hide().css("z-index", 10); 
    });
    
		// Slide up the directors list
    if ($("#director-list").is(":visible")) {
      $("#director-list").slideUp();
			playVideo();
    }
  
	  // Hide the partager lightbox
    if ($("#partager-div").is(":visible")) {
      $("#partager-div").fadeTo(500, 0, function() {$(this).hide();});
      playVideo();
    }
  });
  
	// Submit the search form when the go button is clicked
  $("#go").live("click", function() {
    $(this).parents("form").submit();
		return false;
  });
  
	// Mouse over on the thumbnails
  $('.blue-bottom').live('mouseover mouseleave', function(event) {
    
		// Decide whether to use the height for the feature_block_1 or the
		// other ones which all have the same height
		var sizeIndex = $(this).parents("#feature_block_1").length > 0 ? 0 : 1;
		
		// Find all the relevant elements
    var moreInfoHeight = currentHeights[sizeIndex],
        videoHolder =  $(this).find("div.video-mask"),
				moreInfo = $(this).find(".more-info"),
				playButton = $(this).find(".play-button"),
				addtoPlaylist = $(this).find("a.add-to-playlist, a.remove-from-playlist"),
				videoTitle = $(this).children("a.videoTitle, a.galleryTitle");
		
    if (event.type == 'mouseover') {
    
	    // Decide on the size of the blue-bottom after hover
	    if (moreInfo.find("span").length ==2) {
	      moreInfoHeight = currentHeights[sizeIndex] - 40;
	    }
	    else if (moreInfo.find("span").length == 1){
	      moreInfoHeight = currentHeights[sizeIndex] - 18;
	    }
		
      // Animate the blue bottom to raise up
      videoHolder.stop().animate({
        height:moreInfoHeight
      }, 200);
			
			// Animate the first row to shrink a little bit
			addtoPlaylist.stop().animate({
				"margin-top":"4px",
				"margin-bottom":"2px"
			}, 200);
      videoTitle.stop().animate({
        "margin-top":"7px",
        "margin-bottom":"4px"
      }, 200);
			
			// Show the play button
			playButton.show();
    }
    else if (event.type == 'mouseleave'){
			
			// Animate the blue bottom to lower back down
      videoHolder.stop().animate({
        height:currentHeights[sizeIndex]
      }, 200);
      
			// Animate the first row to grow back
      addtoPlaylist.stop().animate({
        "margin-top":"8px",
        "margin-bottom":"6px"
      }, 200);
      videoTitle.stop().animate({
        "margin-bottom":"10px",
        "margin-top":"11px"
      }, 200);
			
			// Hide the play button
			playButton.hide();
    }
  });
	
	$("#playlist-toggle.closed").live('mouseover mouseleave', function(event) {
		if (event.type == 'mouseover') {
			// Show the "Edit playlist" tooltip
			showEditPlaylistMsg();
		}
		else if (event.type == 'mouseleave') {
			// Hide the "Edit playlist" tooltip
			hideEditPlaylistMsg();
		}
  });
  
	// The open/close buttons on the playlist
  $("#playlist-toggle, #playlist-holder").live("click", function(e) {
		
		var playlistToggle = $("#playlist-toggle")
		
		// Check whether the playlist is closed or open
    if (playlistToggle.hasClass("closed")) {
			// It's closed, the open button has been clicked
      playlistToggle.parent().next().slideDown(500, function() {
        playlistToggle.removeClass("closed");
			});
      $.cookie("playlist-open", "true", {path: '/'});
      $("#empty-playlist-msg, #edit-playlist-msg").animate({bottom: "50px"});
			$("#playlist-holder").addClass("open");
    }
    else if (e.target.id == "playlist-toggle"){
			// It's open, the closed button has been clicked
      playlistToggle.parent().next().slideUp(500, function() {
        playlistToggle.addClass("closed");
			});
      $.cookie("playlist-open", "false", {path: '/'});
      $("#empty-playlist-msg, #edit-playlist-msg").animate({bottom: "-10px"});
      $("#playlist-holder").removeClass("open");
    }
		
    return false;
  });
  
	// When a link which asks the window to scroll to the video player is clicked
  $(".scroll").live("click", function() {
    
		var videoSection = $(this).parents(".accordian-block").find(".video-section");
		
		if (videoSection.length == 0) {
			videoSection = $(".video-section:first");
		}
		
		// Check if there's a video section. If yes, set a new url..
    if (videoSection.length > 0) {
      window.location = window.location.toString().split("#")[0] + "#" + $(this).attr("href").split("#")[1];
    }
    else {
			// .. otherwise load the page with the video player
      return true;
    }
    
    $(".blue-bottom.active").removeClass("active");
    
    $(this).parents(".blue-bottom").addClass("active");
    
		// Load the video with ajax
    loadVideo(videoSection);
    
      // Scroll to the top where the video player will load
      $("body,html,document").animate({
        scrollTop: 70}, 500);
      
    return false;
  });
  
	// When the "+" is hovered
	$(".add-to-playlist").live('mouseover mouseleave', function(event) {
    if (event.type == 'mouseover') {
      // Show the "Add" tooltip
      $(this).siblings(".add-to-playlist-tooltip").show();
    }
    else if (event.type == 'mouseleave'){
			// Hide the tooltip
      $(this).siblings(".add-to-playlist-tooltip").hide();
		}
	});
  
  // When the "-" is hovered
  $(".remove-from-playlist").live('mouseover mouseleave', function(event) {
    if (event.type == 'mouseover') {
      // Show the "Remove" tooltip
      $(this).siblings(".remove-from-playlist-tooltip").show();
    }
    else if (event.type == 'mouseleave'){
      // Hide the tooltip
      $(this).siblings(".remove-from-playlist-tooltip").hide();
    }
  });
	
	// When the "+" is clicked
  $(".add-to-playlist").live("click", function() {
		var videoId = $(this).parents(".blue-bottom").find("a.scroll").attr("href").split("#")[1];
		var imageSource = $(this).parents(".blue-bottom").find(".playlist-img-src").html();
		
		// If the playlist is shown, add the video..
    if ($("#playlist").is(':visible')) {
      addToPlaylist(videoId, imageSource);
    }
    else {
			// ..otherwise show the playlisSt and then add it
      $("#playlist").slideDown(500, function() {
        $.cookie("playlist-open", "true", {path: '/'});
        $("#playlist-toggle").removeClass("closed");
        addToPlaylist(videoId, imageSource);
      });
    }
    return false;
  });
  
  // When the "-" is clicked
  $(".remove-from-playlist").live("click", function() {
    var videoId = $(this).parents(".blue-bottom").find("a.scroll").attr("href").split("#")[1];
    
    $("li.playlist_" + videoId + " a.playlist-thumb-remove").click();
		
    return false;
  });
  
	// When the playlist's delete link is clicked
  $("#playlist-supprimer").live("click", function() {
		// Delete all the items and then remove them from the DOM
    $($("#playlist .item:not(.empty)").get().reverse()).each(function() {
      removePlaylistThumb($(this));
    });
    
		// Reset the playlist carousel
    $("#playlist-ul").css("left", "0px");
		
		// Reset the playlist current index
    nextPlaylistThumb = 0;
    
    return false;
  });
  
	// When the playlist play button is clicked
	$("#playlist-jouer").live("click", function() {
		
		
    // Check if there are any items in the playlist
    if ($("#playlist-ul li:not(.empty)").length == 0) {
			showPlaylistEmptyMsg();
			return false;
		} 
		
		window.location = $(this).attr("href");
		
		return true;
	});
	
	// When the playlist share button is clicked
  $("#playlist-partager").live("click", function() {
		
		// Check if there are any items in the playlist
		if ($("#playlist-ul li:not(.empty)").length == 0) {
			showPlaylistEmptyMsg();
		}
		else {
			// Get the playlist URL
			var playlistURL = getPlaylistURL();
			
			// Set the url in the input and in the facebook/email links
			$("#partager-url").val(playlistURL);
			$("#facebook-share").attr("href", $("#facebook-share").attr("href").replace("***", playlistURL));
			
			// Set the overlay to be above the directors list
			$("#overlay").css("z-index", 30);
			$("#overlay").fadeTo(500, 0.85);
			$("#partager-div").fadeTo(500, 1);
			pauseVideo();
		}
    return false;
  });
  
	// When the little "X" in a playlist thumb is clicked
  $(".playlist-thumb-remove").live("click", function() {
		// Remove the playlist thumb
    removePlaylistThumb($(this).parent());
		
		// Decrement the playlist index
    nextPlaylistThumb--;
    
    return false;
  });
  
	// When a directors link is clicked
  $("#nav-directors, #small-realisateurs").click(function() {
		// If the overlay is visible hide it, otherwise show it
    if ($("#overlay").is(":visible")) {
      $("#overlay").fadeOut(500);
    }
    else {
      $("#overlay").fadeTo(500, 0.85);
      pauseVideo();
    }
    
    // If the director list is visible hide it, otherwise show it
    if ($("#director-list").is(":visible")) {
      $("#director-list").slideUp();
    }
    else {
      $("#director-list").slideDown();
    }
    
    return false;
  });
  
	// If a link has the fadeLink class, fade the page out before loading the href
  $(".fadeLink").live('click', function(e) {
    e.preventDefault();
		var link = $(this).attr("href")
    $("body").fadeOut(200, function() {
			$("body").remove();
      document.location = link;               
    });
  });
	
  $.ajaxSetup({
    error:function(x,e){
      if(x.status==404){
        // Hide the loading icon gif
        $("#loading-icon").hide();
					
        $(window).unbind("scroll");
      }
    }
  });

  // Search auto-load
	if ($("#search-results").length > 0) {
		// Retrieve the GET variables
  	get_vars = "?" + window.location.toString().split("?")[1];
    get_vars = get_vars.split("#")[0];
		
		// Initialize the page to load at 2
  	page_num = 2;
  	
		// Call the function when the user scrolls to the bottom
  	$(window).scroll(function(){
  		if (getScrollTop() >= $(document).height() - $(window).height()) {
  			
				if (!$("#loading-icon").is(":visible")) {
					$("#loading-icon").show();
					
					// Get the upcoming results
					$.get(heap.urlmap.search_ajax + get_vars + "&page=" + page_num, function(data){
						
						// If there are no more resutls, unbind this functionality
						if ($(data).find("li").length == 0) {
							$(window).unbind("scroll");
						}
						else {
							// Append the results
							$("#search-results .accordian-block").append(data);
							
							// Increment the next page number to retrieve
							page_num++;
							
							// Refresh cufon
							//Cufon.refresh();
							
							// Realign all the thumbs
							resizeWindow(true);
						}
						
            // Hide the loading icon gif
            $("#loading-icon").hide();
					}, false);
				}
  		}
  	});
  }
  
	// Call the doResize function
  $(window).resize(function() {
    doResize();
  });
	
	$("#toggler").live("click", function() {
		$("body").toggleClass("twenty");
    $(this).toggleClass("green");
		return false;
	});
  
  $("#font-weight").live("click", function() {
    $("body").toggleClass("bold");
		$(this).toggleClass("green");
    return false;
  });
});



/************************************************************
 * 
 * jQuery window.load Function
 * 
 ************************************************************/

// This is executed once all the images are done loading
$(window).load(function() {
	// Fade everything in
  $("body").fadeIn(600);
	
	// Setup everything alignment
  resizeWindow();
  
	if ($("li.blue-bottom:visible").length > 0 && window.location.toString().indexOf("#") == -1 && $("#my-selection").length > 0) {
		// Get the first video thumb
		var firstVideoThumb = $("li.blue-bottom:visible:eq(0)");
		
		// Get the video id from the thumb
		var videoId = firstVideoThumb.find("a.scroll").attr("href").split("#")[1];
		
		// Set the window target to the id
		window.location = window.location.toString().split("#")[0] + "#" + videoId;
		
		// Set the first video thumb to be active
	  firstVideoThumb.addClass("active");
	  
		// If there's a video being requested, load it
	    if ($(".video-section").length > 0) {
			
	      var videoSection = $(".video-section");
			
	      loadVideo(videoSection);
	  }
	}
	else if ($("li.blue-bottom:visible").length > 0 && window.location.toString().indexOf("#") != -1 && $(".video-section").length > 0) {
		// Load a gallery
		if (window.location.toString().split("#gallery-")[1]) {
			galleryId = window.location.toString().split("#gallery-")[1];
			
			$(".director-link.photo-link").click();
			$(".gallery-" + galleryId).click();
		}
		
		var videoId = window.location.toString().split("#")[1];
		$(".blue-bottom." + videoId + ":eq(0)").addClass("active");
		
	  var videoSection = $(".blue-bottom." + videoId + ":eq(0)").parents("accordian-block").find("video-section");
	  
	  if (videoSection.length == 0) {
				videoSection = $(".video-section:first");
	  }
	      loadVideo(videoSection);
	}
	
		
  
	// If the playlist was last closed, keep it closed
  if ($.cookie("playlist-open") != "true") {
    var timeoutForPlaylistHide = window.setTimeout('$("#playlist-toggle").click()',  3000);
  }
  
	for (i=1; i<=4;i++) {
		if ($("#feature_block_" + i + " > ul > li.blue-bottom").length > 1) {
		  $("#feature_block_" + i + " > ul").append($("#feature_block_" + i + "  li.blue-bottom:first").clone());
	  }
	}
	
  // Set up al lthe carousels
	if ($("#feature_block_1 li.blue-bottom").length > 1)
    $("#feature_block_1").jCarouselLite({auto:10000, visible:1, afterEnd:  updateIndex, speed:1000, new_circular:true});
		
  if ($("#feature_block_2 li.blue-bottom").length > 1)
    $("#feature_block_2").jCarouselLite({auto:8000, visible:1, afterEnd:  updateIndex, speed:1000, new_circular:true});
	
  if ($("#feature_block_3 li.blue-bottom").length > 1)
    $("#feature_block_3").jCarouselLite({auto:8000, visible:1, afterEnd:  updateIndex, speed:1000, new_circular:true});
	
  if ($("#feature_block_4 li.blue-bottom").length > 1)
    $("#feature_block_4").jCarouselLite({auto:8000, visible:1, afterEnd:  updateIndex, speed:1000, new_circular:true});
		
  if ($("#director-carousel li").length > 0) {
    var pages = new Array();
    $("#director-carousel li").each(function() {
      pages[$(this).index()] = ".externalControl ." + parseInt($(this).index() + 1)
    });
    $("#director-carousel").jCarouselLite({visible:1, btnGo:pages, afterEnd:updateIndex, speed:600 });
  }
  
	// Load the empty playlist item into a global variable
  $.get(heap.urlmap['playlist_item'], function(data) {
    emptyPlaylistItem = $(data).width(0);
  
	  // Load the playlist from cookies
	  setupPlaylist();
  }, false);
	
	// Initialize the email share link and the facebook share link 
	facebookPartagerLink = $("#facebook-share").attr("href");
  
  // Center the playlist
  resizeBorder();
  
  // Preload all the css hover images
  if (navigator.platform != 'iPad' && navigator.platform != 'iPhone' && navigator.platform != 'iPod') {
    try {
      $.preloadCssImages();
    } catch(e){}
  }
});



/************************************************************
 * 
 * External Plugins
 * 
 ************************************************************/

/* Cookie plugin */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options=$.extend({},options);options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};

/* preloadCssImages */
jQuery.preloadCssImages=function(h){function m(){clearTimeout(o);if(c&&c.length&&c[g]){g++;if(h.statusTextEl){var a=c[g]?"Now Loading: <span>"+c[g].split("/")[c[g].split("/").length-1]:"Loading complete";jQuery(h.statusTextEl).html('<span class="numLoaded">'+g+'</span> of <span class="numTotal">'+c.length+'</span> loaded (<span class="percentLoaded">'+(g/c.length*100).toFixed(0)+'%</span>) <span class="currentImg">'+a+"</span></span>")}if(h.statusBarEl){a=jQuery(h.statusBarEl).width();jQuery(h.statusBarEl).css("background-position", -(a-(a*g/c.length).toFixed(0))+"px 50%")}p()}}function p(){if(c&&c.length&&c[g]){var a=new Image;a.src=c[g];a.complete?m():jQuery(a).bind("error load onreadystatechange",m);o=setTimeout(m,h.errorDelay)}}function q(a,n){for(var k=false,l=[],r=[],i,d=a.length;d--;){var f="";if(n&&n[d])i=n[d];else{i=(a[d].href?a[d].href:"window.location.href").split("/");i.pop();if(i=i.join("/"))i+="/"}if(a[d].cssRules||a[d].rules){j=a[d].cssRules?a[d].cssRules:a[d].rules;for(var e=j.length;e--;)if(j[e].style&&j[e].style.cssText){var b= j[e].style.cssText;if(b.toLowerCase().indexOf("url")!=-1)f+=b}else if(j[e].styleSheet){l.push(j[e].styleSheet);k=true}}if(f=f.match(/[^\("]+\.(gif|jpg|jpeg|png)/g))for(e=f.length;e--;){b=f[e].charAt(0)=="/"||f[e].match("://")?f[e]:i+f[e];jQuery.inArray(b,c)==-1&&c.push(b)}if(!k&&a[d].imports&&a[d].imports.length){f=0;for(e=a[d].imports.length;f<e;f++){b=a[d].imports[f].href;b=b.split("/");b.pop();if(b=b.join("/"))b+="/";b=b.charAt(0)=="/"||b.match("://")?b:i+b;r.push(b);l.push(a[d].imports[f])}}}if(l.length){q(l, r);return false}for(k=h.simultaneousCacheLoading;k--;)setTimeout(p,k)}h=jQuery.extend({statusTextEl:null,statusBarEl:null,errorDelay:999,simultaneousCacheLoading:2},h);var g=0,c=[],j,o;q(document.styleSheets);return c};
