/*=======================================*/
/* Initialization functions */
/*=======================================*/

/* General */

var mainMenuIndex, drawingsIndex, pressIndex;
var subMenues;
var mainSectionsNav, drawingsImagesNav, drawingsMenuNav, pressMenuNav, pressIndexNav, blogMenuNav;

var activeOptionsOpacity = 0.4;
var animationSpeed = 400;
var minWindowHeihgtForVScroll = 680;
var sectionNames = new Array('drawings', 'press', 'blog', 'bio');
var subMenuTotalItems = 18;
var pressImagesMaxWidth = 445;

//jQuery.fx.off = true;

function initGeneral() {
	// Contact options toggle
	$('#mainMenuContact_btn').click(function() {
		$('#mainMenuContact').slideToggle('slow');
	});

	// Configure scrollable area for main sections navigation
	// Main menu / sections
	mainSectionsNav = $('#rightColumnScrollerCanvas').scrollable({
		keyboard	: false,
		onBeforeSeek		: function() {
			// Force loading of first content for each section on main menu navigation
			loadSectionFirstContent(0, true);
			//loadSectionFirstContent(1, true);
			loadSectionFirstContent(2, true);

			// Check if right column is higher than window height
			if($('#rightColumn').height() > $(window).height()) {
				// If so, force scroll top of content
				$('#rightColumnVScroll').animate({scrollTop: '0px'}, 200);
			} else {
				// If not, force height of right column to window height
				$('#rightColumnVScroll, #rightColumn, #rightColumnScrollerCanvas').height($(window).height() + 'px');
			}

		}, 
		onSeek		: function() {
			changeMainMenuSelection(this.getIndex());
		}
	}).navigator({
		navi			:	'ul.mainMenuNavi',
		naviItem	:	'li.activeNav'
	});

	// Sub-menues
	subMenuesNav = $('#subMenuesCanvas').scrollable({
		keyboard	: false
	}).navigator({
		navi			:	'ul.mainMenuNavi',
		naviItem	:	'li.activeNav'
	});

	// Configure scrollable area for sub-menues links navigation
	// Drawings
	drawingsMenuNav = $('#drawingsSubMenu').scrollable({
		keyboard	: false,
		prev			: '.drawings_prevNav',
		next			: '.drawings_nextNav',
		vertical	: true,
		onSeek		: function() { checkSubMenuNavigation('drawings', this.getIndex(), this.getSize()); }
	});
	
	// Press
	changePressSubMenu();

	// Init main menu and sub-menues first options
	changeMainMenuSelection(0);

	// Special individual section initialization
	initDrawings();
	initPress();
	initBlog();

	// Sub-menues initialization
	
	// Adjust right column height to match document height and recall function on window resize
	adjustContentHeight();
	
	$(window).resize(function() {
		adjustContentHeight();
	});
}

/* Change sub-menues active link on click */

function initSubMenues() {
	// Unbind all previous click events
	$('div#drawingsSubMenu ul li, div#pressSubMenu ul li, div#blogSubMenu ul li').unbind('click');

	// Drawings
	$('div#drawingsSubMenu ul li').click(function () {
		changeSubMenuSelection('drawings', $('div.subMenu ul li').index(this));
		changeDrawingsContent($('div#drawingsSubMenu ul li').index(this), $(this).children().first().attr('id'));
	});

	// Drawings sub-menu navigation
	checkSubMenuDisplay('drawings');

	// Press
	$('div#pressSubMenu ul li').click(function () {
		changeSubMenuSelection('press', $('div#pressSubMenu ul li').index(this));
		changePressContent($('div#pressSubMenu ul li').index(this), $(this).children().first().attr('id'));
	});

	// Press sub-menu navigation
	checkSubMenuDisplay('press');

	// Blog sub-menu navigation
	checkSubMenuDisplay('blog');
}

/* Change blog sub-menu active link on click */

function initBlogSubMenu() {
	$('#blogSubMenu_years .subMenu').each(function() {
		itemYear = $(this).attr('id').substr($(this).attr('id').lastIndexOf('_') + 1);
		
		// If no scrollable is set, hide navigation buttons and adjust sub-menu height
		if($('#blogSubMenu_year_' + itemYear + ' ul li').size() <= subMenuTotalItems) {
			$(this).css('height', $(this).children().children().first().height());
			$('#blogSubMenuNav_' + itemYear).hide();
		}
		
		$('#blogSubMenu_year_' + itemYear + ' ul li').click(function () {
			itemYear_li = $(this).parent().parent().parent().parent().parent().parent().attr('id');
			itemYear_li = itemYear_li.substr(itemYear_li.lastIndexOf('_') + 1);
			changeSubMenuSelection('blogSubMenu_year_' + itemYear_li, $('#blogSubMenu_year_' + itemYear_li + ' ul li').index(this));
			changeBlogContent($(this).children().first().attr('id'));
		});

		$(this).scrollable({
			keyboard	: false,
			prev			:	'.blog_' + itemYear + '_prevNav',
			next			:	'.blog_' + itemYear + '_nextNav',
			vertical	: true,
			onSeek		: function(yearElement) {
				itemYear_li = this.getRoot().attr('id');
				itemYear_li = itemYear_li.substr(itemYear_li.lastIndexOf('_') + 1);
				checkSubMenuNavigation('blog_' + itemYear_li, this.getIndex(), this.getSize());
			}
		});
		
		// Force sub-menu initial position 
		$(this).data('scrollable').begin();
	});
}

/* Drawings */

function initDrawings() {
	// Configure scrollable area for drawings images navigation
	drawingsImagesNav = $('#drawingsImageScrollerCanvas').scrollable({
		keyboard	: false,
		prev			:	'.drawingsImage_prevNav',
		next			:	'.drawingsImage_nextNav',
		speed			: 0,
		onBeforeSeek	:	function(event, index) {
			if(index < parseInt(this.getSize())) {
				// Fade out before image seek and navigate to selected item
				var element = $('#drawingsImageScrollerCanvas');

				if (element.css('opacity') == 0) {
					return true;
				}

				element.fadeTo('fast', 0, function() {
					if(drawingsImagesNav.data('scrollable')) {
						drawingsImagesNav.data('scrollable').seekTo(index);
					}
				});

				return false;
			}
		},
		onSeek		: function() {
			// Fade content in after seek is completed
			$('#drawingsImageScrollerCanvas').fadeTo('fast', 1);

			// Check content for navigation buttons display
			checkDrawingsImageNavigation(this.getIndex(), this.getSize());
		}
	}).navigator({
		navi			:	'div#drawingsImageNavi'
	});

	// Initially hide previous image navigation button
	$('#drawingsNavigationPrevious').hide();

	// Check image proportions for content orientation toggle (only when first image of set finishes loading)
	var imageWidth = parseInt($('.drawingsImageScrollerItem img').first().width());
	var imageHeight = parseInt($('.drawingsImageScrollerItem img').first().height());

	checkDrawingsContentSize(imageWidth, imageHeight);

	if($(window).height() <= minWindowHeihgtForVScroll) {
		adjustContentHeight();
	}

	// Init sub-menu navigation buttons
	checkSubMenuNavigation('drawings', drawingsMenuNav.data('scrollable').getIndex(), drawingsMenuNav.data('scrollable').getSize())
}

/* Blog */

function initBlog() {
	// Lazyload initialization for images fade in on main scroll
	/* --- fede - chau lazy load
	$('#blogPostSummary img, #blogPostText img').lazyload({
		//placeholder	:	'images/transparent.gif',
		threshold		: -150,
		effect			:	'fadeIn',
		effectspeed	:	600,
		container		: $('#rightColumnVScroll')
	});
	*/
	// Images scroller
	blogImagesNav = $('#blogImagesScrollerCanvas').scrollable({
		keyboard	: false,
		next			:	'.blogImages_nextNav',
		circular	:	true,
		speed			: 0,
		onBeforeSeek	:	function(event, index) {
			if(index <= parseInt(this.getSize())) {
				// Fade out before image seek and navigate to selected item
				var element = $('#blogImagesScrollerCanvas');

				if (element.css('opacity') == 0) {
					return true;
				}

				element.fadeTo('fast', 0, function() {
					if(blogImagesNav.data('scrollable')) {
						blogImagesNav.data('scrollable').seekTo(index);
					}
				});

				return false;
			}
		},
		onSeek		: function() {
			// Fade content in after seek is completed
			$('#blogImagesScrollerCanvas').fadeTo('fast', 1);
		}
	});

	// Unbind all previous click events
	$('#blogSubMenu_years > div > p > a').unbind('click');

	// Set click event for years menu
	var blogYearsSubMenuElement = '#blogSubMenu_years > div > p > a';

	$(blogYearsSubMenuElement).click(function() {
		// Check if the option is already active
		if($(this).attr('class') !== 'active') {
			// Unset previous active option
			$(blogYearsSubMenuElement).fadeTo('fast', 1);
			$(blogYearsSubMenuElement).removeClass('active');

			// Set active option
			$(this).fadeTo('fast', activeOptionsOpacity);
			$(this).addClass('active');

			// Load related posts for clicked years
			changeBlogSubMenu($(this).attr('id'));
		}
	});
}

/* Press */

function initPress() {
	// Index images fade in / out effect on mouse over / out
	$('.pressIndexItem img:not(.imageHolder)').hover(
		function() { $(this).fadeTo(250, activeOptionsOpacity); },
		function() { $(this).fadeTo(350, 1); }
	);

	// Index scroller initializacion
	pressIndexNav = $('#pressIndexScrollerCanvas').scrollable({
		keyboard: false,
		prev: '.press_prevNav',
		next: '.press_nextNav',
		speed: 0,
		onBeforeSeek: function(event, index) {
			if($('#pressIndexScrollerCanvas').html() && index < parseInt(this.getSize())) {
				// Fade out before image seek and navigate to selected item
				var element = $('#rightColumnContent_press');

				if(element.css('opacity') == 0) {
					return true;
				}

				element.fadeTo('fast', 0, function() {
					if(pressIndexNav.data('scrollable')) {
						pressIndexNav.data('scrollable').seekTo(index);
					}
				});
				
				return false;
			}
		},
		onSeek: function() {
			// Fade content in after seek is completed
			$('#rightColumnContent_press').fadeTo('fast', 1);
			checkSubMenuNavigation('press', this.getIndex(), this.getSize());
		}
	});

	// Configure scrollable area for press images navigation
	pressImagesNav = $('#pressImagesScrollerCanvas').scrollable({
		keyboard	: false,
		prev			:	'.pressImages_prevNav',
		next			:	'.pressImages_nextNav',
		speed			: 0,
		onBeforeSeek	:	function(event, index) {
			if(index < parseInt(this.getSize())) {
				// Fade out before image seek and navigate to selected item
				var element = $('#pressImagesScrollerCanvas');

				if (element.css('opacity') == 0) {
					return true;
				}

				element.fadeTo('fast', 0, function() {
					pressImagesNav.data('scrollable').seekTo(index);
				});

				return false;
			}
		},
		onSeek	: function() {
			// Count number of pages in scroller item
			subItemsCount = $('.pressImagesScrollerItem').eq(this.getIndex()).children().size();
			subItemsWidth = $('.pressImagesScrollerItem').eq(this.getIndex()).children().first().width();
			
			// Align next element right arrow according to sub items count
			if(subItemsCount == 2) {
				$('#pressImagesNavigationNext').css('left', (subItemsWidth * 2) + 18);
			} else {
				$('#pressImagesNavigationNext').css('left', subItemsWidth + 19);
			}

			// Fade content in after seek is completed
			$('#pressImagesScrollerCanvas').fadeTo('fast', 1);

			// Check content for navigation buttons display
			checkPressImageNavigation(this.getIndex(), this.getSize());
		}
	});

	// Check image proportions for content orientation toggle (only when first image of set finishes loading)
	var imageWidth = parseInt($('.pressImagesScrollerItem img').first().width());
	var imageHeight = parseInt($('.pressImagesScrollerItem img').first().height());
	
	checkPressContentSize(imageWidth, imageHeight);
}


/*=======================================*/
/* Auxiliary functions */
/*=======================================*/

/* Adjust content height to document / window height */

function adjustContentHeight() {
	var sectionHeight = $('#rightColumnContent_' + sectionNames[mainMenuIndex]).outerHeight() + 200;

	if(mainMenuIndex == 2) {	// Blog
		if($(window).height() <= minWindowHeihgtForVScroll) {
			$('body').css('overflow', 'auto');
			$('#rightColumnVScroll').css('overflow', 'hidden');
			$('#rightColumnVScroll, #rightColumn, #rightColumnScrollerCanvas').height(sectionHeight);
		} else {
			$('body').css('overflow', 'hidden');
			$('#rightColumnVScroll').css('overflow', 'auto');
			$('#rightColumnVScroll').height($(window).height());
		}
	} else {
		if($(window).height() <= minWindowHeihgtForVScroll) {
			$('body').css('overflow', 'auto');
			//$('#rightColumnVScroll').css('overflow', 'hidden');
			$('#rightColumnVScroll, #rightColumn, #rightColumnScrollerCanvas').height(sectionHeight);
		} else {
			$('body').css('overflow', 'hidden');
			$('#rightColumnVScroll').css('overflow', 'auto');
			$('#rightColumnVScroll, #rightColumn, #rightColumnScrollerCanvas').height($(window).height());
		}
	}
}

/* Adjust blog height to loaded content */

function adjustBlogContentHeight() {
		$('#rightColumn, #rightColumnScrollerCanvas').height($('#rightColumnContent_blog').outerHeight() + $('#rightColumnContent_blog').offset().top);
}

/* Adjust press height to loaded content */

function adjustPressContentHeight() {
		$('#rightColumn, #rightColumnScrollerCanvas').height($('#rightColumnContent_press').outerHeight() + $('#rightColumnContent_press').offset().top);
}

/* Check sub-menu display */

function checkSubMenuDisplay(subMenuName) {
	// If there is more than one page in the section's sub-menu, show navigation buttons
	if($('#' + subMenuName + 'SubMenu .subMenuScrollerStrip').children().size() > 1) {
		$('#' + subMenuName + 'SubMenuNav').show();
	} else { // Otherwise, hide them...
		$('#' + subMenuName + 'SubMenuNav').hide();
	}
}

/* Check sub-menu nevigation */

function checkSubMenuNavigation(subMenuName, index, amount) {
	if(index == (amount - 1)) {
		$('.' + subMenuName + '_nextNav').fadeTo('fast', activeOptionsOpacity);
	} else {
		$('.' + subMenuName + '_nextNav').fadeTo('fast', 1);
	}

	if(index == 0) {
		$('.' + subMenuName + '_prevNav').fadeTo('fast', activeOptionsOpacity);
	} else {
		$('.' + subMenuName + '_prevNav').fadeTo('fast', 1);
	}
}

/* Check drawings image navigation */

function checkDrawingsImageNavigation(index, amount) {
	// Get next item index and id
	nextIndex = drawingsIndex + 1;
	nextId = $('div#drawingsSubMenu ul').eq(parseInt(nextIndex / subMenuTotalItems)).children().eq(nextIndex % subMenuTotalItems).find('a').attr('id');

	// Get previous item index and id
	prevIndex = drawingsIndex - 1;
	prevId = $('div#drawingsSubMenu ul').eq(parseInt(prevIndex / subMenuTotalItems)).children().eq(prevIndex % subMenuTotalItems).find('a').attr('id');

	// Hide or show previous image button
	if(drawingsIndex == 0 && $('#drawingsImageScrollerCanvas').data('scrollable').getIndex() == 0) {
		$('#drawingsNavigationPrevious').fadeTo('fast', 0);
	} else {
		$('#drawingsNavigationPrevious').fadeTo('fast', 1);
	}

	// If end of actual gallery is reached, assign navigation to next gallery item
	if(index == (amount - 1)) {
		$('#drawingsNavigationNext').click(function() {
			// If next ID wasn't found reset Drawings navigation to start (0)
			if(!nextId) {
				nextId = $('div#drawingsSubMenu ul li:nth-child(1) a').attr('id');
				nextIndex = 0;
			}

			// Start navigation only if values were obtained
			if(nextId) {
				changeDrawingsContent(nextIndex, nextId);
				changeSubMenuSelection('drawings', nextIndex);

				// Check and scroll drawings sub-menu if necessary
				if(nextIndex == 0) {
					drawingsMenuNav.data('scrollable').begin();
				} else if(drawingsMenuNav.data('scrollable').getIndex() !== parseInt(nextIndex / subMenuTotalItems)) {
					drawingsMenuNav.data('scrollable').next();
				}
			}
		});
	} else {
		// Unbind all previous click events
		$('#drawingsNavigationNext').unbind('click');
	}

	if(index == 0) {
		$('#drawingsNavigationPrevious').click(function() {
			// Start navigation only if values were obtained
			if(prevId) {
				changeDrawingsContent(prevIndex, prevId);
				changeSubMenuSelection('drawings', prevIndex);

				// Check and scroll drawings sub-menu if necessary
				if(drawingsMenuNav.data('scrollable').getIndex() !== parseInt(prevIndex / subMenuTotalItems)) {
					drawingsMenuNav.data('scrollable').prev();
				}
			}
		});
	} else {
		// Unbind all previous click events
		$('#drawingsNavigationPrevious').unbind('click');
	}
}

/* Check press image navigation */

function checkPressImageNavigation(index, amount) {
	// Get next item index and id
	nextIndex = pressIndex + 1;
	nextId = $('div#pressSubMenu ul').eq(parseInt(nextIndex / subMenuTotalItems)).children().eq(nextIndex % subMenuTotalItems).find('a').attr('id');

	// Get previous item index and id
	prevIndex = pressIndex - 1;
	prevId = $('div#pressSubMenu ul').eq(parseInt(prevIndex / subMenuTotalItems)).children().eq(prevIndex % subMenuTotalItems).find('a').attr('id');

	// Hide or show previous image button
	if(pressIndex == 0 && $('#pressImagesScrollerCanvas').data('scrollable').getIndex() == 0) {
		$('#pressImagesNavigationPrevious').fadeTo('fast', 0);
	} else {
		$('#pressImagesNavigationPrevious').fadeTo('fast', 1);
	}

	// If end of actual gallery is reached, assign navigation to next gallery item
	if(index == (amount - 1)) {
		$('#pressImagesNavigationNext').click(function() {
			// If next ID wasn't found reset Drawings navigation to start (0)
			if(!nextId) {
				nextId = $('div#pressSubMenu ul li:nth-child(1) a').attr('id');
				nextIndex = 0;
			}

			// Start navigation only if values were obtained
			if(nextId) {
				changePressContent(nextIndex, nextId);
				changeSubMenuSelection('press', nextIndex);

				// Check and scroll press sub-menu if necessary
				if(nextIndex == 0) {
					pressMenuNav.data('scrollable').begin();
				} else if(pressMenuNav.data('scrollable').getIndex() !== parseInt(nextIndex / subMenuTotalItems)) {
					pressMenuNav.data('scrollable').next();
				}
			}
		});
	} else {
		// Unbind all previous click events
		$('#pressImagesNavigationNext').unbind('click');
	}

	if(index == 0) {
		$('#pressImagesNavigationPrevious').click(function() {
			// Start navigation only if values were obtained
			if(prevId) {
				changePressContent(prevIndex, prevId);
				changeSubMenuSelection('press', prevIndex);

				// Check and scroll press sub-menu if necessary
				if(pressMenuNav.data('scrollable').getIndex() !== parseInt(prevIndex / subMenuTotalItems)) {
					pressMenuNav.data('scrollable').prev();
				}
			}
		});
	} else {
		// Unbind all previous click events
		$('#pressImagesNavigationPrevious').unbind('click');
	}
}

/* Set main menu active option */

function changeMainMenuSelection(index) {
	mainMenuIndex = index;

	// Close contact section if it's visible and it was not clicked
	if($('#mainMenuContact').is(':visible')) {
		$('#mainMenuContact').slideToggle('fast');
	}

	// Unset previous active option
	$('#mainMenu ul li a').fadeTo('fast', 1);
	$('#mainMenu ul li').removeClass('active');

	// Set active option
	$('#mainMenu ul li a').each(function(arrayIndex) {
		if(mainMenuIndex == arrayIndex) {
			$(this).fadeTo('fast', activeOptionsOpacity);
			$(this).parent().addClass('active');
		}
	});

	// Load section first content
	loadSectionFirstContent(mainMenuIndex, true);

	// Adjust height of right column for scroller bar
	if(mainMenuIndex == 1) {
		// Adjust right column height to window height
		adjustContentHeight();
	} else if(mainMenuIndex == 2) {
		if($(window).height() > minWindowHeihgtForVScroll) {
			adjustBlogContentHeight();
		} else {
			adjustContentHeight();
		}

		// Force subtle scroll for starting lazyload on visible images
		$('#rightColumnVScroll').scrollTop(1);
		$('#rightColumnVScroll').scrollTop(0);
	} else {
		// Adjust right column height to window height
		adjustContentHeight();
	}
}

/* Set sub-menu active option */

function changeSubMenuSelection(subMenuName, index) {
	if(subMenuName.indexOf('blogSubMenu_year_') == -1) {
		subMenuName = subMenuName + 'SubMenu';
		$('#' + subMenuName + '.subMenu ul li a').fadeTo('fast', 1);
		$('#' + subMenuName + '.subMenu ul li').removeClass('active');
	} else {

		$('#blogSubMenu_years .subMenu ul li a').fadeTo('fast', 1);
		$('#blogSubMenu_years .subMenu ul li').removeClass('active');
	}
	
	
	$('#' + subMenuName + ' ul li a').each(function(arrayIndex) {
		if(index == arrayIndex) {
			$(this).fadeTo('fast', activeOptionsOpacity);
			$(this).parent().addClass('active');
		}
	});
}

/* Adjust drawings image container size */

function checkDrawingsContentSize(width, height) {
		// Get container size
		var containerWidth = $('#drawingsImage').outerWidth();

		// Calculate right column margin top
		var marginTop;
		
		/*
		if(width > height) {
			//marginTop = 120; fede
			marginTop = parseInt(($(window).height() - $('.drawingsImageScrollerItem img').first().outerHeight()) / 2);
		} else {
			marginTop = parseInt(($(window).height() - $('.drawingsImageScrollerItem img').first().outerHeight()) / 2);
		}
		alert(marginTop);
		*/
		marginTop = 82; //harcoded fede
		
		$('#rightColumnContent_drawings').animate({ marginTop: marginTop }, animationSpeed);
		//$('#rightColumnContent_drawings').marginTop = 82;
		//$('#rightColumnContent_drawings').css('top', marginTop);

		// Scroller container
		//$('#drawingsImageScrollerCanvas, .drawingsImageScrollerItem').animate( { width: width }, animationSpeed);
		//$('#drawingsImageScrollerCanvas, .drawingsImageScrollerItem').animate( { height: height }, animationSpeed);
		$('#drawingsImageScrollerCanvas, .drawingsImageScrollerItem').css('width', width);  // fede - vuela el efecto
		$('#drawingsImageScrollerCanvas, .drawingsImageScrollerItem').css('height', height);  // fede - vuela el efecto
		
		// Navigation buttons
		$('#drawingsNavigationNext').css('left', width + 50);
		$('#drawingsNavigationPrevious').css('right', width + 50);
		//$('#drawingsNavigationPrevious').animate( { top: (height / 2) - 13 }, animationSpeed);   // fede. vuela el efecto
		//$('#drawingsNavigationNext').animate( { top: (height / 2) - 13 }, animationSpeed);
		$('#drawingsNavigationPrevious').css('top', (height / 2) - 13 );
		$('#drawingsNavigationNext').css    ('top', (height / 2) - 13 );

		// Drawing info text
		
		//$('#drawingsInfo').animate( { marginRight: (containerWidth - width) / 2 }, animationSpeed);
		$('#drawingsInfo').css('marginRight',   (containerWidth - width) / 2    ) ;
		
}

/* Adjust press images container size */

function checkPressContentSize(width, height) {
		// Get container size
		var containerWidth = $('#pressImages').outerWidth();

		// Scroller items
		// If image width is greater than maximum allowed, force image width to maximum
		if(width > pressImagesMaxWidth) {
			$('.pressImagesScrollerItem img').css('width', pressImagesMaxWidth);
			width = $('.pressImagesScrollerItem img').width();
			height = $('.pressImagesScrollerItem img').height();
		} else {
			$('.pressImagesScrollerItem img').css('width', width);
			$('.pressImagesScrollerItem img').css('height', height);
		}
		
		// Navigation buttons
		$('#pressImagesNavigationNext').css('left', (width * 2) + 20);
		$('#pressImagesNavigationPrevious').css('left', '-42px');
		$('#pressImagesNavigationPrevious').css('top', (height / 2) - 13);
		$('#pressImagesNavigationNext').css('top', (height / 2) - 13);

		// Scroller container
		$('#pressImagesScrollerCanvas').css('width', (width * 2));
		//alert (height);
		if (height > 553) $('#pressImagesScrollerCanvas').css('height', height);
}

/* Load first content of a section according to the first item in its sub-menu */

function loadSectionFirstContent(sectionIndex, activateOption) {
	// Get section name from general array
	var sectionName = sectionNames[sectionIndex];

	// Get first sub-menu item and parent for section
	firstItem = $('#' + sectionName + 'SubMenu ul li a').first();
	firstItemParent = $('#' + sectionName + 'SubMenu ul li a').first().parent();
	
	// If a valid item was found...
	if(sectionName == 'blog' || firstItem) {
		// Load content according to clicked section
		switch(sectionIndex) {
			case 0: // Drawings
				if(firstItemParent.attr('class') !== 'active') {
					changeDrawingsContent(0, firstItem.attr('id'));

					// Activate sub-menu first option
					if(activateOption) {
						changeSubMenuSelection(sectionName, 0);
					}
				}

				break;

			case 1: // Press
				if(!$('#pressIndexScrollerCanvas .pressIndexItem').html() || $('#pressDetail').length > 0) {
					changePressContent(0, 'index');
					//alert ('change press content');
				}

				break;

			case 2: // Blog
				var blogLastYear = $('.blogSubMenu_yearsItem > p > a').last();
				var year = blogLastYear.attr('id');
				var blogFirstPost = $('#blogSubMenu_year_' + year + ' ul li').first();


				if(blogLastYear.attr('class') !== 'active' || blogFirstPost.attr('class') !== 'active') {
					// Re-initialize sub-menues options for click actions
					initBlogSubMenu();

					// Slide up all year sub-menues
					$('#blogSubMenu_years div.subMenuContainer').slideUp('slow');

					// Slide down active year sub-menu
					$('#blogSubMenu_year_' + year + '_container').slideDown('fast');

					// Unset previous active option
					var blogYearsSubMenuElement = '#blogSubMenu_years > div > p > a';
					$(blogYearsSubMenuElement).fadeTo('fast', 1);
					$(blogYearsSubMenuElement).removeClass('active');

					// Set active option
					$(blogYearsSubMenuElement + '#' + year).fadeTo('fast', activeOptionsOpacity);
					$(blogYearsSubMenuElement + '#' + year).addClass('active');

					// Change posts sub-menu selection and load first post content
					changeSubMenuSelection('blogSubMenu_year_' + year, $('#blogSubMenu_year_' + year + ' ul li').first().index());
					changeBlogContent($('#blogSubMenu_year_' + year + ' ul li a').first().attr('id'));
				}

				break;
		}
	}
}


/*=======================================*/
/* Extensions */
/*=======================================*/

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();


/*=======================================*/
/* AJAX calls */
/*=======================================*/

/* Drawings content */

function changeDrawingsContent(index, id) {
	// Store selected index
	drawingsIndex = index;

	// Fade out drawings section container
	$('#rightColumnContent_drawings').fadeTo(
		'fast',
		0,
		function() { // On fade complete, load new content
			// Load new content
			$('#rightColumnContent_drawings').load(
				'ajax/ajaxHelper.php',
				{ mode : 'changeDrawingsContent', id : id },
				function() {
					// If an image scroller is set, go to its first element
					if(drawingsImagesNav.data('scrollable')) {
						drawingsImagesNav.data('scrollable').begin();
					}

					// On first image load complete...
					$('.drawingsImageScrollerItem img').first().load(function() {
						// Recall drawings section initialization
						setTimeout(function() { // setTimeout needed for proper behaviour in Chrome with cached images
							// Fade in drawings section container
							$('#rightColumnContent_drawings').fadeTo('fast', 1);
							//$('#rightColumnContent_drawings').css('visibility','visible');
							initDrawings();
							}, 100);
					});

					// Render page content again with Typeface for font refresh
					//_typeface_js.renderDocument();
				}
			);
		}
	);
}

/* Press sub-menu */

function changePressSubMenu() {
	// Fade out sub-menu container
	$('#pressSubMenu').fadeTo(
		'fast',
		0,
		function() { // On fade complete, load new content
			$('#pressSubMenu').load(
				'ajax/ajaxHelper.php',
				{ mode : 'changePressSubMenu' },
				function() {
					pressMenuNav = $('#pressSubMenu').scrollable({
						keyboard	: false,
						prev			: '.press_prevNav',
						next			: '.press_nextNav',
						vertical	: true,
						onSeek		: function() { checkSubMenuNavigation('press', this.getIndex(), this.getSize()); }
					});

					// Scroll blog submenu to first position
					pressMenuNav.data('scrollable').begin();
					
					// Re-initialize sub-menues options for click actions
					initSubMenues();

					// On content load complete, fade in sub-menu container
					$('#pressSubMenu').fadeTo('fast', 1);
				}
			);
		}
	);
}

/* Press content */

function changePressContent(index, id) {
	// Store selected index
	pressIndex = index;
	//alert('press');
	// Fade out press section container
	$('#rightColumnContent_press').fadeTo(
		'fast',
		0,
		function() { // On fade complete, load new content
			// Load new content
			$('#rightColumnContent_press').load(
				'ajax/ajaxHelper.php',
				{ mode : 'changePressContent', id : id },
				function() {
					// Fade out images scroller for preventing scrollable glitch
					$('#pressImages').fadeTo(0, 0);

					// On index first image load complete...
					$('#pressIndexScrollerCanvas img').first().load(function() {
						// Recall drawings section initialization
						initPress();
					});

					// On first image load complete...
					if($('.pressImagesScrollerItem img').size() >= 2) {
						imgElement = $('.pressImagesScrollerItem img').eq(1);
					} else {
						imgElement = $('.pressImagesScrollerItem img').eq(0);
					}

						imgElement.load(function() {
						setTimeout(function() { // setTimeout needed for proper behaviour in Chrome with cached images
							// Fade in drawings section container
							$('#pressImages').fadeTo(1200, 1);

							// Recall drawings section initialization
							initPress();
						}, 100);
					});

					// Change sub-menu selected option if it was not previously selected
					$('div#pressSubMenu ul li').each(function() {
						if($(this).attr('class') !== 'active' && $(this).children().first().attr('id') == id) {
							changeSubMenuSelection('press', $(this).index());
						}
					});

					// If an image scroller is set, go to its first element
					if(pressImagesNav.data('scrollable')) {
						pressImagesNav.data('scrollable').begin();
					}
					
					// Adjust height to loaded content
					if(id !== 'index' && $(window).height() > minWindowHeihgtForVScroll) {
						adjustPressContentHeight();
					} else {
						adjustContentHeight();
					}

					// On content load complete, fade in press section container
					$('#rightColumnContent_press').fadeTo('fast', 1);
				}
			);
		}
	);
}

/* Blog sub-menu */

function changeBlogSubMenu(year) {
	// Slide up all year sub-menues
	$('#blogSubMenu_years div.subMenuContainer').slideUp('slow');
	
	// Reset year sub-menu to the first position
	if($('#blogSubMenu_year_' + year).data('scrollable')) {
		$('#blogSubMenu_year_' + year).data('scrollable').begin();
	}

	// Slide down active year sub-menu
	$('#blogSubMenu_year_' + year + '_container').slideDown('slow');
}

/* Blog content */

function changeBlogContent(id) {
	// Fade out blog section container
	$('#rightColumnContent_blog').fadeTo(
		'fast',
		0,
		function() { // On fade complete, load new content
			// Scroll blog content to top
			$('#rightColumnVScroll').scrollTop('0px');

			// Load new content
			$('#rightColumnContent_blog').load(
				'ajax/ajaxHelper.php',
				{ mode : 'changeBlogContent', id : id },
				function() {
					// Fade out images scroller for preventing scrollable glitch
					$('#blogImages').fadeTo(0, 0);

					$('#rightColumnContent_blog').ready(function() {
						// Recall blog section initialization (only when div container is loaded and ready)
						initBlog();

						// Fade in images scroller
						$('#blogImages').fadeTo(1000, 1);
					});

					// If an image scroller is set, go to its first element
					if(blogImagesNav.data('scrollable')) {

						blogImagesNav.data('scrollable').begin();
					}

					// If blog is active section, fit container height according to its content
					if(mainMenuIndex == 2) {
						adjustBlogContentHeight();
					}

					// On content load complete, fade in blog section container
					$('#rightColumnContent_blog').fadeTo('fast', 1);
				}
			);
		}
	);
	//alert ('aa');
}
