﻿// v2 : img.clone() -> new Image();

var AL = {};
AL.base = "http://www.aissalogerot.com/";
if(window.location.href.indexOf("localhost") != -1) AL.base = "http://localhost/template/";
AL.loader = "<img class='loader' src='"+AL.base+"img/loader.gif' />";
AL.video = "<img src='"+AL.base+"img/video.gif' />";

// CONST
AL.hMax = 10;
AL.wMax = 0;

// Container
AL.gallery = null;
AL.container = null;
AL.main = null;
AL.currentImg = null;
AL.ready = false;

AL.init = function()
{
	//AL.initSidebar();
	
	var url = document.location.toString();
	if(url.indexOf("/projects") != -1 || url.indexOf("/news") != -1 || url.indexOf("/press") != -1)
		AL.initGallery();
	if(url == AL.base)
		AL.initHome();
	
	
    $('a').click(function() {this.blur();});
	
	AL.initSWFAddress();
	AL.initSidebar();
}

AL.initSWFAddress = function()
{
	SWFAddress.addEventListener("change", AL.handleChange);
	AL.updateLinks();
}

/**
 * Get all the links of the target HTML content and replace each of them
 */
AL.updateLinks = function(html)
{
	var links = $("a", html);
	links.each(AL.updateLink);
}

/**
 * Add the # so that the link will change the anchor instead of opening the target URL
 */
AL.updateLink = function()
{
	var href = this.href;
	var text = $(this).text();
	
	if(href.indexOf(AL.base + "#") == -1)
	{
		href = href.split("#").join("");
		
		var parts = href.split(AL.base);
		var path = parts[1];
		
		// avoid wordpdress link replacement
		if(path && path.indexOf("wp-") != -1) return;
		if(path && path.length) 
		{
			href = parts.join(AL.base + "#" + (path.length ? "/" : ""));
			
			this.href = href;
			this.innerHTML = text;
		}
	}
}


AL.handleChange = function ()
{
	var value = SWFAddress.getValue();
	
	if(AL.isValid(value))
	{
		$("a").removeClass("selected");
		AL.loadPage(value);
		
		var link = $("#sidebar a[href="+AL.base + "#" + value + "]");
		if(link.length)
		{
			link.addClass("selected");
			//link.before("»");
			//«‹›
			var p = link.parent();
			while(p != undefined && !p.hasClass("navigation")) 
			{
				//console.log(p);
				if(p.css("display") != "block") p.slideDown("normal");
				p = p.parent();
			}
		}
	}
}

AL.isValid = function(value)
{
	var valid = false;
	
	if (value == "") return false;
	if(value.indexOf("more-info") != -1) return true;
	var links = $("#sidebar a[href="+AL.base + "#" + value + "]");
	return links.length == 1;
}

AL.loadPage = function (path)
{
	//AL.trackPage(path);
	var h = $("#content").height();
	$("#content").html(AL.loader);
	$("#content").css("height", h);
	$("#content").load(AL.base + path + " #content .post", AL.showContent);
}

AL.showContent = function()
{
	$("a").css("cursor", "pointer");
	AL.initGallery();
	var content = $("#content");
	var children = content.children();
	children.css("display", "none");
	children.fadeIn();
	
	$("#content").css("height", "auto");
	$("#content p").each(AL.hideEmptyParagrah);
	AL.updateLinks();
}

AL.hideEmptyParagrah = function ()
{
	if($("img", this).length == 0 && $(this).text() == "") $(this).css("display", "none");
}


AL.initSidebar = function()
{
	// All the first items of the menu slideToggle
	var ul = $("#sidebar>ul");
	$("ul", ul).css("display", "none");
	$("ul ul li a").each(AL.initBullet);
	$("a", ul).click(AL.slideToggle);
}

AL.initBullet = function ()
{
	var before = "-";
	var p = $(this).parent();
	var subNav = $("ul", p);
	if(subNav.length) 
	{
		before = "<font color='#000'>› </font>";
	}
	else before = "<font color='#aaa'>› </font>";
	
	$(this).prepend(before);
}

AL.slideToggle = function ()
{
	if(this.title == "links")
	{
		AL.loadLinks();
		return false;
	}
	else if(this.title == "about me")
	{
		AL.loadAboutMe();
		return false;
	}
	else if(this.title == "contact")
	{
		AL.loadContact();
		return false;
	}
	
	var subNav = $(">ul", $(this).parent());
	if(subNav.length) 
	{
		subNav.slideToggle("normal");
		return false;
	}
	else if(this.href.indexOf("#") != -1)
	{
		var value = this.href.split("#")[1];
		$(this).addClass("selected");
		SWFAddress.setValue(value);
		
		return false;
	}
	else
	{
		return true;
	}
}


//
//AL.initSidebar = function()
//{
	//var items = $("#sidebar>ul>li>a");
	//items.each(this.initUnwrap);
//}


AL.initUnwrap = function()
{
	if(	$("ul", $(this).parent()).length  > 0) 
	{
		$(this).bind("click", {}, AL.unwrap);
		$("ul", $(this).parent()).addClass("wrappable");
		// vérifier si un des elements n'est pas ".current_page_item"
		//console.info($("ul li .current_page_item").length);
		if($(".current_page_item", $(this).parent()).length == 0)
			$("ul", $(this).parent()).css("display", "none");
	}
	else
	{
		
		switch(this.title)
		{
			case "links":
				$(this).bind("click", {}, AL.unwrap);
				$.ajax({
					url: this.href,
					cache: false,
					success: function(html)
					{
						$("#sidebar>ul>li>a[title='links']").after($("div.entry", html).addClass("wrappable").css("display", "none"));
					}
				});
			break;
			case "contact":
				$(this).bind("click", {}, AL.unwrap);
				$.ajax({
					url: this.href,
					cache: false,
					success: function(html)
					{
						$("#sidebar>ul>li>a[title='contact']").after($("div.entry", html).addClass("wrappable").css("display", "none"));
					}
				});
			break;
			case "about me":
				$(this).bind("click", {}, AL.unwrap);
				$.ajax({
					url: this.href,
					cache: false,
					success: function(html)
					{
						$("#sidebar>ul>li>a[title='about me']").after($("div.entry", html).addClass("wrappable").css("display", "none"));
					}
				});
			break;
		}
	}
}

AL.toggleContent = function (e)
{
	$(".wrapContent", $(this).parent()).slideToggle("fast");
	return false;
}

AL.unwrap = function (e)
{
	$(".wrappable", $(this).parent()).slideToggle("fast");
	return false;
}

AL.hideSubItems = function (i)
{
	var items = $("#sidebar>ul>li");
	var item = $("#sidebar>ul").get(i);
	//console.info(i + " " + item);
}



AL.initGallery = function ()
{
	//alert("init gallery");
	var gallery = "<div id='al_gallery' />";
	$("#content div.entry").prepend(gallery);
	AL.gallery = AL.container = $("#al_gallery");
	//AL.container.css("border", "1px solid pink");
	AL.gallery.css("width", "640px");
	AL.container.css("float", "left");
	
	// INJECT CONTAINER
	var container = "<div id='al_container'/>";
	AL.gallery.prepend(container);
	AL.container = $("#al_container");
	AL.container.css("width", "640px");
	//AL.container.css("height", "480px");
	//AL.container.css("border", "1px solid green");
	
	// INJECT MAINIMAGE
	var mainImg = "<div id='al_main'/>";
	AL.gallery.prepend(mainImg);
	AL.main = $("#al_main");
	//AL.main.css("border", "1px solid red");
	AL.main.css("width", "640px");
	AL.main.css("height", "480px");
	AL.main.css("margin-bottom", "4px");
	
	// INIT IMAGES
	// TODO: récupérer la liste de tous les <p>.
	// Parcourir les paragraphes et traiter les img et les embed / object
	var imgs = $("#content img");
	imgs.each(this.initImg);
	
	//console.info(imgs.length);
	if(imgs.length < 2) AL.container.css("display", "none");
	if(imgs.length == 0) AL.gallery.css("display", "none");
}

AL.initImg = function(i)
{
	var img = $(this);
	var w = img.css("width").split("px").join("");
	var h = img.css("height").split("px").join("");
	
	AL.hMax = Math.max(h, AL.hMax);
	
	img.click(AL.select);
	img.css("width", "64px");
	img.css("height", "48px");
	img.css("cursor", "pointer");
	AL.container.append(img);
	
	// Si le cheùin de l'image contient vimeo
	// on définit le paramètre data("video") pour générer un lecteur au lieu de cloner l'image
	// ex : src = /images/vimeo/id.jpg
	var src = this.src;
	var vimeoIndex = src.indexOf("vimeo");
	if(vimeoIndex != -1)
	{
		var id = src.substring(vimeoIndex + 6, src.indexOf(".", vimeoIndex));
		img.data("video", id)
	}
	
	if(i == 0) AL.displayImg(img);
}
AL.vimeo = function (id)
{
	var out ='<object width="640" height="480" data="http://vimeo.com/moogaloop.swf?clip_id='+id+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://vimeo.com/moogaloop.swf?clip_id='+id+'&amp;server=vimeo.com&amp;show_title=0&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /></object>';
	return out;
}

AL.unselect = function(img)
{
	AL.main.html("");
}


AL.displayImg = function (target)
{
	if(target.data("video") != undefined) 
	{
		var id = target.data("video");
		AL.main.append(AL.vimeo(id));
	}
	else 
	{
		// v1
		//var clone = img.clone();
		//AL.currentImg = clone;
		//AL.main.append(clone);
		//
		//clone.css("width", "640px");
		//clone.css("height", "480px");
		//clone.css("cursor", "auto");
		//clone.css("display", "none");
		//clone.fadeIn("fast");
		
		// v2
		var src = target[0].src;
		var img = new Image();
		img.src = src.split("/thumbs/").join("/");
		AL.main.html(img);
		$(img).css("display", "none");
		$(img).fadeIn("fast");
	}
}

AL.initHome = function()
{
	var imgs = $("div.entry img");
	imgs.css("display", "none");
	var n = Math.round(Math.random() * (imgs.length - 1));
	
	// old
	// $(imgs[n]).css("display", "block");
	
	// new
	var thumb = $(imgs[n])[0];
	var img = new Image();
	img.src = thumb.src.split("/thumbs/").join("/");
	$("#content div.entry").html(img);
}

AL.select = function()
{
	if(AL.currentImg) AL.unselect(AL.currentImg);
	
	AL.displayImg($(this));
}

AL.loadLinks = function ()
{
	if(AL.linksLoaded) AL.toggleLinks();
	else 
	{
		var link = $("a[href=" + AL.base + "#/links/]");
		link.after("<div class='linkContent'>"+AL.loader+"</div>");
		AL.linkContent = $(".linkContent", link.parent());
		AL.linkContent.load(AL.base + "links/ #content .entry", AL.linksComplete);
	}
}

AL.linksComplete = function ()
{
	AL.linksLoaded = true;
}

AL.toggleLinks = function ()
{
	AL.linkContent.slideToggle("slow");
}

AL.loadAboutMe = function ()
{
	if(AL.aboutMeLoaded) AL.toggleAboutMe();
	else 
	{
		var aboutme = $("a[href=" + AL.base + "#/about-me/]");
		aboutme.after("<div class='aboutMeContent'>"+AL.loader+"</div>");
		AL.aboutMeContent = $(".aboutMeContent", aboutme.parent());
		AL.aboutMeContent.load(AL.base + "about-me/ #content .entry", AL.aboutMeComplete);
	}
}

AL.aboutMeComplete = function ()
{
	$(".aboutMeContent p").each(AL.hideEmptyParagrah);
	AL.aboutMeLoaded = true;
	AL.updateLinks();
}

AL.toggleAboutMe = function ()
{
	AL.aboutMeContent.slideToggle("slow");
}

AL.loadContact = function ()
{
	if(AL.loadingContact && !AL.contactLoaded) return;
	else AL.loadingContact = true;
	if(AL.contactLoaded) AL.toggleContact();
	else 
	{
		var contact = $("a[href=" + AL.base + "#/contact/]");
		contact.after("<div class='contactContent'>"+AL.loader+"</div>");
		AL.contactContent = $(".contactContent", contact.parent());
		AL.contactContent.load(AL.base + "contact/ #content .entry", AL.contactComplete);
	}
}

AL.contactComplete = function ()
{
	AL.contactLoaded = true;
	AL.updateLinks();
}

AL.toggleContact = function ()
{
	AL.contactContent.slideToggle("slow");
}

AL.trackPage = function (value)
{
	try
	{
		var pageTracker = _gat._getTracker("UA-7601108-1");
		pageTracker._trackPageview(value);
	} catch(err) {}
}


$(document).ready(function(){
	AL.init();
});

