//Initialisation
var playlist = Array();
var plposition = 0;
var searchtime;
var imageBigillator;
var lecShown = false;
//History breaks navigation in safari, so need to test for safariness
var useHistory = navigator.userAgent.toLowerCase().indexOf('safari')==-1;
function menuSearch() {
	q = $("input#qs").attr('value').replace(/^\s*|\s*$/g,'');
	if(q=='') return false;
	filter = '&univers='+$("input#subset").attr('value');
	if(!$("div#results").length) {
	args= '&notext=true'+filter;
	mainSearch(q,args,$("td#album_cell"));
	}
	else mainSearch(q,'&resultsonly=true',$("div#results"));
}
function mainSearch(q,args,target) {
		search_href = 'search?q='+escape(q)+args;
		search_href_history = 'search?q='+encodeURI(escape(q));
		//alert(search_href_history);
		fadeTransition(search_href,target);
		updateHistory(search_href_history,'Search');
		search_href = search_href.replace(/&notext=true/,'&resultsonly=true');
		start = 26;
		$(window).unbind('scroll');
		loading = false;
		$(window).scroll(function() {
		if(!loading) {
		var ScrollTop = document.body.scrollTop;
		if (ScrollTop == 0)
		{
		    if (window.pageYOffset)
      		ScrollTop = window.pageYOffset;
    else
        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
}
		maxScroll = $("div#content").outerHeight() - (0.6 * screen.height); //Rather innacurate		
		scrollpercent = (ScrollTop / maxScroll) * 100;
		screensLeft = (maxScroll - ScrollTop) /screen.height;
		if(scrollpercent > 80 || screensLeft < 1) {
			loading = true;	
			$.get(search_href+'&start='+start,function(data) {
				$("div#results").append(data);								   
				if(data.length > 100)
				loading = false;
				start+=25;
				ajaxInit();
			});
		}
		}
		});	
	
}
//Fonctions de SoundManager
SMready = false;
if(typeof(soundManager) != "undefined") {
soundManager.url = 'src'; // directory where SM2 .SWFs live
soundManager.debugMode = false;
soundManager.onload = function() {
	SMready = true;	
	if(playlist.length>0) 
		playTrack();
}
}
function poll(sound) {
	lec_title = playlist[plposition][0];
	//Check if the current sound is loaded:
	if(soundManager.getSoundById(sound).position>500) {
	
		pos = soundManager.getSoundById(sound).position/1000;
		dur = soundManager.getSoundById(sound).durationEstimate/1000;
		posMins = Math.floor(pos/60);
		if(posMins<10) posMins = "0"+posMins;
		posSecs = Math.floor(pos%60);
		if(posSecs<10) posSecs = "0"+posSecs;
		durMins = Math.floor(dur/60);
		if(durMins<10) durMins = "0"+durMins;
		durSecs = Math.floor(dur%60);
		if(durSecs<10) durSecs = "0"+durSecs;		
	
		contString = lec_title+' ('+posMins+':'+posSecs+'/'+durMins+':'+durSecs+')';
	}
	else {
		contString = lec_title+' <img src="images/throbber.gif" alt="loading" />';	
	}
	$("td#menu_cell span").html(contString);
}
//MP3 loading gubbins
function showLec() {
	if(lecShown == true) return false;
	else lecShown = true;
			$.get("show_template.php?temp=lec", function(data){
															 $("td#menu_cell").prepend(data);
				//Fill in missing values
				updateLec();
				//Enable player controls
				$("div#lec a.afficher").unbind();
				$("div#lec a.afficher").click(function() {
					showPlaylist();		
					return false;
													   });
				$("div#lec img.next").click(function() {
					nextTrack();
													  });
				$("div#lec img.back").click(function() {
					prevTrack();
													  });
				$("div#lec img").hover(function() {$(this).css("cursor","pointer");},function(){});
				
				$("td#menu_cell").children("div#lec").fadeIn('slow');
				if(!$("div#lec").length) lecShown = false;

			});
}

function updateLec() {
	lec_title = playlist[plposition][0];
	
	if(lec_title == 'Radio') $("#lec_buy").hide();
	else $("#lec_buy").show();
	$("div#lec li").css('backgroundColor','#F3F3F3');
	$("div#lec a").filter(function() {return $(this).attr('href')==plposition;}).parent().css('backgroundColor','#FFFFFF');
	$("div#lec a.player").attr('href',playlist[plposition][1]);
	if(lec_title == 'Radio')
		$("div#lec img.pochette").attr('src','images/pochette_radio.jpg');
	else
		$("div#lec img.pochette").attr('src','thumb.php?title='+escape(lec_title));
				$("div#lec span.titre").html(lec_title+' <img src="images/throbber.gif" alt="loading" />');
				//Preload hover image
				hoverImage = new Image();
				hoverImage.src = 'thumb.php?title='+escape(lec_title)+'&size=med';
				$.get('showalb.php?title='+escape(lec_title),function(datum) {
						$("div#lec a#pochlink").attr("href",datum);												  
				});
				
				//Enable hovery magic
				$("div#lec img.pochette").unbind();
				$("a#lec_buy").attr('href','buy/'+playlist[plposition][1]);
				$("div#lec img.pochette").hover(function() {
					//Swap for larger version - if preloaded
					imageBigillator = window.setTimeout(function(image) {
					if(lec_title!='Radio')
					if(hoverImage.complete) image.attr('src',hoverImage.src);
					image.animate({width: "150px"},'fast');	
											   },220,$(this));},
					
					function() {
						window.clearTimeout(imageBigillator);
						$(this).animate({width: "80px"},'fast');
						if(lec_title!='Radio')
					$(this).attr('src','thumb.php?title='+escape(lec_title));

					});
	plist = '';
	for(i =playlist.length-1; i>=0;i--) { //Rebuild playlist
		plist+='<li><a href="'+i+'">'+playlist[i][0]+'</a></li>';
	}
	$("ol#playlist").html(plist);
	ajaxInit();
	$("ol#playlist a").unbind().click(function() {plposition=$(this).attr('href'); playTrack();return false;});
				
}
function nextTrack() {
	if(plposition > 0) {
	plposition -=1;
	}
	else plposition = playlist.length-1;
	playTrack();
}
function prevTrack() {
	if(plposition < playlist.length-1) 
		plposition +=1;
	else 
		plposition = 0;
	playTrack();
}
var poll;
function playTrack() {
	sid = playlist[plposition][1];
lec_page = 'getfile.php?sid='+sid;
	$.get(lec_page, function(data){
	if(data!='ERROR') {
	if(SMready ===true) {
	soundManager.destroySound('current');
  soundManager.createSound({id:'current',url:data,onfinish:nextTrack});
  soundManager.play('current');
if( $("td#menu_cell div#lec").text() == '') { showLec();
	} else updateLec();
  playing = true;
  $("a.player").children('img').filter(function() {return ($(this).attr('src')=='images/throbber.gif') }).attr('src','images/control_pause.png');
  	window.clearInterval('poll');
	window.setInterval("poll('current')",500);
	}
	else 
		if(playlist.length>1)
			nextTrack();
	}
  });	

}
function showPlaylist() {
	if($("ol#playlist").css('display')=='block') { 
		$("ol#playlist").slideUp();
		$("div#lec a.afficher").text('Afficher playlist');
	}
	else {
	$("ol#playlist").remove();
	plist = '<ol id="playlist">';
	for(i =playlist.length-1; i>=0;i--) {
		plist+='<li><a href="'+i+'">'+playlist[i][0]+'</a></li>';
	}
	plist+='</ol>';
	$("div#lec").append(plist);
	
	$("ol#playlist").slideDown();
	$("div#lec a.afficher").text('Masquer playlist');
	$("ol#playlist a").click(function() {plposition=$(this).attr('href'); playTrack();return false;});
	}
	$("div#lec li").css('backgroundColor','#F3F3F3');
	$("div#lec a").filter(function() {return $(this).attr('href')==plposition;}).parent().css('backgroundColor','#FFFFFF');
}
function playAlbum(lnk) {
	href = lnk.attr('href');
	$.get(href,function(data) {
	tracks = data.split('|');
	for(i=tracks.length-1;i>=0;i--) { 
		track=tracks[i]; 
		if(track =='')continue;
		playlist.push(track.split('>'));//Add to playlist
		
	}
	if( $("td#menu_cell div#lec").text() == '') { showLec();
	} else updateLec();
	plposition = playlist.length -1;
	playTrack();
	});
}
function play(lnk) {
	ltxt=lnk.attr('href');
	if(ltxt.indexOf('?') !=-1) {
	ltxt = ltxt.split('?');
	sid = ltxt[0];
	posi = ltxt[1];
	$.get('saveclick.php?id='+posi);
	}
	else sid = ltxt;
	sid = sid.substr(sid.lastIndexOf('/')+1);
	if(playlist.length == 0  || playlist[plposition][1] != sid) {
	lec_title=lnk.attr('title');
	//Add to playlist - top value of playlist
	plposition = playlist.push(Array(lec_title,sid))-1;
	lnk.children('img').attr('src','images/throbber.gif');
	updateLec();
	playTrack();
	$("a.player").not(lnk).children('img').attr('src','images/control_play.png');
	lnk.children('img').attr('src','images/control_pause.png');	
	}
	else {	
		if(soundManager.getSoundById('current').paused == true) {
			$('a.player').filter(function() {return ($(this).attr('href')==playlist[plposition][1]);}).children('img').attr('src','images/control_pause.png');
		}
		else {
		$('a.player').children('img').attr('src','images/control_play.png');
	}
	soundManager.togglePause('current');
	}
}

//Search view functions
function showMore(lnk) {
	album=lnk.attr('href').substr(6,100);
	row = lnk.parent().parent();
	if(!row.children(".texte").length) 
		row.append('<div class="texte"></div>');
	txtdiv = row.children(".texte");
	txtdiv.load('gettext.php?album='+album,function() {
		txtdiv.slideDown();																
	});
	lnk.one('click',function() {showLess($(this));return false; });
																																													
}
function showLess(lnk) {
	lnk.parent().parent().children("div.texte").slideUp();					
	lnk.one('click',function() {showMore($(this)); return false;});
}

//Ajax functions
window.dhtmlHistory.create({
        toJSON: function(o) {
                return JSON.stringify(o);
        }
        , fromJSON: function(s) {
                return JSON.parse(s);
        }
});
window.onload = function() {
        dhtmlHistory.initialize();
        dhtmlHistory.addListener(historyFunction);
};



var historyFunction = function(newLocation, historyData) {
	newLocation = decodeURI(newLocation);
	if(newLocation!='') {
	if($("td#album_cell").length)
		fadeTransition(newLocation,$("td#album_cell"));
	else
		fadeTransition(newLocation,$("div#midsection"));
	}
}
var updateHistory = function(page,title) {
	title=escape(title);
	page = encodeURI(page);
	if(useHistory)
		dhtmlHistory.add(page,title);
}
var fadeTransition = function(page,target,page_title,par_title) { //Handle transitions with fading
	//Reinitialise lecShown 
	lecShown = ($("div#lec").length) ? true : false;
	if (typeof page_title == "undefined") page_title = '';
	if($("ul#catalogue_menu").length) page = (page.indexOf('?')==-1) ? page+'?nomenu' : page +'&nomenu';
	//target.css('height',target.innerHeight());
	//target.css('width',target.innerWidth()-24);
	$("th#albums_header").append('<img class="albthrobber" src="images/throbber.gif" />');
	faded = false;//Has the fading finished? Not yet!
	loaded = false; //The ajax? Neither! Rubbish!
	//The data will be loaded while the old contents fade. When both have finished, the new contents will appear.
	xhr = $.get(page, function(contents) {
		if(xhr.getResponseHeader("x-par_title") != null) {
			par_title = xhr.getResponseHeader("x-par_title");
			page_title = xhr.getResponseHeader("x-title");	
		}
		switch(par_title) {
		case 'Cocooning': 
		$("th#albums_header").css('color','#FFD42F');
		$("div#imgfond").css('backgroundPosition','0 110px');
		$("div#imgfond").css('backgroundImage','url(images/cocoon.jpg)');
		break;
		case 'L\'art de la relaxation': $("th#albums_header").css('color','#CFCFCF');
		$("div#imgfond").css('backgroundPosition','0 120px');
		$("div#imgfond").css('backgroundImage','url(images/relax.jpg)');
		break;
		case 'L\'eau: source de vie': $("th#albums_header").css('color','#7883BB');
		$("div#imgfond").css('backgroundPosition','0 50px');
		$("div#imgfond").css('backgroundImage','url(images/eau.jpg)');
		break;
		case 'Nature & Naturel': $("th#albums_header").css('color','#98CBAB');
		$("div#imgfond").css('backgroundPosition','0 70px');
		$("div#imgfond").css('backgroundImage','url(images/nature.jpg)');
		break;
		case 'Terres lointaines': $("th#albums_header").css('color','#964B00');
		$("div#imgfond").css('backgroundPosition','0 40px');
		$("div#imgfond").css('backgroundImage','url(images/terre.jpg)');
		break;
		case 'Recherche':
		case 'Bibliothque':
		$("div#imgfond").css('backgroundPosition','0 0px');
		$("div#imgfond").css('backgroundImage','url(images/dropshad.jpg)');
		break;
		}
		if(faded==true) {target.html(contents);
		
		if(page_title !='') 	{
			if(page_title != par_title) $("th#albums_header").text(par_title + ' > '+ page_title)
			if(playlist.length >0) showLec();
			else $("th#albums_header").text(page_title);
		}

		target.css('height','auto');
		//target.css('width','auto');
		ajaxInit(); $("th#albums_header img.albthrobber").remove();}
		
		loaded = contents; //Do AJAX load and mark as done
						 });
	target.contents().not('.nofade').fadeOut('fast',function() {
		if(loaded) {target.html(loaded);
		if(page_title !='') 		$("th#albums_header").text(page_title);
		target.css('height','auto');
		if(playlist.length >0) showLec();
		//target.css('width','auto');
		ajaxInit();$("th#albums_header img.albthrobber").remove();}
		faded = true}); //Do fade and mark as done
	
	//Re-initialise AJAX events
	
}

ajaxInit = function() {
	$("a, .editable").not('a.envoyer').unbind('click');
	$("form").not("#popform").unbind('submit');
	$("div#lec a.afficher").click(function() {
			showPlaylist();		
			return false;
	});
	$("span.editable").click(function() {
        ht=$(this).outerHeight();
		wd = $(this).outerWidth();
	    edtit = escape($(this).attr('title'));
		edid = 'editable'+Math.floor(10*Math.random());
		editor = "<textarea  id='"+edid+"' name='"+edtit+"' style='width:"+wd+"px;height:"+ht+"px;'>"+$(this).html()+"</textarea>";
		$(this).before(editor);	 
		$(this).remove();
		$('#'+edid).focus();
		$('#'+edid).blur(function() {
			
			newcont = $(this).val();
			labl = $(this).attr('name');
			par = $(this).parent();
			me=$(this);
			$.post('updatetext.php',{text: escape(newcont),label: labl},function(data)
			{
			
			me.before('<span class="editable">'+newcont+'</span>');
			me.remove();
			bfore = par.css('backgroundColor');
			if(bfore == 'transparent') bfore = '#FFFFFF';
			par.css('backgroundColor','#f6ff61');
			par.animate({backgroundColor: bfore},1000,'',ajaxInit());
								  });
			});
	});
	//Catalogue search
	$("input.quicksearch").not("#main_search").unbind();

							
	$("input.quicksearch").not("#main_search").focus(function() {
		$(this).css('color','#333333');
		$(this).attr('value','');
		});
	$("input.quicksearch").not("#main_search").keyup(function(e) {
		window.clearTimeout(searchtime);
		if(e.keyCode == 13) menuSearch();
		else searchtime = window.setTimeout("menuSearch()",700);
										   
										   });
	$("div#radio h2 a").click(function() {
		$("body").unbind('click');
		if($('div#radio').css('width')=='200px') nw = 122; else nw=200;						   
		if($('div#radio').children('div').text()=='')
			$('div#radio').children('div').load('modeles/radio_explan.html',function() {
				$('div#radio').animate({width: nw+"px"},'fast',function() {
				$('div#radio').children('div').slideToggle(function() {
				$("body").not("div#radio").one("click",function() {													
					$("div#radio h2 a").click();
																});
				});	});	
																					   });
		else {
			if(nw == 122)
			$('div#radio').children('div').slideToggle(function() {$('div#radio').animate({width: nw+"px"},'fast');});
			else $('div#radio').animate({width: nw+"px"},'fast',function() {
				$('div#radio').children('div').slideToggle(function() {
				$("body").not("div#radio").one("click",function() {													
					$("div#radio h2 a").click();
																});
				});	});	
		
		}
		return false;
											 });

	$("form#searchform").submit(function() {
		
		q = $("#main_search").attr('value');
		mainSearch(q,'&resultsonly=true',$("div#results"));
		
		return false;
										 });
	$("a.player").click(function() {play($(this)); return false;});
	$("td#menu_cell li a").click(function() {
		$(this).addClass('visited');
		$("td#menu_cell li li a").css('fontWeight','normal');
		$("td#menu_cell li a").css('borderLeft','0px solid #C1C1C1');
		$("td#menu_cell li a").css('paddingLeft','0px');
		$(this).css('fontWeight','bold');
		$(this).css('borderLeft','2px solid #C1C1C1');
		$(this).css('paddingLeft','2px');
		
									   });
	$("td#menu_cell a,div.album_tile a,a#catalogue,a#philosophie,a#search,div#results a, a.fade,div.jqDock a").not('.player, .afficher,.playalbum,#lec_buy').click(function() {
																																						

	//Update topmenu
	if($(this).attr('id')=='catalogue'||$(this).attr('id')=='search'||$(this).attr('id')=='philosophie') {
		$(this).css('backgroundImage','url(images/menubarv4.png)');
		switch($(this).attr('id')) {
		case 'catalogue': bgpos	='-186px -68px'; break;
		case 'search': bgpos	='-279px -68px'; break;
		case 'philosophie': bgpos	='-93px -68px'; break;
		}
		$(this).css('backgroundPosition',bgpos);
		$("ul#topmenu li.selected a").css('backgroundImage','none');		$("ul#topmenu li.selected").removeClass("selected");
		$(this).parent().addClass("selected");
	}
	href= $(this).attr('href');
	if(href.indexOf('univers')>=0){ 
	$("input#subset").attr('value',$(this).text()); 
	$("input.quicksearch").attr('value','Recherche dans "'+$(this).text()+'"');
	
	}
	title = $(this).text();
	if($(this).attr('class') == 'child') par_title = $(this).parent().parent().parent().children('a').text();
		else par_title = title;
	updateHistory(href,title);
	if($("td#album_cell").length&&title!='Catalogue'&&title!='Fondamentaux')
	{
		if(href.indexOf('search')!=-1)href+='?nomenu';
		fadeTransition(href,$("td#album_cell"),title,par_title);	
	}
	else 
	{
		fadeTransition(href,$("div#midsection"),title,par_title);
	}
	return false;
	});	
	$("div#buy a.listen, a.playalbum").click(function() {playAlbum($(this)); return false;});


//Search table click 
$("a.texte").unbind();
$("a.texte").one('click',function() {
	showMore($(this));
	return false;
});	   
}

$(document).ready(function(){
						 
menuwidth=$('td#menu_cell').innerWidth();
$('td#menu_cell').css('width',menuwidth);			   
ajaxInit();

$("ul#topmenu > li").not("li.selected").children("a").css("background-image","none");
	
	//Boundary box for top menu
	boundTop = $('ul#topmenu').position()['top'];
	boundBottom = boundTop + $('ul#topmenu li').not(".selected").innerHeight();
	boundLeft = $('ul#topmenu').position()['left']+Number($('ul#topmenu').css('marginLeft').substring(0,$('ul#topmenu').css('marginLeft').indexOf('px')))+$("div#content").position()['left'];
	boundRight = boundLeft + $('ul#topmenu').outerWidth();
	//Preload rollover image
	rollover = new Image();
	rollover.src = "images/claims-rollover-transparent.png";
	
	$("ul#topmenu >li > a").mouseover(function() {
	thisid=$(this).attr("id");
	//claim2 = $("img#claim2");
	posI = $("img#claim2").position();
	c2x = posI['left'];
	c2y = posI['top'];
	switch(thisid) {
	case 'acceuil': offset = 0; break;
	case 'philosophie': offset = -40;break;
	case 'catalogue': offset = -80;break;
	case 'search': offset = -120;break;
	case 'forum':  offset = -160;break;
	case 'nous':  offset = -200;break;
	case 'contact':  offset = -240;break;
	
	}
	if(!$("#claimroll").length) {
	rollover = '<div id="claimroll"> </div>';
	$("img#claim2").before(rollover);
	}
	$("#claimroll").css('backgroundPosition','0 '+offset+'px');
	$("#claimroll").css('left',c2x+'px');
	$("#claimroll").css('top',c2y+'px');
	$("#claimroll").fadeIn();
	
	$(this).parent().before("<div class='nav-"+thisid+"'></div>");
	$("div.nav-"+thisid).slideDown(300);
	
	});
	$("ul#topmenu >li > a").mouseout(function(e) {
	if(e.pageY>boundBottom-1||e.pageY<boundTop+1||e.pageX<boundLeft+1||e.pageX>boundRight-1) {
/*		selectedId = $("ul#topmenu .selected a").attr('id');
			switch(selectedId) {
	case 'acceuil': offset = 0; break;
	case 'philosophie': offset = -19;break;
	case 'catalogue': offset = -38;break;
	case 'search': offset = -57;break;
	case 'forum':  offset = -76;break;
	case 'nous':  offset = -95;break;
	case 'contact':  offset = -113;break;
	}
	$("#claimroll").css('backgroundPosition','0 '+offset+'px');*/
	$("#claimroll").fadeOut();
	
	}
	theesid=$(this).attr("id");
	//alert($(this).text);
	$("div.nav-"+theesid).fadeOut(400,function() {
	$("div.nav-"+theesid).remove();
	});
	
	});	
	
	//Preload background images
	bgImages = Array('images/cocoon.jpg','images/relax.jpg','images/terre.jpg','images/nature.jpg','images/eau.jpg');
	im = Array();
	for(var i = 0; i<bgImages.length; i++) {
		im[i] = new Image();
		im[i].src = bgImages[i];
	}
	$("div#radio a.player").click();
});//End document.ready