/* Site setup */

46.803408,-71.233721

var SOAZ_map_initialCenter = [60.152442, -98.085937]; // will be overwritten
var SOAZ_map_parkings = [
	[45.507399564241126,-73.56428146362305], // Complexe Desjardins
	[45.50415128315096,-73.56183528900146]	// Bleury et Viger
];

var portfolio_project_preview_bg_image = "/_ui/images/project-preview-bg.png";

/* go! */

$(document.documentElement).addClass("dhtml");	// js-enabled user agent indicator

$(document).ready(function () {

	// don't add any behaviour if css is off
	if ($("#logo a").css("display") !== "block") {
		return false;
	}
	
	// Add the class "paginated" to ul of second col
	$(".layout.col-2 ul").addClass("paginated")
	
	/*
	// don't add any behaviour and remove adveanced styles when there is not enough space for full-fledged layout
	if (($("#the_wrapper").width() < 900) || ($("#the_wrapper").height() < 500)) {
		$(document.documentElement).removeClass("dhtml");
		return false;
	}
	*/

	/**
	 *	Apply shadows to elements with 'shadowed_box' class
	 */
	var applyShadows = function () {
	
		var shadowedBoxes = $(".shadowed_box");
		var shadowElements = $('' +
			'<div class="dhtml shadow-top">' +
				'	<div class="left"></div><div class="center"></div><div class="right"></div>' +
				'</div>' +
				'<div class="shadow-middle">' +
				'	<div class="left"></div><div class="right"></div>' +
				'</div>' +
				'<div class="shadow-bottom">' +
				'	<div class="left"></div><div class="center"></div><div class="right"></div>' +
			'</div>');

		shadowElements.prependTo(shadowedBoxes);

	}();

	/**
	 *	Bottom yellow menu behaviour
	 */
	var intro_nav_mini = function () {

		var contents = $("#intro-nav-mini div.content");
		var collapseTimeout = null;
		var isExpanded = false;
		var expand = function () {
			if (collapseTimeout !== null) {
				clearTimeout(collapseTimeout);
				collapseTimeout = null;
			}
			if (!isExpanded) {
				contents.slideDown("fast");
				isExpanded = true;
			}
		};
		var collapse = function () {
			if (isExpanded) {
				collapseTimeout = setTimeout(function () {
					contents.slideUp("fast");
					//communicationExpand();
					isExpanded = false;
					collapseTimeout = null;
				}, 250);
			}
		};
		var communicationMI = $("#intro-nav-mini li.communication").eq(0);
		var developpementMI = $("#intro-nav-mini li.developpement").eq(0);
		var expositionMI = $("#intro-nav-mini li.exposition").eq(0);
/*
		var communicationMI = $("#intro-nav-mini li.communication").eq(0);
		var communicationIsExpanded = true;
		var communicationExpand = function () {
			expand();
			if (communicationIsExpanded) {
				return false;
			} else {
				communicationIsExpanded = true;
				expositionIsExpanded = false;
				developpementIsExpanded = false;
			}
			communicationMI.animate({ 
				paddingLeft: "0px"
			}, "fast", "swing", function () {
				communicationMI.removeClass("communicationCollapsed");
				communicationMI.animate({ 
					paddingLeft: "92px"
				}, "fast", "swing");
				communicationMI.find("ul.external").animate({ 
					width: "92px"
				}, "fast", "swing");

				expositionMI.animate({ 
					paddingLeft: "0px"
				}, "fast", "swing");
				expositionMI.find("ul.external").animate({ 
					width: "0px"
				}, "fast", "swing");
				
				developpementMI.animate({ 
					paddingLeft: "0px"
				}, "fast", "swing");
				developpementMI.find("ul.external").animate({ 
					width: "0px"
				}, "fast", "swing")
			});
			$("#intro-nav-mini").animate({
				paddingLeft: "36px"
			}, "fast", "swing");
			
		};
		
		var developpementMI = $("#intro-nav-mini li.developpement").eq(0);
		var developpementIsExpanded = false;
		var developpementExpand = function () {
			expand();
			if (developpementIsExpanded) {
				return false;
			} else {
				developpementIsExpanded = true;
				communicationIsExpanded = false;
				expositionIsExpanded = false;
			}
			developpementMI.animate({ 
				paddingLeft: "92px"
			}, "fast", "swing");
			developpementMI.find("ul.external").animate({ 
				width: "92px"
			}, "fast", "swing");
			communicationMI.animate({ 
				paddingLeft: "0px"
			}, "fast", "swing", function () {
				communicationMI.addClass("communicationCollapsed");
				communicationMI.animate({ 
					paddingLeft: "36px"
				}, "fast", "swing");
				$("#intro-nav-mini").animate({
					paddingLeft: "0px"
				}, "fast", "swing");
			});
			communicationMI.find("ul.external").animate({ 
				width: "0px"
			}, "fast", "swing");
		};

		var expositionMI = $("#intro-nav-mini li.exposition").eq(0);
		var expositionIsExpanded = false;
		var expositionExpand = function () {
			expand();
			if (expositionIsExpanded) {
				return false;
			} else {
				expositionIsExpanded = true;
				communicationIsExpanded = false;
				developpementIsExpanded = false;
			}
			expositionMI.animate({ 
				paddingLeft: "92px"
			}, "fast", "swing");
			expositionMI.find("ul.external").animate({ 
				width: "92px"
			}, "fast", "swing");
			communicationMI.animate({ 
				paddingLeft: "0px"
			}, "fast", "swing", function () {
				communicationMI.addClass("communicationCollapsed");
				communicationMI.animate({ 
					paddingLeft: "36px"
				}, "fast", "swing");
				$("#intro-nav-mini").animate({
					paddingLeft: "0px"
				}, "fast", "swing");
			});
			communicationMI.find("ul.external").animate({ 
				width: "0px"
			}, "fast", "swing");
			
			developpementMI.animate({ 
				paddingLeft: "0px"
			}, "fast", "swing", function () {
				developpementMI.addClass("developpementCollapsed");
				developpementMI.animate({ 
					paddingLeft: "36px"
				}, "fast", "swing");
				$("#intro-nav-mini").animate({
					paddingLeft: "0px"
				}, "fast", "swing");
			});
			developpementMI.find("ul.external").animate({ 
				width: "0px"
			}, "fast", "swing");
		};
*/
		communicationMI.mouseover(expand);
		communicationMI.mouseout(collapse);
		developpementMI.mouseover(expand);
		developpementMI.mouseout(collapse);
		expositionMI.mouseover(expand);
		expositionMI.mouseout(collapse);

	}();

	/**
	 *	Top left yellow navigation behaviour
	 */
	var site_nav = function () {

		var menu = $("#site_nav")
		var items = $("#site_nav li"); // menu items
		var activeItem = $("#site_nav li."+document.body.className)
		items.each(function (i) {

			var item = $(this);

			if (this.className === document.body.className) {
				item.css("padding-right", "68px");
			} else {
				var slideUpTimeout = null;
				item.mouseover(function () {
					if (slideUpTimeout === null) {
						item.animate({ 
							paddingRight: "68px"
						}, "fast", "swing");
					} else {
						clearTimeout(slideUpTimeout);
						slideUpTimeout = null;
					}
				});
				item.mouseout(function () {
					slideUpTimeout = setTimeout(function () {
						item.animate({ 
							paddingRight: "0"
						}, "fast", "swing");
						slideUpTimeout = null;
					}, 250);
				});
			}
				
			item.click(function () {
				document.location = item.find("a")[0].href;
			});

		});

	}();


	/**
	 *	Client access form (top right menu) behaviour
	 */
	var accessClientForm = function () {

		var form = $("#access_client_form");

		// toggle form on menu item click

		form.prev("a").click(function (e) {
			form.toggle();
			e.preventDefault();
		});

		// some flavour for form

		form.find("fieldset input").each(function () {

			var input = $(this);
			var labelText = input.prev("label").html();

			input.attr("title", labelText);

			if(input.val() === "") {
				input.val(labelText);
			}
			input.focus(function(){
				if(input.val() === labelText) {
					input.val("");
				}
			});
			input.blur(function(){
				if(input.val() === "") {
					input.val(labelText);
				}
			});

		});

		var loginInput = form.find("input.login"),
			passwordInput = form.find("input.password"),
			loginFirstFocus = false,
			passwordFirstFocus = false;

		loginInput.focus(function () {
			if (!loginFirstFocus) {
				loginInput.val("");
				loginFirstFocus = true;
			}
		});
		passwordInput.focus(function () {
			if (!passwordFirstFocus) {
				passwordInput.val("");
				passwordFirstFocus = true;
			}
		});

	}();


	/**
	 *	Secondary content behaviour
	 */
	var secondaryContent = function () {

		var secondaryContent = $("#secondary_content");
		var toc = $("#secondary_content-toc");
		var fermerButton = $("#secondary_content-fermer");
		
		var contentOverlay = $("<div id='content-overlay' class='dhtml'></div>").insertBefore("#content-wrapper");

		var selectedArticleId = null;
		var selectedArticleContentId = null;

		var hrefToId = function (a) {
			return a.getAttribute("href").split("#")[1];
		};

		var showArticle = function (articleId) {

			var articleIsNewsOnIntroPage = ($("body").hasClass("intro") && (articleId === "les_dernieres_rumeurs"));

			if (articleId !== selectedArticleId) {

				var showArticle = function(){
					secondaryContent.removeClass(selectedArticleId);
					if (articleId) {
						if (!articleIsNewsOnIntroPage) {
							if ((selectedArticleId === null) || ($("body").hasClass("intro") && (selectedArticleId === "les_dernieres_rumeurs"))) {
								contentOverlay.fadeTo(0, 0, function () {
									contentOverlay.show();
									contentOverlay.fadeTo("slow", 0.6);
								});
							}
						}
						var article = $("#" + articleId);
						secondaryContent.addClass(articleId);
						article.slideDown("slow", function () {
							secondaryContent.addClass("open");
							secondaryContent.trigger("articleShow", [articleId]);
						});
					}
					selectedArticleId = articleId;
				};
				// hide old article
				if (selectedArticleId) {
					if (articleIsNewsOnIntroPage || (articleId === null)) {
						contentOverlay.fadeTo("fast", 0, function () {
							contentOverlay.hide();
						});
					}
					$("#" + selectedArticleId).slideUp("fast", showArticle);
					secondaryContent.removeClass("open");
				} else {
					showArticle();
				}

			}

		};

		var switchContent = function (contentId) {

			if (contentId !== selectedArticleContentId) {
				var showContent = function () {
					var content = $("#" + contentId);
					content.slideDown("slow");
				};
				// mark selected item in navigation
				var selectedArticle = $("#" + selectedArticleId);
				selectedArticle.find("div.toc li.selected").removeClass("selected");
				selectedArticle.find("div.toc li." + contentId).addClass("selected");
				// hide old conten and show new
				if (selectedArticleContentId) {
					var selectedArticleContent = $("#" + selectedArticleContentId);
					selectedArticleContent.slideUp("fast", showContent);
				} else {
					showContent();
				}
				selectedArticleContentId = contentId;
			}

		};

		/* init */

		// initlizize tab menu
		toc.find("a").each(function () {
			$(this).mouseover(function () {
				var articleId = hrefToId(this);
				if (articleId !== selectedArticleId) {
					secondaryContent.removeClass(selectedArticleId);
					secondaryContent.addClass(articleId);
				}
			});
			$(this).mouseout(function () {
				var articleId = hrefToId(this);
				if (articleId !== selectedArticleId) {
					secondaryContent.removeClass(articleId);
					if (selectedArticleId) {
						secondaryContent.addClass(selectedArticleId);
					}
				}
			});
			$(this).click(function (e) {
				e.preventDefault();
				showArticle(hrefToId(this));
			});
		});

		// initialize femer button
		fermerButton.click(function (e) {
			e.preventDefault();
			showArticle(null);
		});

		// initialize compact lists
		$("#secondary_content dl.compact dt").click(function () {
			$(this).toggleClass("expanded");
			$(this).next("dd").toggleClass("expanded");
		});
		$("#secondary_content dl.compact dd").click(function () {
			$(this).prev("dt").toggleClass("expanded");
			$(this).toggleClass("expanded");
		});
		

		// open initial article
		if ($("body").hasClass("intro")) {
			showArticle("les_dernieres_rumeurs");
		}
		// select first content in multi-content articles and enable navigation
		var multiContentArticlesTocs = secondaryContent.find("div.article div.toc");
		multiContentArticlesTocs.each(function () {
			$(this).find("li").eq(0).addClass("selected");
			var firstContent = $(this).next("div.content");
			firstContent.show();
			selectedArticleContentId = firstContent.attr("id");
			$(this).find("a").click(function (e) {
				e.preventDefault();
				switchContent(hrefToId(this));
			});
		});

	}();

	/**
	 *	Initializes contact map
	 */
	var contactGmap = function () {

		var mapElement = document.getElementById("contactGmap");
		if (!mapElement) { return false; }
		var openedOnce = false;

		// init

		$("#secondary_content").bind("articleShow", function (e, articleId) {
			if (!openedOnce && (articleId === "contactez-nous")) {	// NOTE: map will be initialized when user will open Contactez-nous tab for the first time 
				openedOnce = true;
				if (window.GBrowserIsCompatible && GBrowserIsCompatible()) {
					// map and markers setup
					var soazIcon = new GIcon({
						"image": "/_ui/images/contactez-nous-map-soaz-ico.png",
						"shadow": "/_ui/images/contactez-nous-map-soaz-ico-shadow.png",
						"iconSize": new GSize(56, 78),
						"shadowSize": new GSize(85, 78),
						"iconAnchor": new GPoint(26, 72)
					});
					var parkingIcon = new GIcon({
						"image": "/_ui/images/contactez-nous-map-parking-ico.png",
						"shadow": "/_ui/images/contactez-nous-map-parking-ico-shadow.png",
						"iconSize": new GSize(35, 48),
						"shadowSize": new GSize(61, 48),
						"iconAnchor": new GPoint(15, 43)
					});
					var map = new GMap2(mapElement);
					map.setCenter(new GLatLng(SOAZ_map_initialCenter[0], SOAZ_map_initialCenter[1]), 2);
					map.setMapType(G_NORMAL_MAP);
					map.addControl(new GSmallMapControl());
					// parkings markers
					for (var i = 0; i < SOAZ_map_parkings.length; i++) {
						map.addOverlay(new GMarker(new GLatLng(SOAZ_map_parkings[i][0], SOAZ_map_parkings[i][1]), parkingIcon));
					}
					// soaz marker and final centering&zoom
					var soaz_address = "";
					var vcard = $("#contactez-nous div.vcard");
					soaz_address += (vcard.find("span.street-address span.building").text() + ", ");
					soaz_address += (vcard.find("span.locality").text() + ", ");
					soaz_address += vcard.find("span.country-name").text();
					var geocoder = new GClientGeocoder();				
					geocoder.getLatLng(soaz_address, function (point) {
						map.addOverlay(new GMarker(point, soazIcon));
						map.setCenter(point, 14);
					});
				}
			}
		});

	}();

	/**
	 *	Intro page behaviour
	 */
	var intro = function () {

		var introNav = $("#intro-nav");
		if(!introNav[0]) return false;

		var tlmi = introNav.find("> ul > li"); // top level menu items
		var contents = introNav.find("div.content");

		tlmi.each(function (i) {

			var mi = $(this);
			var content = $(contents[i]);

			var slideUpTimeout = null;
			mi.mouseover(function () {
				if (slideUpTimeout === null) {
					content.slideDown("fast");
				} else {
					clearTimeout(slideUpTimeout);
					slideUpTimeout = null;
				}
			});
			mi.mouseout(function () {
				slideUpTimeout = setTimeout(function () {
					content.slideUp("fast");
					slideUpTimeout = null;
				}, 250);
			});

		});

	}();

	/**
	 *	Initializes paginated lists in primary content
	 */
	var paginatedList = function () {

		var MAXITEMS = 14;	// NOTE: it is number of visible items on "page"

		var lists = $("ul.paginated");
		lists.each(function () {

			var list = $(this);
			var clients = list.find("li");
			if (clients.length > MAXITEMS) {

				var paginationNav = $('' +
						'<div class="dhtml paginated_list-nav">' +
							'<div class="prev_clients">&lt; '+ navigclients_prev +'</div>' +
							'<div class="next_clients">'+ navigclients_next +' &gt;</div>' +
						'</div>');
				
				$(this).after(paginationNav);

				var pageHeight = $(clients[MAXITEMS]).offset().top - list.offset().top;
	
				list.scrollTo(0);
				list.css({
					"height": (pageHeight + "px"),
					"visibility": "visible"
				});
	
				paginationNav.find("div.prev_clients").click(function () {
					list.scrollTo("-=" + pageHeight + "px", 800);
				});
				paginationNav.find("div.next_clients").click(function () {
					list.scrollTo("+=" + pageHeight + "px", 800);
				});
	
			} else {
				list.css("visibility", "visible");
			}

		});

	}();

	/**
	 *	Portfolio behaviour
	 */
	var projectsGallery = function () {

		var gallery = $("#projects_gallery");
		if (!gallery[0]) return false;

		/* scroll projects left-right */

		var nextBtn = gallery.find("div.next_project");
		var prevBtn = gallery.find("div.prev_project");

		nextBtn.hover(function () {
			$(this).addClass("next_project-hover");
		}, function () {
			$(this).removeClass("next_project-hover");
		});
		prevBtn.hover(function () {
			$(this).addClass("prev_project-hover");
		}, function () {
			$(this).removeClass("prev_project-hover");
		});

		var projectsStripeWrapper = $("#projects-wrapper");
		var projectsStripe = $("#projects");

		projectsStripeWrapper.scrollTo(0, 0, {axis: "x"});
		var scrollProjects = function (dir) {
			
			//console.info("step:"+step+" VS p. length:"+projects.length);
			
			
			
			if ((dir > 0) && (step < projects.length - 5)) {	// NOTE: "5" is number of visible projects
				step++;
				projectsStripeWrapper.scrollTo($(projects[step]), 800, {axis: "x"});
				
			} else if ((dir < 0) && (step > 0)) {
				step--;
				projectsStripeWrapper.scrollTo($(projects[step]), 800, {axis: "x"});
				
			} else if(step == (projects.length - 5)){
				
				step = 0;
				projectsStripeWrapper.scrollTo($(projects[step]), 400, {axis: "x"});
				
			} else if(dir < 0 && step == 0){
				
				step = projects.length-5;
				projectsStripeWrapper.scrollTo($(projects[step]), 400, {axis: "x"});
			}
			
			
		};

		prevBtn.click(function () {
			scrollProjects(-1);
		});
		nextBtn.click(function () {
			scrollProjects(1);
		});

		/* show details on hover */

		var focusOnSomething = false;
		var step = 0;

		var projects = projectsStripe.find("li");
		projects.each(function (i) {

			var project = $(this);
			var previewDiv = project.find("div.preview");
			var previewImage = previewDiv.find("img.image").eq(0);
			var previewBg = $($.browser.version === "6.0" ? '<div class="dhtml bg"></div>' : '<img class="dhtml bg" src="' + portfolio_project_preview_bg_image + '" alt="" />');
			var description = project.find("div.project-description").eq(0);

			var focusOnThis = false;

			gallery.append(description);
			description.css("top", "0");

			previewDiv.prepend(previewBg);

			var unfocusTimeout = null;
			var focus = function () {
				focusOnThis = true;
				focusOnSomething = true;
				if (unfocusTimeout === null) {
					project.animate({ top: "-35px" }, "normal");
					previewBg.animate({ width: "251px", height: "253px" }, "normal");
					previewImage.animate({ width: "191px", marginLeft: "-96px", marginTop: "-116px" }, "normal", function () {
						if (focusOnThis) {
							description.css("left", (i - step) * 172 + "px");
							description.show();
						}
					});
					projectsStripeWrapper.animate({ width: "909px" }, "normal");
				} else {
					clearTimeout(unfocusTimeout);
					unfocusTimeout = null;
				}
			};
			var unfocus = function () {
				focusOnThis = false;
				focusOnSomething = false;
				unfocusTimeout = setTimeout(function () {
					if (unfocusTimeout !== null) {
						project.animate({ top: "0" }, "normal");
						previewBg.animate({ width: "202px", height: "204px" }, "normal");
						previewImage.animate({ width: "152px", marginLeft: "-76px", marginTop: "-93px" }, "normal", function () {
							description.hide();
						});
						if (!focusOnSomething) {
							projectsStripeWrapper.animate({ width: "860px" }, "normal");
						}
						unfocusTimeout = null;
					}
				}, 100);
			};
			var unfocusCancel = function () {
				if (unfocusTimeout !== null) {
					clearTimeout(unfocusTimeout);
					unfocusTimeout = null;
				}
			};

			previewImage.bind("mouseenter", focus).bind("mouseleave", unfocus);
			previewImage.click(function () {
				window.location = description.find("div.more a")[0];
			});
			description.bind("mouseenter", unfocusCancel).bind("mouseleave", unfocus);
			description.click(function () {
				window.location = description.find("div.more a")[0];
			});

		});


	}();

	/**
	 *	Portfolio details behaviour
	 */
	var portfolioDetails = function () {

		var portfolioDetails = $("#portfolio-details");
		if (!portfolioDetails[0]) return false;

		var nextBtn = portfolioDetails.find("div.next_project");
		var prevBtn = portfolioDetails.find("div.prev_project");

		nextBtn.hover(function () {
			$(this).addClass("next_project-hover");
		}, function () {
			$(this).removeClass("next_project-hover");
		});
		prevBtn.hover(function () {
			$(this).addClass("prev_project-hover");
		}, function () {
			$(this).removeClass("prev_project-hover");
		});

		var thumbnails = portfolioDetails.find("div.project_description ul.preview-thumbnails img");
		var projectPreview = portfolioDetails.find("ul.preview");
		var contents = projectPreview.find("li");

		thumbnails.hover(function () {
			$(this).addClass("hover");
		}, function () {
			$(this).removeClass("hover");
		});
		thumbnails.each(function (i) {
			var thumbnail = $(this);
			thumbnail.click(function () {
				if (!thumbnail.hasClass("selected")) {
					thumbnails.removeClass("selected");
					thumbnail.addClass("selected");
					projectPreview.fadeOut("slow", function () {
						contents.hide();
						$(contents[i]).show();
						projectPreview.fadeIn("slow");
					});
				}
			});
		});

		/* init */
		contents.hide();
		$(contents[0]).show();
		$(thumbnails[0]).addClass("selected");
		projectPreview.fadeIn("slow");

	}();

});

