if( typeof window.console == 'undefined'){
    window.console = {
        log:function(){}
    };
}

//
// Global variables.
//

var currentlyScrolling = false,
	animatingPage = true, // Block behaviors until page is loaded.
	animatingMenu = false;

var lang = window.location.href.match(/fr/) ? 'fr' : 'en';

var bgSize = null;


//
// Global handlers.
//

var sidleeTvIPadScroller;

// Fire when HTML is loaded and JQuery is ready.
$(document).ready(function() {
	// Use deep linking URL to choose initial page.
	var link = window.location.hash.replace(/^#/, '');

	var f = function() {
		resizeContent();
		runLoadAnimations();
		setupMenuBehaviors();
	};

//	if (link == '')
		loadPage('home', null, f);

//	else
//		loadPage(deepLinks.getPageName(link), null, f);
//loadContent(pages.get('home'));

	setupArrowAnimations();

	$('#home').bind('click',function() {
		window.location.reload();
	});

	// Animate the thumb in the protfolio
	$('.portfolio .thumb').live('mouseenter', function() {
		if(! $(this).children('.overlay').length ) $(this).append('<span class="overlay"></span>');
		$(this).find('.overlay').stop().animate({ marginTop: "0px", marginLeft: "0px", height: "110px", width: "150px" });
	}).live('mouseleave', function() {
		$(this).find('.overlay').stop().animate({ marginTop: "-20px", marginLeft: "-20px", height: "150px", width: "190px" });
	});

	// Special init for iPhone/iPad.
	if (isIPhone()) {
		document.ontouchmove = function(e) { e.preventDefault(); return false; }
	}
	
	$('#content > div.scroll > div').each(function(){
		var html = $(this).html();
		$(this).empty();
		$(this).append('<div class="contentWrap">'+html+'</div>');
		var img = $(this).find('img.background');
		$(this).find('img.background').remove();
		$(this).append(img);
		
	});
	

});

// Fire on page load, when images are laoded.
$(window).ready(function() {
});

// Fire on window resize.
$(window).resize(function() {
	resizeContent();
});


//
// Attach event handlers.
//

var secondaryMenuOpened = false;
function setupMenuBehaviors() {

	// Initial mouseenter event before first click.
	$('#mainMenu').mouseenter(function(e){
		if ($('#sidleeTvFull').is(':visible')) {
			sidleetv.fullToClosed();
		}
		if ($('#sidleeTvPreview').is(':visible')) {
			sidleetv.previewToClosed();
		}
	});

	$('#mainMenu ul').hover(function(e){
		if (animatingPage || animatingMenu) return false;
		$('#mainMenu li a').stop(true, false).animate({'color':'#7a7a7a'}, 200);
	}, function(e) {
		if (animatingPage || animatingMenu) return false;
		$('#mainMenu li a').stop(true, false).animate({'color':'#F8F8F8'}, 200);
	});

	var lastOverItem;
	$('#mainMenu li a').hover(function(){
		if (animatingPage || animatingMenu) return false;
		if ($(this).hasClass('on')) return;
		if (lastOverItem) lastOverItem.stop(true, true);
		lastOverItem = $(this);
		$(this).stop(true, true).animate({'color':'#F8F8F8'}, 250);
	}, function(e) {
		if (animatingPage || animatingMenu) return false;
		if ($(this).hasClass('on')) return;
		$(this).stop(true, true).animate({'color':'#7a7a7a'}, 250);
	});

	$('#mainMenu li a').click(function() {
		if (animatingPage || animatingMenu) return false;
		if (secondaryMenuOpened)
			expandSecondaryMenu();
		else
			setupSecondaryMenu();
		var id = $(this).parent().attr('id');
		loadPage(id);
		return false;
	});

	$('#secondaryMenu li a').click(function() {
		if (animatingPage || animatingMenu) return false;
		animatingMenu = true;
		collapseSecondaryMenu(function(){
			animatingMenu = false;
		});
		return $(this).attr('href') != '#';
	});

	$('#secondaryMenu').mouseleave(function(e) {
		// Prevent collapse when leaving left of menu.
		if (e.pageX > 240){ // && ! animatingMenu) {
			animatingMenu = true;
			collapseSecondaryMenu(function(){
				animatingMenu = false;
			});
		}
	});
}

function setupSecondaryMenu() {
	if (secondaryMenuOpened) return;
	secondaryMenuOpened = true;
	animatingMenu = true;
	openSecondaryMenu(function() {
		animatingMenu = false;
	});
	setupFinalMenuBehaviors();
};

function setupFinalMenuBehaviors() {
	$('#mainMenu ul').unbind('mouseenter');
	$('#mainMenu ul').unbind('mouseleave');

	$('#mainMenu').mouseenter(function(e){
		if ($('#sidleeTvFull').is(':visible')) {
			sidleetv.fullToClosed();
			return;
		}
		if ($('#sidleeTvPreview').is(':visible')) {
			sidleetv.previewToClosed();
			return;
		}
		if (e.pageX < 40 && ! animatingMenu && ! currentlyScrolling)
			animatingMenu = true;
			expandSecondaryMenu(function(){
				animatingMenu = false;
			});
	});
}

//
// Global behaviors.
//

function resizeContent() {
	var sidleeWidth =
		  $(window).width()
		- 39;
	$('#sidleeTv').width(sidleeWidth);
	if ($('#sidleeTvFull').is(':visible')) {
		$('#sidleeTv').css('left', -sidleeWidth + 197);
	}

	// Resize contentPane container to fit content and sidleetv width.
	$('#contentPane').width(
		  $(window).width()
		+ $('#sidleeTv').outerWidth(true)
		+ 500 /* abritrary buffer to prevent float wrapping */
		);

	// Resize content to fit window width.
	$('#content').width(
		  $(window).width()
		- 200 // Opened menu width
		- 37  // Closed SidleeTV
		);

	resizeContentBackground();

	// Resize page height.
	$('#page').height($(window).height());
	$('#page #content > div.scroll > div').height($(window).height());
	$('#page #content .contentWrap').height($(window).height());

	centerContentVertically();
	
}
var backgroundMargin={
	w:0,
	h:0
};
function resizeContentBackground() {
	
	var media = $("#content img.background");
	var mediaSize={
		h:600,
		w:720
	};
	
	var holder = $('#content');
	var holderSize = {
		h:holder.height(),
		w:holder.width()
	}
	
	// adjust media to it's parent width
	// make sure orginal media ratio is respected
	
	
	var tW = holderSize.w;
	var tH = (holderSize.w / mediaSize.w) * mediaSize.h;
	
	if(tH < holderSize.h){
		var tH = holderSize.h;
		var tW = (holderSize.h / mediaSize.h) * mediaSize.w
	}
	
	var verticalOffset = ($(window).height() - 640) / 2;
	if (verticalOffset <= 0) verticalOffset = 0;
	
	
	backgroundMargin={
		w: tW/-2,
		h: tH/-2
	}
	//apply height width and centers media
	media.css({
		'height':tH+'px',
		'width':tW+'px',
		'margin-left':(backgroundMargin.w)+'px',
		'margin-top':(backgroundMargin.h)+'px'
	});
	
		/*
	var bgImage = $("#content img.background");
	var currentWidth = $("#content img.background").width();
	var newWidth = $('#content').width();
	if (newWidth < 600) {
		return;
	}
	var oldWidth = bgImage.width();
	var ratio = $(window).height() / $('#content').width();
	if (ratio > 0.55)
		newWidth = newWidth + (ratio - 0.55) * 900;
	bgImage.width(newWidth);
	*/
	
}

function centerContentVertically() {
	var verticalOffset = ($(window).height() - 640) / 2;
	if (verticalOffset <= 0) verticalOffset = 0;
	console.log('Vertical centering offset: ' + verticalOffset);
	$('#mainMenu ul').css('margin-top', verticalOffset);
	$('#secondaryMenu #containerNum').css('margin-top', verticalOffset);
	//$('#content > div.scroll > div').css('padding-top', verticalOffset);
	$('#content .contentWrap').css('padding-top', verticalOffset);
	
	//$('#content img.background').css('margin-top', backgroundMargin.h-verticalOffset);
	//$('#content img.background').css('top', -verticalOffset);
	$('#content .alignTop').css({'top':-verticalOffset, 'position':'relative'});
	if (verticalCenterResizeCallback) verticalCenterResizeCallback();
}

var verticalCenterResizeCallback = null;
function startCenterElementVertically(elementParam) {
	// Create a new closure to hold current value.
	var closure = function() {
		var element = elementParam;
		var container = element.parent();
		var offsetTop =  (Math.min(container.height(), $(window).height()) - element.height()) / 2;
		if (offsetTop < 0) offsetTop = 0;
		container.css('padding-top', offsetTop);
	};

	// Add closure to hash.
	verticalCenterResizeCallback = closure;

	// Call closure now.
	closure();
}

function stopCenterElementVertically() {
	verticalCenterResizeCallback = null;
}

//
// Menu behaviors.
//

var animatingMenu = false;
function openSecondaryMenu(callback) {
	$('#secondaryMenu').show(0, function() {
		$('#contentPane').animate({'left':40}, 400, function() {
			$('#secondaryMenu').css({'position':'absolute', 'top':0, 'left':0, 'z-index':4, 'float':'none'});
			$('#contentPane').css({'padding-left':"200px"});
			if (callback) callback();
		});
	});
}

function expandSecondaryMenu(callback) {
	if (currentlyScrolling) return;
		$('#secondaryMenu').stop(true, true).animate({'left':200}, 400, function() {
			$('#secondaryMenu').queue(function(next) {
				$('#mainMenu').css('z-index', 5);
				next();
			});
			if (callback) callback();
		});
}

function collapseSecondaryMenu(callback) {
	if (currentlyScrolling) return;
	$('#secondaryMenu').stop(true, true).queue(function(next) {
		$('#mainMenu').css('z-index', '');
		next();
	});
	$('#secondaryMenu').animate({'left': 0}, 400, function() {
		if (typeof callback === 'function') callback();
	});
}

function expandSidleeTv(slideSpeed, callback) {
	if (currentlyScrolling) return false;
		$('#contentPane').queue(function(next) {
			if (secondaryMenuOpened) {
				$('#mainMenu').css('width', 40);
				$('#mainMenu').css('z-index', 5);
			}
			next();
		});
		$('#contentPane').animate({'margin-left': -200}, slideSpeed, function() {
		if (typeof callback === 'function') callback();
	});
}

function collapseSidleeTv(slideSpeed, callback) {
	$('#contentPane').animate({'margin-left': 0}, slideSpeed, function() {
		$('#contentPane').queue(function(next) {
			if (secondaryMenuOpened) {
				$('#mainMenu').css('width', 240);
				$('#mainMenu').css('z-index', '');
			}
			next();
		});
		if (typeof callback === 'function') callback();
	});
}

function expandSidleeTvFull(slideSpeed, callback) {
	$('#sidleeTv').show().animate({
		left: - $(window).width() + 237,
		duration: slideSpeed
	}, function(){
		if (typeof callback === 'function') callback();
	});
}

function collapseSidleeTvFull(slideSpeed, callback) {
	var windowWidth = $(window).width();
	$('#sidleeTv').animate({
		left: -45,
		duration: slideSpeed
	}, function(){
	    // Need to be smoothened
	    collapseSidleeTv('fast', callback);
	});
}

/**
 * Main function to load another page.
 */
function loadPage(name, param, callback) {
	console.log('loadPage ' + name + ' ' + param);
	$('.languageBox:visible').hide();
	var page = pages.get(name, param);
	if (!page) {
		if (console) console.log('Missing page: ' + name);
		return;
	}
	displaySecondaryMenu(page, function() {
		loadContent(page, function() {
			displayContent(page, callback);
			collapseSecondaryMenu();
		});
	});
	location.hash = deepLinks.getLink(page.section);
}

/**
 * Displays the appropriate secondary menu for the resquested page.
 */
function displaySecondaryMenu(page, callback) {
	if (pages.getCurrent().section == page.section) {
		if (callback) callback();
		return;
	}

	$('#mainMenu li a.on').stop(true, true).animate({'color':'#7a7a7a'}, 250);
	$('#mainMenu li a.on').removeClass('on');
	$('#mainMenu li a').eq(page.section - 1).css('color', '#F8F8F8');
	$('#mainMenu li a').eq(page.section - 1).addClass('on');

	var menuSlider = $('#secondaryMenuSlider');
	var secondaryMenu = $('> div', menuSlider).eq(page.section - 1);

	// Slide secondaryMenuSlider.
	var heightSlider = menuSlider.height();
	var top = menuSlider.offset().top - secondaryMenu.offset().top;
	menuSlider.stop(true, true).animate({top:top}, 1000, 'easeInOutExpo', function() {
		if (callback) callback();
	});

	// Slide numbers.
	var secondaryMenuNumber = $('#numbers > div').eq(page.section - 1);
	var topNum =  $('#numbers').offset().top - secondaryMenuNumber.offset().top;
	$('#numbers').stop(true, true).animate({top:topNum}, 'slow', 'easeInOutExpo');
}

/**
 * Loads the content into the page, if not already loaded.
 */
function loadContent(page, callback) {
	var sectionName = 'section' + page.name.charAt(0).toUpperCase() + page.name.slice(1);
	var sectionId = (page.param) ? sectionName + '-' + page.param : sectionName;

	// Check if page is already loaded.
	var section = $('#' + sectionId);
	if (section.length)	{
		//TODO pass context, don't do whole site now each time
		setupArrowAnimations();
		resizeContentBackground();
		if (callback) callback();
		return;
	}

	// Page needs to be loaded by Ajax.
	var url = '../' + lang + '/contentSections/' + sectionName + '.html';
	var randomNumber = Math.floor(Math.random()*1000); // Force cache bypass.
	$.get(url, {lang:lang, id:page.param, r:randomNumber}, function(data) {
		console.log("Ajax loaded: " + url + (page.param ? ' id=' + page.param : ''));
		var container = $('#content .scroll');
		if (container.length != 1) console.log('ERROR length is ' + container.length);
		var wrapper = $('<div></div>');
		
		wrapper.html(data);
	
		$('> *', wrapper).each(function(index, el) {
			$(el).each(function(){
				var html = $(this).html();
				$(this).empty();
				$(this).append('<div class="contentWrap">'+html+'</div>');
				var img = $(this).find('img.background');
				$(this).find('img.background').remove();
				$(this).append(img);
				
			});
			container.append($(el));
			console.log('Appending content #' + $(el).attr('id'));
			
		});
		
		

		//TODO pass context, don't do whole site now each time
		setupArrowAnimations();
		resizeContentBackground();
		centerContentVertically();

		if (callback) callback();
	}, 'html');
}

/**
 * Display the requested content.
 */
function displayContent(newPage, callback) {
	var sectionName = 'section' + newPage.name.charAt(0).toUpperCase() + newPage.name.slice(1);
	var sectionId = (newPage.param) ? sectionName + '-' + newPage.param : sectionName;
	var nextContent = $('#' + sectionId);
	if (nextContent.length < 1) {
		console.log('Next content ' + '#' + sectionId + ' not found inside container');
		return;
	}

	var execQueue = buildPageExecutionQueue(nextContent, newPage, callback);

	var oldPage = pages.getCurrent();
	if (oldPage == null) {
		// First page to be displayed.
		nextContent.css('display', 'block');
		execQueue();
		pages.setCurrent(newPage);
		return;
	}

	// Choose animation depending if page is in a different section than previous page.
	var animation;
	if (oldPage.section == newPage.section) {
		animation = 'bounce';
	} else {
		animation = (oldPage.section < newPage.section) ? 'up' : 'down';
	}

	animateContent(oldPage, newPage, sectionId, animation, execQueue);
	pages.setCurrent(newPage);
}

/*
 * Build page display execution queue. Must be called when page is not hidden, ottherwise
 * some dimension properties will be set to 0.
 */
function buildPageExecutionQueue(nextContent, newPage, callback) {
	var queue = $('#content').stop(true, false); // Container to use as JQuery execution queue.
	return function() {
		console.log('Executing queue for ' + nextContent.attr('id'));

		// First make sure page is completely loaded, otherwise wait for images.
		if (! nextContent.hasClass('loadComplete')) {
			queue.queue(function(next) {
				nextContent.addClass('loadComplete');
				waitForContent(nextContent, next);
			});
		}

		// Execute onload page handler.
		if (newPage.onload) {
			queue.queue(function(next) {
				console.log('Executing onload for ' + nextContent.attr('id'));
				newPage.onload();
				next();
			});
		}

		// Adjust page width and other properties, now that page is fully loaded.
		queue.queue(function(next) {
			console.log('Executing adjust block for ' + nextContent.attr('id'));
			//adjustContainerWidth('#' + nextContent.attr('id'));
			columnize(nextContent, 250, 350, next);
			//next();
		});

		queue.queue(function(next) {
			//console.log('Executing adjust block for ' + nextContent.attr('id'));
			//adjustContainerWidth('#' + nextContent.attr('id'));
			enableScrollbars(nextContent);
			next();
		});

		// Execute function callback.
		if (callback) {
			queue.queue(function(next) {
				console.log('Executing callback for ' + nextContent.attr('id'));
				callback();
				next();
			});

            queue.queue(function(next) {
                enableScrollbars(nextContent);
                next();
            });
		}
	};
}

/**
 *
 */
function animateContent(oldPage, newPage, nextContentId, type, execQueue) {
	console.log('animateContent ' + nextContentId + ' ' + type);
	var container = $('#content > .scroll');
	// As an additional precaution, hide all but first visible content.
	$('> div:visible', container).slice(1).hide();

	var currentContent = $('> div:visible', container).eq(0);
	var nextContent = $('#' + nextContentId, container);
	if (! nextContent.length) {console.log('Next content ' + '#' + nextContentId + ' not found inside container'); return;};
	nextContent.height($(window).height());

	if (nextContent.attr('id') == currentContent.attr('id')) {
		console.log('Same content ' + nextContent.attr('id'));
		execQueue();
		return;
	}

	console.log('Showing ' + nextContent.attr('id') + ' hiding: ' + currentContent.attr('id'));
	if (type == 'bounce') {
		bounceContent(oldPage, newPage, container, currentContent, nextContent, execQueue);
		return;
	}
	slideContent(oldPage, newPage, container, currentContent, nextContent, (type != 'up'), execQueue);
}

/**
 *
 */
function slideContent(oldPage, newPage, container, currentContent, nextContent, isDirectionDown, execQueue) {
	// Get margin of current content.
	var currentMargin = $(container).css('margin-top').replace(/px$/i, '');
	var slideAmount = $(window).height() * (isDirectionDown ? 1 : -1);

	// Place next content up of current content.
	var currentMarginTop = (currentContent.length == 1) ? parseInt(currentContent.css('margin-top').replace(/px$/i, '')) : 0;
	nextContent.css('margin-top', (currentMarginTop - slideAmount) + 'px');
	nextContent.show();
	if (oldPage.onunload) oldPage.onunload();
	execQueue();

	// Animate container up or down.
	var newContainerMargin = parseInt(container.css('margin-top').replace(/px$/i, '')) + slideAmount;
	if (newContainerMargin < 0) container.css('height', ($(window).height() - newContainerMargin) + 'px');
	container.animate({marginTop:newContainerMargin}, 500, 'easeInExpo', function() {
		if (currentContent) currentContent.hide();
		enableScrollbars(nextContent);
		//columnize(nextContent, 250, 350);
		//adjustContainerWidth('#' + nextContent.attr('id'));
	});
}

/**
 *
 */
function bounceContent(oldPage, newPage, container, currentContent, nextContent, execQueue) {
	var heightContent = $(window).height();
	var currentMargin = parseInt(container.css('margin-top').replace(/px$/i, ''));
	var newMargin = currentMargin + heightContent;
	var f = function() {
		container.css('margin-top', 0); // Reset container margin to 0.
		nextContent.css('margin-top', heightContent).show();
		if (oldPage.onunload) oldPage.onunload();
		execQueue();

		nextContent.animate({marginTop:0}, 500, 'easeInOutExpo', function() {
			//columnize(nextContent, 250, 350);
			//adjustContainerWidth('#' + nextContent.attr('id'));
			enableScrollbars(nextContent);
		});
	};
	if (! currentContent) {
		f();
		return;
	};
	currentContent.animate({marginTop:newMargin}, 500, 'easeInOutExpo', function() {
		currentContent.hide();
		f();
	});
}

function waitForContent(jqElement, callbackParam) {
	// Create closure scope for this method call.
	var closure = function() {
		var callback = callbackParam;

		// Get the list of images to process.
		var images = $('img', jqElement);
		var imageCount = images.length;
		if (imageCount == 0) {
			// No images, run callback immediately.
			if (callback) callback();
			return;
		}

		/*
		 * Function to call when all images are loaded. Callback is executed
		 * and also being prevented from being called more than once.
		 */
		var runCallback = function() {
console.log("runCallback called");
			if (imageCount < 0) return;
console.log("runCallback executing callback");
			imageCount = -1;
			callback();
			images.each(function(index, el) {
				$(el).unbind('load')
				$(el).unbind('error')
			});
		};

		var timeout = (document.all) ? 3500 : 4500; // complete trigger is unreliable under IE, lower timeout
		console.log("Waiting for content (" + imageCount + " images) with id " + jqElement.attr('id'));
//		$(body).delay(timeout).queue(function(next) {
//			if (imageCount <= 0) return;
//			console.log("Timeout, releasing wait on image for content with id " + jqElement.attr('id'));
//			runCallback(); // We waited long enough, run call back now, do not wait for remaining images.
//			next();
//		});
		setTimeout(function() {
			if (imageCount <= 0) return;
			console.log("Timeout, releasing wait on image for content with id " + jqElement.attr('id'));
			runCallback(); // We waited long enough, run call back now, do not wait for remaining images.
		}, timeout);

		images.each(function(index, el) {
			console.log("Processing image " + $(el).attr('src'));

			var checkImage = function() {
				if (imageCount < 0) return true;

				// Image is already complete, fire the callback (fixes browser issues were cached
				// images isn't triggering the load event)
				if (el.complete || el.readyState === 4) {
					console.log("Image " + $(el).attr('src') + " in cache for content with id "
								+ jqElement.attr('id') + ", " + imageCount + " images left.");
					imageCount--;
					if (imageCount == 0) {
						runCallback();
						return true;
					}
				}

				// Check if data URI images is supported, fire 'error' event if not
				else if (el.readyState === 'uninitialized' && el.src.indexOf('data:') === 0 ) {
					console.log("Image " + $(el).attr('src') + " not data uri for content with id "
								+ jqElement.attr('id') + ", " + imageCount + " images left.");
					imageCount--;
					if (imageCount == 0) {
						runCallback();
						return true;
					}
					//$(this).trigger('error');
				}

				return false;
			};

			if (checkImage()) return;

			setTimeout(function() {
				if (imageCount > 0) checkImage();
			}, 500);
			setTimeout(function() {
				if (imageCount > 0) checkImage();
			}, 1000);

			$(el).bind('error', function() {
				console.log("Image " + $(el).attr('src') + " error loading for content with id "
							+ jqElement.attr('id') + ", " + imageCount + " images left.");
				if (imageCount < 0) return true;
				imageCount--;
				if (imageCount == 0) {
					runCallback();
					return true;
				}
			});

			$(el).bind('load', function() {
				console.log("Image " + $(el).attr('src') + " loaded for content with id "
							+ jqElement.attr('id') + ", " + imageCount + " images left.");
				if (imageCount < 0) return true;
				imageCount--;
				if (imageCount == 0) {
					runCallback();
					return true;
				}
			});
		});
	};
	closure();
}

function columnize(container, width, height, callback) {
	console.log("Columnizing check " + container.attr('id') + " width:" + width);
	var targetList = container.find('.columnize');
	var count = targetList.length;
	if (count == 0) {
		if (callback) callback();
	}
	targetList.each(function(index, el) {
		var element = $(el);
		console.log("Columnizing found target " + container.attr('id') + " " + index);
		// If already columnized, don't do it again, or stranges nested structures will be created.
		if ($('> .column', element).length > 0) return;

		element.columnize({
			width:width,
			height:340,
			doneFunc:function() {
				console.log("Columnizing done for target " + container.attr('id') + " " + index);
//				$(window).resize();
				count--;
				if (count == 0) {
					if (callback) callback();
				}
			}
		});
	});
}

function adjustContainerWidth(sectionSelector) {
	console.log('Adjusting content width for selector ' + sectionSelector);
	var containerSelector = sectionSelector + ' .content';
	$(containerSelector).each(function(index, el) {
		var container = $(el);

		var contentWidth = 0;
		$('> .element', container).each(function(index, el) {
			 contentWidth += $(el).outerWidth(true);
		});
		console.log('Adjusting content width to: ' + $(container).css('width'));

		container.find('.columnize').each(function(index, el) {
			$(el).css('width', '6000px'); // Start small to force tall columns.
			$(el).columnize({
				width:250,
				height:350,
				doneFunc:function() {
					$(el).css('width', '10000px'); // Reset width.
					//var contentWidth = 0;
					//$(' > .element', container).each(function(index, el) {
						//if ($(el).children().length > 0)
					//		contentWidth += $(el).outerWidth(true) + 25;
					//});
					//container.css('width', (contentWidth + 50) + "px");
					//console.log('Adjusting content width again to: ' + $(container).css('width'));
					//if (contentWidth > ($('#content').width() - 40))
						//$(sectionSelector + ' .scrollbarWrapper', container).show();
				}
			});
		});

		if (false && container.hasClass('columnize')) {
			//container.css('width', '600px'); // Start small to force tall columns.
			$('> .element', container).columnize({
				width:230,
				height:350,
				doneFunc:function() {
					//var contentWidth = 0;
					//$(' > .element', container).each(function(index, el) {
						//if ($(el).children().length > 0)
					//		contentWidth += $(el).outerWidth(true) + 25;
					//});
					//container.css('width', (contentWidth + 50) + "px");
					//console.log('Adjusting content width again to: ' + $(container).css('width'));
					//if (contentWidth > ($('#content').width() - 40))
						//$(sectionSelector + ' .scrollbarWrapper', container).show();
				}
				//ignoreImageLoading:false
			});
		}

		enableScrollbar(container);
	});
}

function enableScrollbars(container) {
	$('.content', container).each(function(index, el) {
		enableScrollbar($(el));
	});
}

function Scrollbar(containerParam, scrollbarId) {
		var container = containerParam;
		// Check if scrollbar is present, if not return.
		var contentWrapper = container.parent().parent();
		if (! contentWrapper) return;
		var scrollbarWrapper = contentWrapper.next();
		if (! scrollbarWrapper || ! scrollbarWrapper.hasClass('scrollbarWrapper')) return;

		if (isIPhone()) {
			// iPhone/iPad need their touch events remapped to drag events.
			var handle = $('.handle', scrollbarWrapper);
			new ScrollHandle(handle[0], this);
		}

		var sliderInitialOffset = 12;
		var sliderRatio = 1;
		var contentMargin = 24;
		var sidleeTvMargin = 40;

		// Container might be still hidden, and JQuery 1.4.4 only returns values for width() and height()
		// on hidden elements. Do not use outerWidth() or innerWidth() at this point.
		var contentWidth = 0;
		$('> div', container).each(function(index, el) {
			contentWidth += $(el).getHiddenDimensions(true).outerWidth;
		});
		var sliderWidth = $('> div', scrollbarWrapper).width() - $('.handle', scrollbarWrapper).width();
		if (contentWidth <= $('#content').width() - sidleeTvMargin) {
			console.log("Hiding scrollbar, content width: " + contentWidth + " slider width: " + sliderWidth);
			scrollbarWrapper.hide();
			return;
		}
		console.log("Showing scrollbar, content width: " + contentWidth + " slider width: " + sliderWidth);
		scrollbarWrapper.show();

		this.startHandler = function(event, ui) {
			currentlyScrolling = true;
			sliderWidth = $('> div', scrollbarWrapper).width() - $('.handle', scrollbarWrapper).outerWidth(true);
			contentWidth = 0;
			$('> div', container).each(function(index, el) {
				contentWidth += $(el).getHiddenDimensions(true).outerWidth;
			});
			contentWidth += 30;
			// Set handle width here.
		}

		this.dragHandler = function(event, ui) {
			var sliderScroll = ui.offset.left - scrollbarWrapper.offset().left;
			if (sliderScroll < 0) sliderScroll = 0;

			var sliderPosition = sliderScroll - sliderInitialOffset;
			var sliderPercent = sliderPosition / sliderWidth;
			//$('#_ss2').text(sliderPercent);

			var contentScroll = (contentWidth - $('#content').width() + sidleeTvMargin) * sliderPercent;
			if (contentScroll < 0) contentScroll = 0;
			contentWrapper.scrollTo(contentScroll + 'px',  {axis: 'x'});
		}

		this.stopHandler = function(event, ui) {
			currentlyScrolling = false;
		}

		$('.handle', scrollbarWrapper).draggable({
			containment: 'parent',
			axis: 'x',
			cursor: 'pointer',
			delay: 10,
			distance: 1,
			scroll: false,
			addClasses: false,
			start: this.startHandler,
			drag: this.dragHandler,
			stop: this.stopHandler
		});
}

function enableScrollbar(containerParam) {
	var scrollbarId = containerParam.parent().attr('id') + " " + containerParam.index();
	console.log("Checking scrollbar for container " + scrollbarId);
	// Create closure scope for this scrollbar.
	var scrollbar = new Scrollbar(containerParam, scrollbarId);
}

function createVideoPlayer(container, playerId, videoUrl, width, height, callback, autoplay) {
	if (isIPhone()) {
		createHtml5VideoPlayer(container, playerId, videoUrl, width, height, callback, autoplay);
	} else {
		createFlashVideoPlayer(container, playerId, videoUrl, width, height, callback, autoplay);
	}
}

function createFlashVideoPlayer(container, playerId, videoUrl, width, height, callback, autoplay) {
	// Create video holder div. Will be replaced by swfobject.
	var playerDiv = $('<div></div>');
	playerDiv.attr('id', playerId);
	container.empty().append(playerDiv);

	// Setup Flash config for SWFObject.
	var flashvars = {
		videoURL: videoUrl,
//		autoplay: autoplay ? 'true' : 'false'
//		forceHeight: 360,
//		forceWidth: 300,
//		maxWidth: 500,
//		maxHeight: 400,
		playText: lang =='fr' ? 'Jouer' : 'Play',
		pauseText: lang == 'fr' ? 'Pause' : 'Pause',
		id: playerId
//		posterFrameTime: 3 // Nb seconds.
	};

	if (width) flashvars.forceWidth = width;
	if (height) flashvars.forceHeight = height;
	if (typeof autoplay === 'undefined') autoplay = false;

	flashvars.autoplay = autoplay;

	var params = {
		allowfullscreen: 'true',
		scale: 'noscale',
		wmode: 'opaque',
		align: 'l',
		salign: 'lt',
		allowscriptaccess: 'sameDomain',
		allownetworking: 'all',
		swliveconnect: 'true',
		loop: 'false',
		menu: 'true',
		quality: 'autolow',
		bgcolor: '#141414'
	};
	var attributes = {
		styleclass: 'videoPlayer'
	};

	// Create video player through SWFObject.
	swfobject.embedSWF("../flash/SidLeeVideoPlayer.swf?v=8", playerId, '640', '480', "9.0.0", false,
					   flashvars, params, attributes, function(e){
		// If a callback function was defined, call it after load (on success or on error)
		if (! e.success) { console.log('Cannot load video player.'); }
		if (callback) callback(e);
	});
}

function createHtml5VideoPlayer(container, playerId, videoUrl, width, height, callback, autoplay) {
	var video = $('<video id="' + playerId + '" class="" width="' + width + '" height="' + height
				+ '" controls="controls" preload="auto" class="videoPlayer"></video>');
	video.attr('id', playerId);

	var srcMp4 = video.append('<source class="mp4" type="video/mp4; codecs=\'avc1.42E01E, mp4a.40.2\'" />');
	srcMp4.attr('src', videoUrl);
	//srcMp4.attr('src', 'videos/sid_lee_reel_2009_high_fr.mp4');

	//var srcOgg = video.append('<source class="ogg" type="video/ogg; codecs=\'theora, vorbis\'" />');
	//srcOgg.attr('src', videoUrl);
	//srcOgg.attr('src', 'videos/01_sortez_High.

	container.empty().append(video);
	container.show();

	resizeFlashVideo(width, height, playerId);

	var e = { success: true };
	if (callback) callback(e);
}


/**
 * Destroy a video player.
 */
function killVideoPlayer(playerId) {
	var container = $('#' + playerId).parent();
	container.empty();
}

function loadPageSurvol(anchor, index) {
	loadPage('sidleeSurvol', null, function() {
		scrollSurvol(anchor, index);
	});
}

function scrollSurvol(anchor, index) {
	var container = $('#sectionSidleeSurvol #survol_wrapper');
	container._scrollable();
	container.scrollTo('#' + anchor + '-content', 1000, {axis:'x', margin:true, easing:'easeInOutQuart'});

	var scrollBarHandleNewLeft = ($('#sectionSidleeSurvol .scrollbarWrapper div').outerWidth(true) + 150) / 7 * index;
	$('#sectionSidleeSurvol .scrollbarWrapper .handle').animate({ left: scrollBarHandleNewLeft }, 1000);
}

function showLanguageBox(box){
	hideLanguageBox(null, function() {
		var leftMargin  = ($(window).width() - $("#" + box).width()) / 2;
		var topMargin  = ($(window).height() - $("#" + box).height()) / 2;

		$("#" + box).css("left", leftMargin + 'px');
		$("#" + box).css("top", $(window).height() + 'px');
		$("#" + box).show();
		$("#" + box).animate({"top": topMargin + 'px'}, 300);
	});
}

function hideLanguageBox(box, callback) {
	var box = $('.languageBox:visible');
	if (box.length <= 0) {
		if (callback) callback();
		return;
	}
	box.animate({"top": $(window).height() + 'px'}, 250, function() {
		box.hide();
		if (callback) callback();
	});
}

/**
 * This function is called by the Flash player to adjust height and width accordng to video size.
 */
function resizeFlashVideo(awidth, aheight, id){
//alert(awidth + "," + aheight, + "," + id);
	var videoPlayer = $('#' + id);
	var playerHolder = videoPlayer.parent();
	videoPlayer.width(awidth);
	videoPlayer.height(aheight);
	if (id == 'realisationsPlayer') {
		playerHolder.width(awidth);
		playerHolder.height(aheight);
	}
	startCenterElementVertically(playerHolder);

//            $('#sidleeTv .videos').width( $('.sidleeTvChannels .channel').width() - $('.sidleeTvChannels .description').outerWidth() -40 );
            $('.sidleeTvChannels').height( $(document).height() - $('.sidleeTvFull .sidleeTvHeader').height()  );

            var videoFreeSpace = $(document).height() - $('.sidleeTvFull .sidleeTvHeader').height() - $('.sidleeTvPlayer .videoTitle').height() - 40,
                videoHeight = $('#sidleeTvVideo').height(),
                margin;
            if (videoFreeSpace < videoHeight ) margin = 0;
            else margin = Math.floor( ( videoFreeSpace - videoHeight ) / 2 );
            $('#sidleeTvVideo').css('marginTop', margin );

}

function setupArrowAnimations() {
    $('.arrow-shift-left').mouseenter(function() {
		$('span', this).stop(true, true)
			.animate({'left': 15}, 100)
			.animate({'left':  0}, 100)
			.animate({'left': 15}, 200)
			.animate({'left':  0}, 200);
    });

    $('.arrow-shift-right, .arrow-left-shift-right').mouseenter(function() {
		$('span', this).stop(true, true)
			.animate({right: 15}, 100)
			.animate({right: 0}, 100)
			.animate({right: 15}, 200)
			.animate({right: 0}, 200);
    });

    $('.arrow-appear').hover(
        function() {
			$(this).animate({'padding-left': 25}, 200);
			$('span', this).delay(100).animate({'left': -5}, 300);
        },
        function() {
			$('span', this).stop(true, false).animate({'left': -30}, 200);
			$(this).stop(true, false).delay(100).animate({'padding-left': 0}, 200);
        }
	);
};

function isIPhone() {
	if((navigator.userAgent.match(/iPhone/i)) ||
	 (navigator.userAgent.match(/iPad/i))) {
	   if (document.cookie.indexOf("iphone_redirect=false") == -1)
	   	return true;
	}
	return false;
};

/**
 * JQuery pluging to provide valid inner/outder width/height for hidden elements.
 */
//Optional parameter includeMargin is used when calculating outer dimensions
(function($) {
$.fn.getHiddenDimensions = function(includeMargin) {
    var $item = this,
        props = { position: 'absolute', visibility: 'hidden', display: 'block' },
        dim = { width:0, height:0, innerWidth: 0, innerHeight: 0, outerWidth: 0, outerHeight: 0 },
        $hiddenParents = $item.parents().andSelf().not(':visible'),
        includeMargin = (includeMargin == null)? false : includeMargin;

    var oldProps = [];
    $hiddenParents.each(function() {
        var old = {};

        for ( var name in props ) {
            old[ name ] = this.style[ name ];
            this.style[ name ] = props[ name ];
        }

        oldProps.push(old);
    });

    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);

    $hiddenParents.each(function(i) {
        var old = oldProps[i];
        for ( var name in props ) {
            this.style[ name ] = old[ name ];
        }
    });

    return dim;
}
}(jQuery));

