// Browser check
if (BrowserDetect.browser == 'Explorer' && BrowserDetect.version <= 7)
{
	if (confirm('This website uses the latest web technologies\n' +
			'and does not work with ' + BrowserDetect.browser +
			' version ' + BrowserDetect.version + '.\n' +
			'Please update your browser.' + '\n\n---\n\n' +
			'Ce site web a ete concu avec les plus recentes technologies.\n' +
			'Il n\'est par consequent pas supporte par Explorer, version 7.\n' +
			'Pour visualiser le site, veuillez s\'il-vous-plait mettre a jour votre navigateur.'))
	{
		window.location.href = 'http://www.updateyourbrowser.net/';
	}
}

// Global variables
var busy = false;
var loading_items = 0;
var current_blog = 0;
var rotation = undefined;

function is_ie9()
{
	return (BrowserDetect.browser == 'Explorer' && BrowserDetect.version == 9);
}

function is_iphone()
{
	return BrowserDetect.OS == 'iPhone/iPod';
}

function is_ipad()
{
	return BrowserDetect.OS == 'iPad';
}

function set_tab(s, hide, section)
{
	if (hide == undefined) hide = true;
	if (hide) $('#menu').hide();

	if (section == undefined) section = 0;

	// Clicking on the active tab does nothing
	if ($('#' + s).hasClass('active')) return;

	if (hide) $('#gallery').fadeOut();
	if (hide) $('#credits').fadeOut();
	if (hide) $('#text-container').fadeOut();
	if (hide) $('#blog').fadeOut();

	if (!busy)
	{
		// Lock semaphore
		busy = true;

		// Empty all menus
		clear_menu();

		// Make sure we have a default active tab
		if (!$('.accordion.active').length) $('#news').addClass('active');

		// Animate or initial setup?
		if ($('.accordion.active .menu').length)
		{
			// Hide previous active menu
			$('.accordion.active .menu').animate({width: '0px'}, 400, 'easeInExpo', function()
			{
				anim_tab(s, hide, section);
			});
		}
		else anim_tab(s, hide, section);
	}
}

function anim_tab(s, hide, section)
{
	if (hide == undefined) hide = true;
	if (section == undefined) section = 0;

	// Get current language
	$.ajax(
	{
		type: "POST",
		url: 'lib/lang.php',
		async: false,
		success: function(data)
		{
			var l = data;

			// Set the text to normal
			$('.tab img').each(function()
			{
				var s = $(this).parents('li.accordion').attr('id');
				$(this).attr('src', 'img/' + s + '-' + l + '.png');
			});

			// Move tab out
			var left = $('#' + s + ' .tab').css('left');
			$('.accordion.active .tab').animate({left: left}, hide ? 400 : 0, 'easeInExpo');

			// Unactivate tab
			$('.accordion').removeClass('active');

			// Set the text to highlight mode
			$('#' + s).addClass('active');
			$('#' + s + ' .tab img').attr('src', 'img/' + s + '-hi-' + l + '.png');

			// Move tab in
			$('#' + s + ' .tab').animate({left: '118px'}, hide ? 400 : 0, 'easeOutExpo', function()
			{
				if (rotation != undefined)
				{
					clearTimeout(rotation);
					rotation = undefined;
				}

				// Move menu in
				$('#' + s + ' .menu').animate({width: '200px'}, hide ? 500 : 0, 'easeOutExpo', function()
				{
					busy = false;

					// Update the menu
					set_menu(s, hide, section);

					// Update the background
					if (hide)
					{
						if (s == 'news') set_rotation('news', 1, 5);
						else set_bg('', s, true);
					}
				});
			});
		}
	});
}

function set_rotation(name, at, max)
{
	set_bg('rotation/' + name, at);

	at++;
	if (at > max) at = 1;
	if (!is_iphone() && !is_ipad() && !is_ie9()) rotation = setTimeout('set_rotation("' + name + '", ' + at + ', ' + max + ')', 10000);
}

function set_bg(root, s, slide)
{
	if (rotation == undefined) loading();
	if (slide == undefined) slide = false;

	if (is_iphone() || is_ipad()) slide = false;

	// Background image
	$.ajax(
	{
		type: "POST",
		url: 'lib/fillcrop.php',
		data:
		{
			w: screen.width,
			h: screen.height,
			f: 'img/bg/' + (root ? root + '/' : '') + s + '.jpg'
		},
		async: false,
		success: function(data)
		{
			var img = new Image();
			img.src = data;
			if (img.complete) $(img).load();

			$(img).one('load', function()
			{
				$('#page').hide();
				$('#subpage').css('background-image', $('#page').css('background-image'));
				$('#page').css('background-image', 'url(' + data + ')');

				if (slide)
				{
					$('#subpage').show();
					$('#page').css('left', screen.width + 'px');
					$('#page').show();
					$('#page').animate({left: '0px'}, 500, 'easeInExpo');
				}
				else $('#page').fadeIn(500, 'easeInExpo');
			});
		},
		complete: function() { if (rotation == undefined) loading_done(); }
	});
}

function loading_done()
{
	loading_items--;
	if (loading_items == 0) $('#loading').hide();
}

function loading()
{
	loading_items++;
	$('#loading').show();
	$('#loading').fadeIn();
}

function clear_menu()
{
	// Clear previous menu
	$('.menu .top-content').html('');
	$('.menu .popup-content').html('');
	$('.menu .bottom-content').html('');
}

function setup_menu(hide, section)
{
	if (hide == undefined) hide = true;
	if (section == undefined) section = 0;

	// Hide all menubars and dropdowns on startup
	$('#menu').hide();
	$('.menubar').hide();
	$('.text-entry').hide();

	// Vertical menu item click
	$('.popup-item > a').click(function()
	{
		$('.popup-item > a').removeClass('highlight');
		$(this).addClass('highlight');

		$('#menu').stop(true, true).fadeOut();
		$('#gallery').stop(true, true).fadeOut();
		$('#credits').stop(true, true).fadeOut();
		$('#blog').stop(true, true).fadeOut();
		$('.menubar').stop(true, true).slideUp(500);

		$(this).siblings('.menubar').delay(500).stop(true, true).fadeIn(500, function()
		{
			var o = $(this).find('a:first');
			var href = $(o).attr('href');

			$(o).click();
			if (href) window.location.href = href;
		});

		update_breadcrumbs();
	});

	// Menubar item click
	$('.menubar-item > a').click(function()
	{
		var page = $('.accordion.active').attr('id');
		var color = '';

		if ($(this).parent().attr('rel') != '')
		{ 
			set_bg('section', $(this).parent().attr('rel'));
		}

		switch (page)
		{
			case 'news': color = 'yellow'; break;
			case 'projects': color = 'blue'; break;
			case 'durable': color = 'green'; break;
			case 'firm': color = 'red'; break;
		}

		$('#blog').removeClass('yellow');
		$('#blog').removeClass('blue');
		$('#blog').removeClass('green');
		$('#blog').removeClass('red');
		$('#blog').addClass(color);

		$('#menu').removeClass('yellow');
		$('#menu').removeClass('blue');
		$('#menu').removeClass('green');
		$('#menu').removeClass('red');
		$('#menu').addClass(color);

		$('.menubar-item > a').removeClass('highlight');
		$(this).addClass('highlight');
		var s = '<ul>' + $(this).siblings('.dropdown').html() + '</ul>';

		if ($(this).hasClass('blog'))
		{
			show_blog(s);
			var bg = $(this).parent('li').find('input[type=hidden]').val();

			if (bg != undefined && bg != '')
			{
				set_bg('', bg);
			}
		}
		else show_menu(s);

		update_breadcrumbs();
	});

	if (hide) $('.popup-item:nth-child(' + (section + 1) + ') > a').click();
}

function show_menu(s)
{
	if (s == '' || s == undefined) $('#menu').html('<ul class="dropdown-item"><li>&nbsp;</li></ul>');
	else $('#menu').html(s);

	$('#gallery').fadeOut();
	$('#text-container').fadeOut();

	if (!$('#menu').is(':visible'))
	{
		$('#menu').css('width', '0%');
		$('#menu').css('top', '128px');
		$('#menu').show();
		$('#menu').animate({width: '100%'}, '1000', 'easeOutExpo');
	}
	else
	{
		$('#menu ul').hide();
		$('#menu ul').fadeIn();
	}

	$('#menu a').click(function()
	{
		$('#menu a').removeClass('highlight');
		$(this).addClass('highlight');
		update_breadcrumbs();
	});
}

function refresh_blog()
{
	var i = 0;

	$('#blog .dropdown-item').each(function()
	{
		if (i == current_blog) $(this).slideDown(500, 'easeOutExpo');
		else if (i == current_blog + 1) $(this).slideDown(500, 'easeOutExpo');
		else if (i == current_blog + 2) $(this).slideDown(500, 'easeOutExpo');
		else $(this).hide();
		i++;
	});
}

function show_blog(s)
{
	current_blog = 0;
	$('#blog').fadeIn();
	$('#blog').html(s);
	$('#blog .dropdown-item').hide();

	// Blog list manager
	$('#blog .previous').click(function()
	{
		if (current_blog > 0) current_blog--;
		refresh_blog();
	});

	$('#blog .next').click(function()
	{
		if (current_blog < $('#blog .dropdown-item').length - 1) current_blog++;
		refresh_blog();
	});

	$('#blog .read-more-button').click(function()
	{
		var ul = $('#blog > ul');
		var li = $(this).closest('li');

		if (ul.hasClass('expanded'))
		{
			ul.removeClass('expanded');
			li.find('.article').css('overflow', 'hidden');
			li.find('.read-more-button').css('background-image', 'url(img/expand.png)');

			li.find('.article').animate({height: '45px'}, 500, 'easeOutExpo');
			ul.animate({width: '365px'}, 500, 'easeOutExpo');
			$('#blog nav').animate({left: '755px'}, 500, 'easeOutExpo');

			refresh_blog();
		}
		else
		{
			ul.addClass('expanded');
			li.find('.article').css('overflow', 'auto');
			li.find('.read-more-button').css('background-image', 'url(img/minimize.png)');

			$('#blog nav').animate({left: '825px'}, 500, 'easeOutExpo');
			ul.animate({width: '430px'}, 500, 'easeOutExpo');
			li.find('.article').animate({height: '200px'}, 500, 'easeOutExpo');

			ul.find('li').each(function()
			{
				if ($(this).attr('id') != li.attr('id')) $(this).slideUp(500, 'easeOutExpo');
			});
		}
	});

	refresh_blog();
}

function set_menu(tab, hide, section)
{
	if (hide == undefined) hide = true;
	if (section == undefined) section = 0;

	var f = 'page/' + tab + '-' + language + '.php';

	$('#blog').stop(true, true).fadeOut();

	// Load top menu content
	loading();
	$.ajax(
	{
		url: f,
		async: false,
		success: function(data)
		{
			$('#' + tab + ' .menu .top-content').html(data);
		},
		complete: function() { loading_done(); },
		error: function() { alert('Could not load page title from file: ' + f); }
	});

	// Load bottom menu content
	f = 'page/' + tab + '-footer-' + language + '.php';
	
	loading();
	$.ajax(
	{
		url: f,
		async: false,
		success: function(data)
		{
			$('#' + tab + ' .menu .bottom-content').html(data);
		},
		complete: function() { loading_done(); },
		error: function() { alert('Could not load page footer from file: ' + f); }
	});

	// Load new menu data
	loading();
	$.ajax(
	{
		type: "POST",
		url: 'lib/popup.php',
		data:
		{
			tab: tab,
			lang: language
		},
		async: false,
		success: function(data)
		{
			$('#' + tab + ' .menu .popup-content').html(data);
			setup_menu(hide, section);
			update_breadcrumbs();
		},
		complete: function() { loading_done(); }
	});
}

function credits(file, offset)
{
	$.ajax(
	{
		type: "POST",
		url: 'lib/credits.php',
		async: false,
		data:
		{
			file: file
		},
		success: function (data)
		{
			$('#menu').stop(true, true).fadeOut();
			$('#gallery').stop(true, true).fadeOut();
			$('#blog').stop(true, true).fadeOut();

			var c = $('#credits');
			var t = $('#credits-html');
			t.html(data);

			var n = t.html().split("\n").length;
			var h = t.height();

			$('#credits').removeClass('mission');
			$('#credits').removeClass('contact');
			$('#credits').removeClass('red');
			$('#credits').removeClass('blue');
			$('#credits').removeClass('green');
			$('#credits').removeClass('yellow');
			$('#credits').css('top', offset == true ? '250px' : '175px');

			var a = file.split('/');
			var s = '';

			switch (a[1])
			{
				case 'durable': s = 'green'; break;
				case 'firm': s = 'red'; break;
				case 'news': s = 'yellow'; break;
				case 'projects': s = 'blue'; break;
				default: s = 'black'; break;
			}

			if (a[2] == 'mission') $('#credits').addClass('mission');
			else if (a[2] == 'contact') $('#credits').addClass('contact');

			$('#credits').addClass(s);
			$('#credits').stop(true, true).fadeIn();
			t.stop(true, true);
			t.css('top', '0px');
			//if (t.height() > c.height()) t.delay(5000).animate({top: -(t.height() - c.height()) + 'px'}, n * 250, 'linear');
		}
	});
}

function gallery(path)
{
	set_bg(path, '1');

	loading();
	$.ajax(
	{
		type: "POST",
		url: 'lib/gallery.php',
		data:
		{
			rel: path
		},
		async: false,
		success: function (data)
		{
			$('#gallery').html(data);
			$('#gallery .hover').hide();
			$('#gallery').fadeIn();

			var t = '#text-' + path.replace(/\//g, '-');
			var h = $(t).html();

			if (h != null)
			{
				$('#text-container').html('<span>' + h + '</span>');
				$('#text-container').fadeIn();
			}

			if (!is_iphone() && !is_ipad()) $('.gallery-item').hover(
				function()
				{
					$(this).children('.hover').stop(true, true).slideDown('fast');
				},
				function()
				{
					$(this).children('.hover').stop(true, true).slideUp('fast');
				}
			);
			
			$('.gallery-item').click(function()
			{
				var a = $(this).attr('id').split('-');
				var id = a[a.length - 1];
				set_bg($(this).attr('rel'), id);
			});

			$('.gallery-item').each(function()
			{
				var rel = $(this).attr('rel');
				var a = $(this).attr('id').split('-');
				var id = a[a.length - 1];
				var item = $(this);

				item.hide();

				loading();
				$.ajax(
				{
					type: "POST",
					url: 'lib/fillcrop.php',
					async: false,
					data:
					{
						w: 50,
						h: 50,
						f: 'img/bg/' + rel + '/' + id + '.jpg'
					},
					success: function(data)
					{
						var img = item.children('img');
						img.attr('src', data);

						$(img).one('load', function()
						{
							item.fadeIn();
						});
					},
					complete: function() { loading_done(); }
				});
			});
		},
		complete: function() { loading_done(); }
	});
}

function echeck(str)
{
	var at = "@"
	var dot = "."
	var lat = str.indexOf(at)
	var lstr = str.length
	var ldot = str.indexOf(dot)

	if (str.indexOf(at) == -1) return false
	if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) return false;
	if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) return false;
	if (str.indexOf(at, (lat + 1)) != -1) return false;
	if (str.substring(lat - 1, lat) == dot || str.substring(lat + 1, lat + 2) == dot) return false;
	if (str.indexOf(dot, (lat + 2))==-1) return false;
		
	if (str.indexOf(" ")!=-1) return false;

	return true					
}

// Startup
$(document).ready(function()
{
	$('#tabs').disableSelection();
	$('#credits').hide();
	$('#subscribe').hide();

	// Global setup
	$('#credits-up').click(function()
	{
		var top = parseInt($('#credits-html').css('top'));
		if (top < 0) $('#credits-html').css('top', top + 50);
	});

	$('#credits-down').click(function()
	{
		var top = parseInt($('#credits-html').css('top'));
		$('#credits-html').css('top', top - 50);
	});

	$('#fullscreen').click(function()
	{
		if ($('#tabs').is(':visible'))
		{
			$('#tabs').fadeOut(250, 'swing');
			$('#bread').animate({top: '69px'}, 500, 'swing', function()
			{
				$('#crumbs').animate({marginLeft: '20px'}, 250, 'swing');
			});
			$('#menu').animate({top: '87px'}, 500, 'swing', function()
			{
				$('#menu > ul').animate({marginLeft: '10px'}, 250, 'swing');
				$('#text-container').animate({left: '10px'}, 250);
			});
			$('#gallery').animate({top: '135px'}, 500, 'swing').animate({left: '10px'}, 250, 'swing');
			$('#fullscreen .label').text(language == 'fr' ? 'vue normale' : 'default view');
		}
		else
		{
			$('#tabs').fadeIn(250, 'swing');
			$('#crumbs').animate({marginLeft: '375px'}, 250, 'swing', function()
			{
				$('#bread').animate({top: '110px'}, 500, 'swing');
			});
			$('#menu > ul').animate({marginLeft: '365px'}, 250, 'swing', function()
			{
				$('#menu').animate({top: '128px'}, 500, 'swing');
			});
			$('#gallery').animate({left: '365px'}, 250, 'swing').animate({top: '175px'}, 500, 'swing');
			$('#text-container').animate({left: '365px'}, 250);
			$('#fullscreen .label').html(language == 'fr' ? 'plein &eacute;cran' : 'full screen');
		}
	});

	/*$('#newsletter').click(function()
	{
		$('#subscribe').toggle();
	});

	$('#subscribe input').focus(function()
	{
		if ($(this).val() == (language == 'fr' ? 'adresse courriel' : 'email address')) $(this).val('');
	});

	$('#subscribe input').blur(function()
	{
		$(this).val(language == 'fr' ? 'adresse courriel' : 'email address');
	});

	$('#subscribe input').keypress(function(e)
	{
		var code = (e.keyCode ? e.keyCode : e.which);

		if (code == 13)
		{
			if (echeck($(this).val()))
			{
				//<form name="ccoptin" action="http://visitor.r20.constantcontact.com/d.jsp" method="post">
				//<input type="hidden" name="llr" value="fmowavfab">
				//<input type="hidden" name="m" value="1105585715589">
				//<input type="hidden" name="p" value="oi">
				//<input type="text" name="ea">
				//<input type="submit" name="go" value="Go">
				//</form>

				loading();
				$('#subscribe').hide();

				$.ajax(
				{
					type: 'POST',
					url: 'http://visitor.r20.constantcontact.com/d.jsp',
					async: false,
					data:
					{
						llr: 'fmowavfab',
						m: '1105585715589',
						p: 'io',
						ea: $(this).val(),
						go: 'Go'
					},
					success: function()
					{
						alert((language == 'fr' ? 'Merci de vous être inscrit à notre infolettre.' : 'Thank you for subscribing to our newsletter.') + "\n" + $(this).val());
					},
					error: function(xhr, ajaxOptions, message)
					{
						alert((language == 'fr' ? 'Impossible de compléter votre inscription.' : 'Cannot complete your subscription.') + "\n" + xhr.status + "\n" + message);
					},
					complete: function()
					{
						loading_done();
					}
				});
			} else alert('Ce courriel n\'est pas valide.');
		}
	});*/

	// On iPhone make sure the page stay at top
	//setInterval(function() { window.scrollTo($(window).scrollLeft(), 1) }, 1000);
	//setInterval(function() { window.scrollTo(0, 1); }, 1000);

	// Check hashtag changes for JS bookmarking
	setTimeout(processHash, 1000);

	// iPad fix
	if (is_ipad())
	{
		//$('#page').css('height', '105%');
	}
});

