
$(document).ready(myOnDomReady);
$(window).load(myDocumentLoad);

var g=
{
	 mainFrameW	:7
	,mainX0		:34
	,mainY0		:36
	,pageName	:""
	,contentW	:1000
	,contentH	:700
	,contentHReal:0
	,async		: "async.php"
	,cellW		:75
	,cellH		:75
	,cellSpc	:5
	,debug		: false
	,cellShowDuration:700
	,cellHideDuration:400
	,cellDx0	: 30
	,nbIm		: 16
	,im			: new Array()
	,url		: ""
	,urlEnd		: ""
	,moImDelay	: 100
	,isPgNews	: false
	,history	: false
};
// myOnDomReady
function myOnDomReady()
{
	//RQDebug("myOnDomReady with g.pageName="+g.pageName)
	if( FontDetector.M_test("Futura"))
	{	$("body").addClass('hasFonts');
		$("img.rqFont").each(function(){
			var t=$(this).attr('alt');
			$(this).replaceWith("<span>"+t+"</span>");
		});
	}

	// browser detection
	isIE = jQuery.browser.msie?true:false;
	isIE6 = (isIE && (jQuery.browser.version.charAt(0)<="6" ))?true:false;


	AdjustLayout();
	MakeMenuLinks();
	InitGrid();
	if( g.history)
	{	$.historyInit(onHistoryPage);
		// set onlick event for buttons
		$("a[@rel='history']").click(function(){
				//RQDebug('History');
				var hash = this.href;
				hash = hash.replace(/^.*#/, '');
				// moves to a new page. pageload is called at once. 
				$.historyLoad(hash);
				return false;
			});
	}


	// page dependent inits
	switch(g.pageName)
	{
		case 'Start':
			$('#content').css("opacity",0.01);
			$('#logoBig').css({position:"absolute",left:g.mainX0,top:g.mainY0,width:g.contentW-20,display:"none"});
			break;
		default:
			$('#menu').css("display","block");
	}
	inlineDomReady();
	ShowMenuWork(g.pageName=="Work");
}
function AdjustLayout()
{
	// frame sized to windows size
	var windowWidth		= $(window).width(); //$(window).width();
	var windowHeight	= $(window).height();
	g.contentW	= windowWidth-2*g.mainFrameW;
	g.contentH	= windowHeight-2*g.mainFrameW;
	$("#frame").css({width:g.contentW,height:Math.max(g.contentH,g.contentHReal)});
	$("#content").css("height",Math.max(g.contentH,g.contentHReal));
}
function MakeMenuLinks()
{	$("#menu a").RQTransformLinks();
}

jQuery.fn.RQTransformLinks=function()
{
	return this.each(function()
		{	var ref=$(this).attr('href');

			// IE Fix: removes URL from ref
			var ind=ref.indexOf(g.url,0);
			if( ind==0)
				ref=ref.substring(g.url.length)
			if(ref)
			{	$(this).data('link',ref).css({cursor:"pointer"}).removeAttr('href').mousedown(onLinkClicked);
				
			}
		}
	);
}
function onHistoryPage()
{
	//RQDebug("onHistoryPage");
}
function NewHistory(title,url)
{
	document.title=title;
	if(g.history && url) $.historyAddHistory(url);
}
function imagesPreload()
{
	if( g.isPgNews)
		RQPreload("data_image.jpg","Data/Pages/News/");
	RQPreload("data_image.jpg","Data/Pages/About/");
	RQPreload("data_image.jpg","Data/Pages/Contact/");
}

function LoadPage(name)
{
	//RQDebug("Ajax call: page="+name);
	RQAjaxCall(g.async+"?module=RQPages&action=load&page="+name,cbLoadPage)
}
function cbLoadPage(m,e)
{
	if( !e) eval(m);
}
function onLinkClicked()
{	var a=$(this);
	if(a.is('.alevel1'))
	{	$("a.alevel1").addClass('unselected');
		a.removeClass('unselected');
	}
	else if(a.is('.alevel3'))
	{	$("a.alevel3").addClass('unselected');
		a.removeClass('unselected');
	}
	var link=a.data('link');
	if( link)
		FetchURL(link);

}
function FetchURL(url)
{	$("#imageControls").fadeOut("slow");		// arrows are outside the layout
	if( $('#contentFade').text())
		$('#contentFade').fadeOut("slow",function(){doFetchURL(url);});
	else doFetchURL(url);
}
function doFetchURL(url)
{
	var wkRg=/^Work/g;
	var asncUrl =g.async+"?module=RQPages&action=fetch&url="+url;
	//RQDebug("doFetchURL("+url+")");
	wkRg.lastIndex=0;	
	if( wkRg.test(url) )
	{	var isWork=(url=="Work");
		var consultRg=/^Work\/Consulting/g;
		var projRg=/^Work\/.*\/([0-9]+)/g;
		//RQDebug(" +isWork="+(isWork?"true":"false"));
		if( isWork) CellsFilterCategory("");
		ShowMenuWork(true, function()
			{	if( isWork|| (!sIsGridOn && !consultRg.test(url))) 
					ShowGrid(true,function()
					{	//RQDebug("Grid End (a) ");
						//RQAjaxCall(asncUrl,cbLoadPage);			// Test remove
					});
				else
				{	//RQDebug("RQAjaxCall("+asncUrl+") (b)");
					projRg.lastIndex=0;
					if( projRg.test(url))
						StartLoader();
					
					RQAjaxCall(asncUrl,cbLoadPage);
				}
			} );
	}
	else
	{	//RQDebug(" +work no match");
		ShowMenuWork(false,function() {ShowGrid(false,function(){
			StartLoader();
			//RQDebug("RQAjaxCall("+asncUrl+") (c)");
			RQAjaxCall(asncUrl,cbLoadPage);
		} );});
	}
	
	
}
var sIsLoader=0;
function StartLoader()
{	if(!sIsLoader)
	{	//RQDebug("StartLoader");
		$('#loader').show().animate({opacity:1},{duration:500,queue:false},"linear");	
		sIsLoader=1;
	}
}
function StopLoader()
{
	if(sIsLoader)
	{	//RQDebug("StopLoader");
		$('#loader').animate({opacity:0},{duration:500,queue:false},"linear");	
		sIsLoader=0;
	}
}

function ShowMenuWork(m,cb)
{	//RQDebug("ShowMenuWork("+(m?"true":"false")+")");
	var a=$("#menu .children1");
	if(m)
	{	$("#Work").addClass("expanded");
		a.slideDown("slow",function(){if(cb)cb();});
	}
	else
	{	a.slideUp("slow",cb);
		$("#Work").removeClass("expanded");
	}
}
var sImgCount=0;
function SetContent(style,s,domReady)
{
	$('#content').empty();
	$('#content').attr('className',style).html("<div id=\"contentFade\">"+s+"</div>");
	if(domReady)
		eval(domReady);
	// place loaders on images
	sImgCount=0;

	//RQDebug("SetContent-style="+style);	
	if( style=="ContentPage")		// Analyse IMG inside content and install a loader
	{
		$('#contentFade img').each(function()
			{	var src=$(this).attr('src');
				$(this).removeAttr('src');
				$(this).load(onContentImgLoaded);
				$(this).attr('src',src);
				sImgCount++;
			}
		);
	}
	if( sImgCount==0)
	{	if(style=="ContentPage" || style=="twoColumns" || style=="projConsulting") StopLoader();
		$('#contentFade').fadeIn("slow");
	}
	
}
function onContentImgLoaded()
{	sImgCount--;
	if(sImgCount<=0)
	{	StopLoader();
		$('#contentFade').fadeIn("slow");		
	}
}

function InitGrid()
{
	//RQDebug("InitGrid()");
	var reg=/^i([0-9]+)j([0-9]+)$/g;
	$(".cell").each(function()
		{
			var id=$(this).attr('id');
			var a;
			if(a= reg.exec(id))
			{
				reg.lastIndex=0;
				var i=a[1];
				var j=a[2];
				var x0 = 274+i*(g.cellW+g.cellSpc);
				var y0 = 36+j*(g.cellH+g.cellSpc);
				var sX0=x0+g.cellDx0;
				$(this).data("a",{i:i,j:j,x0:x0,y0:y0,sX0:sX0}).data("m",false).css({opacity:0,left:sX0,top:y0});
			}
			else alert("err with "+id);
		}
	);
	$(".cell").RQTransformLinks();
}

var sIsGridOn=true;
var sCbCellAnimate=null;
var sCellAnimateNb=0;

function cellAnimateDone()
{
	if(sCellAnimateNb)
	{
		sCellAnimateNb--;
		if( sCellAnimateNb==0 && sCbCellAnimate)
		{
			sCbCellAnimate();
			sCbCellAnimate=0;
		}
		
	}

}
jQuery.fn.CellAnimate=function(opts)
{
	sCellAnimateNb=this.length;
	if( sCellAnimateNb==0 && sCbCellAnimate) {sCbCellAnimate();sCbCellAnimate=0;return this;}

	// clear timeouts
	var te,a;
	this.each( function(i,e){
		if( te=$(this).data("te"))
		{	window.clearTimeout(te);
			$(this).removeData("te");
		}
	});
	
	if( opts.type=="show")
	{
		return this.each( function(i,e){
			if(a=$(this).data("a"))
			{	$(this).data("te", window.setTimeout(RQDelegate(this,ShowCell),opts.delay? opts.delay : a.i*100));
			}

		}
		);
	}
	else if( opts.type=="hide")
	{
		return this.each( function(i,e){
			a=$(this).data("a")
			$(this).data("te",window.setTimeout(RQDelegate(this,HideCell),a.i*100 ));
		}
		);
	}
	else if(opts.type=="fadeOut")
	{
		return this.each( function(i,e){
			if($(this).data("m"))
			{	$(this).data("m",false);
				$(this).animate({opacity:0},500,"linear",function()
				{
					var a=$(this).data("a");
					$(this).css({left:a.sX0}).hide();
					cellAnimateDone();
				});
			}
		}
		);
	}
	else if( opts.type=="filter")
	{	return this.each( function(i,e){
			a=$(this).data("a")
			var is=$(this).is("."+opts.cat);
			$(this).data("te",window.setTimeout(RQDelegate(this,is? ShowCell:HideCell),is?1:a.i*100 ));
		}
		);
	}

}
function ShowCell()
{	if(!$(this).data("m"))
	{	var a=$(this).data("a");
		$(this).data("m",true)
		$(this).css({left:a.x0});
		$(this).css({display:"block"}).animate({left:a.x0,top:a.y0,opacity:1},g.cellShowDuration,"swing",cellAnimateDone);
	}
	else cellAnimateDone();
}
function HideCell()
{	if($(this).data("m"))
	{	var a=$(this).data("a");
		$(this).data("m",false)	
		$(this).animate({left:a.sX0,top:a.y0,opacity:0},g.cellHideDuration,"linear",function(){$(this).hide();cellAnimateDone();});
	}
	else cellAnimateDone();
}
function ShowGrid(m,cb)
{	//RQDebug("ShowGrid("+(m?"true":"false")+")");
	sCbCellAnimate=cb;
	if(m)
	{	sIsGridOn=true;
		StopLoader();
		$(".cell").CellAnimate({type:"show"});
	}
	else if( !m)
	{	if( !sIsGridOn)
		{	if(cb)cb();
		}
		else
		{	sIsGridOn=false;
			$(".cell").CellAnimate({type:"hide"});
		}
	}
}
function FadeOutThumbs()
{
	$(".cell").CellAnimate({type:"fadeOut"});
}
var sCurrentCat="";
function CellsFilterCategory(cat,cb)
{	//RQDebug("CellsFilterCategory("+cat+")");
	if( cat)
	{
		$(".children1>li").not("#m"+cat).hide("slow",function()
		{		
			if( cb)
				sCbCellAnimate=cb;

			$(".cell").CellAnimate({type:"filter",cat:cat})
			sCurrentCat=cat;
		
		});


	}
	else
	{	$(".children1 li").show("slow").find(".children2").empty();
		sCurrentCat="";
		if(cb) cb();
	}
}
function SetMenuItems(cat,s)
{	//RQDebug("SetMenuItems("+cat+")");
	if(s)
	{	$(".children1 li").not("#m"+cat).hide("slow");

		$("li#m"+cat+" .children2").html(s).slideDown("slow").find("a").RQTransformLinks();
		
	}
}

// myDocumentLoad
function myDocumentLoad()
{	
	switch(g.pageName)
	{
		case 'Start':
			$("#inset").hide();
			LogoAnimate();
			break;
		default:
			InstallResize();
			break;
	}
	
}
function InstallResize()
{
	$(window).resize(onWindowResize).scroll( onWindowScroll);
}
function LogoAnimate()
{	
	// install images
	var nb=g.nbIm;
	var i;
	$("body").append("<div id=\"logoBig\"></div>");
	for(i=0; i<nb;i++)
	{	
		g.im[i]=$(new Image());
		g.im[i].attr('id',"mo"+i).css({position:"absolute",top:g.mainY0,left:g.mainX0,zIndex:10+i,display:"none"});
		$("#logoBig").append(g.im[i]);
	}
	for(i=0; i<nb;i++)
	{	g.im[i].load(onLogoImgLoaded).attr('src',"Data/Img/mo"+(i+1)+".gif");
	}
	//$('#logoBig').show();
	//$('#logoBig img').animate({width:837,height:364},1000,"linear",onLogoAnimateDone);
	
}
function onLogoImgLoaded()
{
	//RQDebug($(this).attr('id')+" loaded");
	g.nbIm--;
	if(g.nbIm==0)
	{	//launch animation
		var i;
		for(i=0;i<g.im.length;i++)
		{	
			window.setTimeout("showMoIm('"+i+"');",10+g.moImDelay*i);
		}
		// preload content images
		imagesPreload();
	}
}
function showMoIm(i)
{
	g.im[i].fadeIn("slow");
	//RQDebug("g.im.length="+g.im.length+" i="+i);
	if(i==g.im.length-1)
		window.setTimeout(onLogoAnimateDone,1000);
}
function onLogoAnimateDone()
{
	$('#inset').show();
	$('#content').css("opacity",1);
	$('#logoBig').hide();
	InstallResize();
	$('#menu').slideDown("slow",function(){if(g.isPgNews) FetchURL("Page/News"+g.urlEnd)});
}

function onWindowResize()
{
	AdjustLayout();
}
function onWindowScroll()
{
	AdjustLayout();

}
function RQDebug(s)
{	if(g.debug)
	{	$('#debug').append("<div>"+s+"</div>");
	
		
	}
}



// ------- layouts domReady ------
var sGfxInfoVisible=false;
var sGfxCurrInfo=null;
var sVideoTitle="";
var sVideoTitleOn=false;
var sTimerTitleRollout=null;
var sPlaylistOn=false;
var sPlaylistVisible=false;
var sPlayer;
var sCurrAlbum=0;

function onGraphicDesignReady()
{
	var nb=0;
	var img;
	$("#content .image img").each(function(i,e)
		{	$(this).data("index",1+i);
			if( i>0) {	$(this).hide(); }
			else
			{
				img=$(this).hide().addClass("current");
				// reset image's src to trigger load event
				var src=img.attr('src');
				img.removeAttr('src');
				img.load(onGfxImageLoaded);
				img.attr('src',src);
			}
			nb++;
		}
	);
	$("#content .info,#imageTitleBlock").hide();
	$(".imgInfoBtn,.imgCloseInfoBtn").click(function(){ 
		var o=sGfxCurrInfo;
		sGfxInfoVisible=!sGfxInfoVisible;
		GfxAjustToImage($("img.current"));		
	});
	if( nb>1)
	{	$("#content").append("<div id=\"imageControls\"><a class=\"btnRight\" onmousedown=\"return switchToImage(1);\"><img src=\"Data/Img/arrowRight.gif\" border=\"0\" alt=\"arrow right\" /></a><a class=\"btnLeft\" onmousedown=\"return switchToImage(0);\"><img src=\"Data/Img/arrowLeft.gif\" border=\"0\" alt=\"arrow left\" /></a></div>");
		$("#imageControls").hide().data("nb",nb);
	}
	else
		StopLoader();
		
	//if( img)img.load(onGfxImageLoaded);
}

function showVideoForProject(projid)
{
	// install player
	var so = new SWFObject("Data/Flash/VideoPlayer/player.swf", "thePlayer", "392", 294+49, "9", "#FAFAFA");
	so.addParam('allowfullscreen',"true");
	so.addParam('allowscriptaccess','always');
	so.addVariable('width','392');
	so.addVariable('height','294');
	so.addVariable();
	so.addVariable('backcolor','0x266EBB');
	so.addVariable('frontcolor','0xFFFFFF');
	//so.addVariable("file", "http://localhost:8888/Clients/MOCreativesLimited/mocreatives.com/Produit/playlist.xml");
	so.addParam("flashvars","bufferlength=4&skin="+g.url+"Data/Flash/VideoPlayer/moplayerSkin2.swf"+"&controlbarsize=49&autostart=false&repeat=list&item=0&file="+g.url+"playlist"+projid+".xml");
	so.write('videoPlayer');

}
function onCategoryVideoPlayer()
{
	// hide playlist / playlist button
	$(".playlist,#btnPlaylist").hide();
	$("#videotitle .title").css({opacity:0.02});

	// playlist close button
	$(".playlist .imgCloseInfoBtn").click(function(){ 
		sPlaylistOn=false;hasPlaylist();
	});

	$("p.info").hide();
	$(".imgCloseInfoBtn").click(function(){
		$("p.info").fadeOut("slow");
		$("#btnInfo").fadeIn("slow");
	});


	// install events on album thumbs
	var index=0;
	$(".albums a").each(function()
	{	
		$(this).mouseover(function(){
			if( !$(this).is("current")) rolloverTitle($(this).find("img").attr('alt'));
		});
		$(this).mouseout(function(){
			rolloutTitle();
		});
		
	});
	StopLoader();
	
	// adjust scroll bar
	g.contentHReal = g.mainY0+540;	// 2 thumbs rows
	AdjustLayout();

}
function playAlbum(id)
{	sPlayer.sendEvent('ITEM',id);
}
function playTrack(id)
{	sPlayer.sendEvent('ITEM',id);
}


function playerReady(obj) 
{	var id = obj['id'];
	var version = obj['version'];
	var client = obj['client'];
	sPlayer = document.getElementById(id);
	if (sPlayer)
	{	sPlayer.addControllerListener("ITEM", "RQJWPlayerChangeItem");
		sPlayer.addControllerListener("STOP", "RQJWPlayerItemStopped");
	} 
};
function RQJWPlayerChangeItem(obj)
{	//{index,id,client,version}
	$(".albums a.track"+obj.index+"").each(function(){
		sCurrAlbum=parseInt($(this).attr('id').replace(new RegExp("(album)","g"),""));
		var title = $(this).find("img").attr('alt');
		//RQDebug("player ChangeItem "+title+" album="+sCurrAlbum);
		setVideoTitle(""+title,true);	// Now playing
		// alpha on album thumbs
		$(this).addClass("current").fadeTo(500,1).siblings().removeClass("current").fadeTo(1000,0.3);

		// playlist tracks title
		$trck=$('.playtrack'+obj.index);
		if($trck.is("li"))
		{	hasPlaylist();
			$("#videotitle .track").fadeOut("slow", function(){
				$(this).html(""+$trck.find('.number').text()+"/"+(1+$trck.siblings().length)+": "+$trck.find("a").text() ).fadeIn("slow");
			} );
			$trck.fadeTo(500,1).siblings().fadeTo(1000,0.3);

		}
		else
			doesntHavePlaylist();
	});

}
function hasPlaylist()
{
	if( sPlaylistOn)
	{	var plSwitch=sPlaylistVisible!=(1+sCurrAlbum);
		if( (!sPlaylistVisible)||plSwitch)
		{	
			if(plSwitch)$(".playlist").not("#playlist"+sCurrAlbum).fadeOut("slow",function(){$(this).hide();});
			sPlaylistVisible = 1+sCurrAlbum;
			$("#playlist"+sCurrAlbum).css({opacity:0.02}).show().fadeTo(800,1);
			$("#btnPlaylist").fadeOut("slow");
		}
	}
	else
	{		$("#btnPlaylist").css({opacity:0.02}).show().fadeTo(500,1);
			if( sPlaylistVisible)
				$(".playlist").fadeOut("slow",function(){$(this).hide();});
			sPlaylistVisible = false;
	}
}
function doesntHavePlaylist()
{	
	$("#videotitle .track").fadeOut("slow",function(){$(this).html("");});
	$(".playlist,#btnPlaylist").fadeOut("slow",function(){$(this).hide();});
	sPlaylistVisible = false;
}
function showPlaylist()
{	sPlaylistOn=true;
	hasPlaylist();
}

function showInfoPane()
{	$("p.info").fadeIn("slow");
	$("#btnInfo").fadeOut("slow");
}
function setVideoTitle(title,isSave)
{	//RQDebug("setVideoTitle(\""+title+"\","+(isSave?"SAVE":"temp")+") (vis="+(sVideoTitleOn?"true":"false")+")");
	var t=$("#videotitle .title");
	if(isSave)
		sVideoTitle=title;		
	if( title)
	{		var d=isSave?700:150;
			if( sVideoTitleOn && (title!=t.text()) )
				t.fadeTo(d,0.03, function(){$(this).html(title).fadeTo(d,1);} );
			else
				t.html(title).fadeTo(d,1);
			sVideoTitleOn=true;
	}
	else
	{	if( sVideoTitleOn)
			t.fadeTo(500,0.02);
		sVideoTitleOn=false;
	}
}
function rolloverTitle(title)
{	//RQDebug("rolloverTitle(\""+title+"\")");
	
	if( sTimerTitleRollout)
	{	window.clearTimeout(sTimerTitleRollout);
		sTimerTitleRollout=0;
		//RQDebug("...timeout interrupted");
	}
	setVideoTitle(title,false);

}

function rolloutTitle()
{
	//RQDebug("rollout timeout...");
	sTimerTitleRollout=self.setTimeout(doRolloutTitle,1000)
}
function doRolloutTitle()
{
	//RQDebug("do rollout title");
	setVideoTitle(sVideoTitle,false);
	sTimerTitleRollout=0;
}
function RQJWPlayerItemStopped(o)
{
	//RQDebug("player stopped");
	sCurrAlbum=0;
	$(".albums a").fadeTo(500,1);
	setVideoTitle("",true);
	$("#videotitle .track").fadeOut("fast",function(){$(this).html("");});
	$(".playlist li").css({opacity:1});
}




// onGfxImageLoaded
function onGfxImageLoaded()
{	
	StopLoader();

	$("#imageTitleBlock").css({position:"absolute",left:0,top:$(this).height(),width:$(this).width()});
	$(this).fadeIn("slow",adjustGfxElements);
}
function adjustGfxElements()
{
	$("#imageControls").fadeIn("slow");
	GfxAjustToImage($(this));
}
function GfxAjustToImage(img)
{	if(img)
	{
		var w=635;//img.width();
		var h=img.height();
		var imPos={left:274,top:36};

		$(".imgTitle span.title").html(img.attr("alt"));
		$("#content .info").hide();
		var inf=$("#content .info"+img.data("index"));
		var infW=316;
		if(inf.is(".info"))	// is there an info block?
		{	sGfxCurrInfo=inf;
			if(sGfxInfoVisible)
			{	inf.css({left:(imPos.left+w-infW)}).fadeIn();
				$(".imgInfoBtn").hide();
			}
			else
			{	$(".imgInfoBtn").show();
			}
		}
		else
		{	sGfxCurrInfo=null;
			$(".imgInfoBtn").hide();
		}
		// image title moves softly
		$("#imageTitleBlock").animate({top:h+5,width:img.width()},{duration:400,queue:false},"easeInOutCubic")
		
		
		// adjust scroll bar
		g.contentHReal = g.mainY0+h+5+18*2;
		AdjustLayout();
	}
}
function switchToImage(dir)
{
	var img=$("img.current");
	img.removeClass("current").css({position:"absolute",top:0,left:0,zIndex:110}).fadeOut("slow");
	var next=dir?img.next('img'):img.prev('img');
	if( !next.length) next=img.siblings("img").filter(dir?":first-child":":last");
	next.css({position:"relative",zIndex:109}).fadeIn("slow").addClass("current");
	//Change the page number : $("#imageControls div span").html(next.data('index'));	//<div><span>1</span>/"+nb+"</div>
	var nb=$("#imageControls").data("nb");
	if( nb>1)
	{	$(".imgTitle span.counter").html(next.data('index')+" / "+nb+": ");
	}
	GfxAjustToImage(next);

	return false;
}
