isIE=document.all?true:false;
isNS4=document.layers?true:false;
isNS6=document.getElementById?true:false;
isOpera=navigator.appName.indexOf('opera')!=-1?true:false;
var isAdmin = false;
var tplstyle = "background-color:#202020;";
var topDesign = "images/deco3.png";
var activePage = 0;
var activeMag = 0;
var magT = ["SlideMag Home","Sept-Oct '09","Dec '09","Jan '10","Fev '10","Mars '10"];
var magObj = {};
var pagesT = [];
var slideShowTimer = null;//some pages can contain slideshows
var slideShowT = null;
var slideShowPath = null;
var slideShowIndex = 0;		
function addFbLog(msg){
	//console.log(msg);
}
function LoadMag(num,actPg,explicitPath){
	loadedMag=true;
	activePage = (actPg==null) ? 0 : actPg;
	activeMag = num;
	explicitPath = (!explicitPath) ? "mags/mag"+num+".js" : num;
	LoadScript(explicitPath+"?date="+new Date().getTime() , function(){openMag()} , null);
	addFbLog("Page:"+activePage+" ,LoadMag : "+activeMag+", explicitPath:"+explicitPath);
}
function openMag(){addFbLog("openMag :: "+magObj.title);
	resetSlideShow();
	if(magObj.topDesign!=null)
		topDesign = magObj.topDesign;
	document.body.style.cssText=magObj.style;
	if(magObj.containerStyle!=null)$('container').style.cssText=$('container').style.cssText+magObj.containerStyle;
	pagesT = magObj.pagesT;
	document.title=magObj.title;
	buildMagIndex();
	pageTurn();
	
}
function openPage(num){addFbLog("openPage :: "+num);
	resetSlideShow();
	if(num!=null && num!=undefined && pagesT[num]!=null)
		activePage = num;
	openX("container",pagesT[activePage].template);
	direction = null;
	selectIndex();
}
function pageTurn(direction){
	if(direction>0){
		if(activePage >= pagesT.length-1){
			if(activeMag >= magT.length)
				activePage = 0;
			else
				LoadMag(activeMag+1);
		}else
			activePage = activePage+1;
	} else if(direction<0)
		activePage = (activePage - 1 < 0 )? 0 : activePage-1;
	addFbLog("count : "+pagesT.length+" mag :"+activeMag+" ::pageTurn :: "+activePage);
	if(pagesT[activePage]==null)
		activePage = 0;
	if(direction>0)
		ListPreLoadElements(activePage);
	openPage(activePage);
}
function openX(id,tpl){//ajax page insertion
	if(id!=null){
		$(id).update('<img src="images/loading.gif" width="50px"/>');
		doThis = new Ajax.Updater(id, "templates/"+tpl+'?date='+new Date().getTime(), 
					{method: 'get',evalScripts:true});
	}
}
var postBuild = null;
function buildTemplate(tplO){ //Generic Template builder strict relation between /templates/xxx.html and associated JSON definition
	if(activePage<0)
		activePage=0;
	dhtmlHistory.add(activeMag+"xxx"+activePage,historyData);
	addFbLog("buildTemplate :: activePage :"+activePage);
	var tplObjs = (tplO!=null) ? tplO : pagesT[activePage];
	addFbLog("buildTemplate :: "+tplObjs.template);
	var whereAndwhatSrc = "",paTitleHTML="",numeroHTML="",whereAndwhatHTML="",sessionHTML="";
	pagination = activePage+1;
	for(p in tplObjs){
		tplObj = tplObjs[p]; 
		addFbLog(p+" > "+typeof tplObj+" > "+tplObj);
		if(p != "template" && p != "cover"){
			if(p.indexOf("whereAndwhat")>=0){
				if(p.indexOf("$link")>=0){
					whereAndwhatHTML = "<a href='"+tplObj.url+"' target='_blank' style='position:absolute; top:30px; left:0px;z-index:0;font-weight:bold;'>"+tplObj.label+"</a>";
				}else{
					whereAndwhatSrc = tplObj;
					if(whereAndwhatSrc.indexOf(",")<0)
						whereAndwhatHTML = "<img border=0 style='position:absolute; top:10px; left:10px;' src='"+whereAndwhatSrc+"'/>"
					else{
						var reg = new RegExp("[ ,]+", "g");
						var whereAndwhaT=whereAndwhatSrc.split(reg);
						for (var i=0; i<whereAndwhaT.length; i++) {
						 whereAndwhatHTML += "<img  border=0 style='position:absolute; top:10px; left:10px;' src='images/"+whereAndwhaT[i]+".gif'/>"
						}
					}		
					whereAndwhatHTML += "<img border=0 style='position:absolute; top:0px; left:0px;z-index:-1;' src='"+topDesign+"'/>";
				}
			} else if(p == "pageTitle"){
				document.title = tplObj +" - "+ magObj.title;
				pageTitleHTML = "<span style='float:right' id='pageTitle'>"+tplObj+"</span>";
			} else if(p == "numero")
				numeroHTML = '<span style="float:left" id="numero">'+tplObj+' &bull; '+pagesT.length+' PAGES </span>';
			else if (p == "session")
				sessionHTML = "<span style='font-size: large' id='session'><a style='text-decoration:none;' href='"+tplObj+"' target='_blank'>Voir toute les Photos de la Session</a></span>";
			else if (p == "picasa"){
				myThemes["photo"].whatswap = tplObj.albumId;
				myThemes["photo"].count = null;
				getAndBuildPicasaList( tplObj.userId,"picasaContainer" , "photo" , true,"picasaAlbumTpl","",null );
				postBuild = tplObj.init;
			} 
			else if (p == "delicious"){
				myThemes[tplObj.deliCat] = new Theme( tplObj.userId,tplObj.deliCat,tplObj.count, tplObj.destId ),
				getAndBuildDeliciousList( tplObj.destId , tplObj.deliCat,true,tplObj.buildStyle,null );
			} 
			else if (p.indexOf("$script")>=0){
				LoadScript(tplObj.uri , function(){(tplObj.callback)()} , null);
			}
			else {
				if(p.indexOf("$srcO")>=0){//slideShow Object
					slideShowT = tplObj.imgT;
					slideShowPath = tplObj.path;
					imgId = p.substring(0,p.length-5);
					slideShowTimer = new PeriodicalExecuter(function(pe){ showNextSlide(imgId); },4);
					$(p.substring(0,p.length-5)).src = slideShowPath + slideShowT[0].src;
					if($("imgTitle")!=null)
						$("imgTitle").innerHTML = slideShowT[0].title;
					else
						new Insertion.After(p.substring(0,p.length-5), ' <br/><span style="padding:0 25px 0 25px;font-weight:bold; font-size:large;padding:10px;background-color:white;color:black;" id="imgTitle">'+slideShowT[0].title+"</span>");
					//preLoadElements(slideShowT , slideShowPath);
				} else if(p.indexOf("$src")>=0){//simple img src
					if(tplObj=="")
						$(p.substring(0,p.length-4)).parentNode.removeChild($(p.substring(0,p.length-4)));
					else{
						$(p.substring(0,p.length-4)).src = tplObj;
						if($("a_"+p.substring(0,p.length-4))!=null)//adds Link LightBox Viewer
							$("a_"+p.substring(0,p.length-4)).href = tplObj;
					}
				} else if(p.indexOf("$style")>=0)//style change
					$(p.substring(0,p.length-6)).style.cssText = tplObj;
				else if(p.indexOf("$href")>=0)//href change
					$(p.substring(0,p.length-5)).href = tplObj;
				 else if(p.indexOf("$js")>=0)//execute JS function
					 tplObj();
				else{ //simple HTMl swap
					if($(p)!=null)
						$(p).innerHTML = tplObj;
				}
			}
			
		}
	}
	
	if(numeroHTML == "")numeroHTML = "<span style='float:left'>PAGE "+pagination+"</span>";
	$("container").innerHTML = "<div style='margin: 0 20px 0 20px;position:absolute;top:0px;left:0px;width:95%;font-weight:bold;'>"+whereAndwhatHTML+numeroHTML+pageTitleHTML+sessionHTML+"</div>"+$("container").innerHTML;
}
var magIndex = []; 
var coverSlideShowT = [];
function buildMagIndex(){//The index is build whenever a mag is loaded
	//if a base PageTitle doesn't change between pages then only the first occurence is added to the index
	magIndex = [],countIndex = 0; countslideIndex = 0; previousSubject = "tmp";
	if($("menuLeft")!=null){
		$("menuLeft").innerHTML = '';
		for(i=0 ; i < pagesT.length ; i++){
			pageTtl = pagesT[i].pageTitle; 
			if(pageTtl !="" && pageTtl.indexOf(previousSubject) < 0){addFbLog("buildMagIndex::"+i+"::"+pageTtl);
				magIndex.push({id:"indexLink"+countIndex , name:pageTtl , page:"#"+activeMag+"mag"+i , from:i , to:0});
				previousSubject = pageTtl.strip();
				if(countIndex>0)(magIndex[countIndex-1]).to = i;
				pos = (countIndex * 31);
				new Insertion.Bottom("menuLeft",'<a style="position:absolute;top:'+pos+'px;left:5px;" id="indexLink'+countIndex+'" class="menu" href="javascript:openPage('+i+')" > '+pageTtl+'</a>');
				if((pagesT[i]["img1$src"]!=null && pagesT[i]["img1$src"]!=undefined)||(pagesT[i]["cover"]!=null && pagesT[i]["cover"]!=undefined)){//build cover slideShow array
					cover = (pagesT[i]["cover"]==null)?"img1$src":"cover";
					coverSlideShowT[countslideIndex] = {"src" : pagesT[i][cover] , "title" : pageTtl };
					addFbLog("has SlideShow img: "+countslideIndex+" : "+pageTtl);
					countslideIndex++;
				}
				countIndex++;
			}
		}
	}
	if($("archiveRight")!=null){
		countArchive=0;
		$("archiveRight").innerHTML = '';
		for(i=magT.length-1 ; i > 0 ; i--){
			magTtl = magT[i]; 
			if(magTtl !=""){
				pos = (countArchive * 31);
				selected = (i==magT.length-1)?"menuSelected":"";
				$("archiveRight").innerHTML = '<a style="position:absolute;top:'+pos+'px;right:5px;" id="indexLink'+countArchive+'" class="menu '+selected+'" href="javascript:LoadMag('+i+')" > '+magTtl+'</a>'+$("archiveRight").innerHTML;
				countArchive++;
			}
		}
	}
	/*if(!isAdmin && $("menuLeft").style.display == "none")
		new Effect.toggle('menuLeft', 'appear');*/
}
function selectIndex(){//link navigation and index highlighting
	for(i=0 ; i < magIndex.length ; i++){
		from = magIndex[i].from;
		to = magIndex[i].to;
		if(activePage >= from && activePage < to)
			$("indexLink"+(i)).className = "menuSelected";
		else if($("indexLink"+(i))!=null)
			$("indexLink"+(i)).className = "menu";
	}
}
function LoadScript(url,func,destId){//JSONP 
	addFbLog("LoadScript getting : "+url);
	if(destId!="" && destId!=null && destId!="swappingSection")
		$(destId).update('Work in process <br/><img src="style/images/loader3.gif" width="50px"/><br/>Please be patient.');
	var head = document.getElementsByTagName('head')[0];
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = url;
	if(func != null){
		if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
		  // IE
		  script.onreadystatechange = function(){ if (this.readyState == 'loaded') { func(); } }
		} else {
		  // Other browsers
		  script.onload = func;
		}
	}
	head.appendChild(script);
}
//keyboard navigation 
function enableKeyboardNavMag() { document.observe('keydown', keyboardActionMag); }
function disableKeyboardNavMag() { document.stopObserving('keydown', keyboardActionMag); }
function keyboardActionMag(event) {
	var keycode = event.keyCode;
	var escapeKey = (event.DOM_VK_ESCAPE) ? event.DOM_VK_ESCAPE :escapeKey = 27;
	var key = String.fromCharCode(keycode).toLowerCase();
	if ( keycode == 37)pageTurn(-1);
	else if ( keycode == 39)pageTurn(1);
}
//Real simple History from :http://code.google.com/p/reallysimplehistory
window.dhtmlHistory.create({toJSON: function(o) {return Object.toJSON(o);}, fromJSON: function(s) {return s.evalJSON();}});
var yourListener = function(newLocation, historyData) {
	var historyMsg = (typeof historyData == "object" && historyData != null) ? historyStorage.toJSON(historyData) : historyData;
	if(newLocation.indexOf("xxx")>=0){
	activeMag = newLocation.substring(0,newLocation.indexOf("xxx"));
	activePage = newLocation.substring(newLocation.indexOf("xxx")+3,newLocation.length);
	}else {
	activeMag = newLocation.substring(0,newLocation.indexOf("mag"));
	activePage = newLocation.substring(newLocation.indexOf("mag")+3,newLocation.length);
	}
	addFbLog("yourListener : mag:"+activeMag+" page:"+activePage+" from "+newLocation);
	if(activeMag.indexOf(".js")>=0)
		LoadMag(activeMag,Number(activePage),true);
	else 
		LoadMag(Number(activeMag),Number(activePage));
}
loadedMag = false;
var historyData = {};
window.onload = function (){
	if(!isIE)buildDynamicDecoration(10);
	if((document.URL).indexOf("admin.html")>=0)
		isAdmin = true;
	addFbLog(screen.width);
	dhtmlHistory.initialize();//Real Simple History browser Back Forth Button
    dhtmlHistory.addListener(yourListener);
	enableKeyboardNavMag();//keyboard access
	hash = window.location.hash;
	if(!loadedMag){
	//reloads a page by the hash key
		if(hash != null && hash!= ""){
			if(hash.indexOf("xxx")>=0){
				activeMag = hash.substring(1,hash.indexOf("xxx"));
				activePage = hash.substring(hash.indexOf("xxx")+3,hash.length);
			} else {
				activeMag = hash.substring(1,hash.indexOf("mag"));
				activePage = hash.substring(hash.indexOf("mag")+3,hash.length);
			}
			addFbLog("onload : mag:"+activeMag+" page:"+activePage);
			if(activeMag!="" && activeMag!=null && activePage!="" && activePage!=null){
				if(activeMag.indexOf(".js")>=0)
					LoadMag(activeMag,Number(activePage),true);
				else 
					LoadMag(Number(activeMag),Number(activePage));
			}
		} 
		if(!loadedMag)
			LoadMag(0);
	}
};
var preloadElemT = ["images/loading.gif","style/images/loader3.gif","images/prevlabelgrey.png","images/homelabelgrey.png","images/nextlabelgrey.png"];
function ListPreLoadElements(page){
	index = page+1;
	if(index > pagesT.length) 
		index = null;
	addFbLog("ListPreLoadElements :: "+index);
	if(index != null){
		for(p in pagesT[index]){addFbLog(p);
			if(p.indexOf("$src")>=0)
				preloadElemT.push(pagesT[index][p]);
		}
		preLoadElements(preloadElemT);
	}
}
preload_image = new Image(); 
function preLoadElements(elemT,path){addFbLog("preLoadElements :: ");
	imgPath = (path != null) ? path : "";
	while(elemT.length>0) {
		elem = preloadElemT[0];
		if( typeof elem == "object")//elemT can contain String or Objects src,title
			elem = elem.src;
		if(elem!=null && elem!=""){
			preload_image.src=imgPath+elem;
			addFbLog("preLoadElements :: "+preloadElemT[0]);
		}			
		preloadElemT.shift();
	}
}
function showNextSlide(imgStr){//Slide show engine :: Array of objects src + title
	if(slideShowTimer!=null){
		slideShowIndex = (slideShowIndex==slideShowT.length-1) ? 0: slideShowIndex+1;	
		src = slideShowT[slideShowIndex].src;
		title = slideShowT[slideShowIndex].title;
		if(slideShowT[slideShowIndex].src!="undefined"){
			src = slideShowPath+src;
			var imgPreloader = new Image();
			imgPreloader.onload=function(){
				if(slideShowTimer!=null){
					$(imgStr).src = imgPreloader.src;
					if($("imgTitle")!=null)
						$("imgTitle").innerHTML = title;
					else
						new Insertion.After(imgStr, ' <br/><span style="padding:0 25px 0 25px;font-weight:bold; font-size:large;padding:10px;background-color:white;color:black;" id="imgTitle">test '+title+"</span>");
				}
			}
			imgPreloader.src = src;
		}
	}else
		resetSlideShow();
}
function resetSlideShow(){
if(slideShowTimer != null){
		slideShowTimer.stop();slideShowTimer = null;slideShowT = null;slideShowPath = null;slideShowIndex = 0;
	}
}
function buildDynamicDecoration(count){
	top = 0;
	right = 0;
	width = 0;
	height=0
	color = 0;
	for(ix=0; ix < count; ix++)
	{
		p = getDecoParam();
		top = p.t;
		right = p.r;
		width = p.w;
		height=p.h;
		color = p.c;
		$('rightDeco').innerHTML = $('rightDeco').innerHTML + '<div id="deco'+ix+'" style="position:absolute; top:'+top+'px; right:'+right+'px;width:'+width+'px;height:'+height+'px;border:2px solid #333; -moz-border-radius: 1em;background-color:'+color+';"></div>';
	}
	startDeco(0);
}

function startDeco(ix){
	ix = (ix > 9)?0:ix;
	p = getDecoParam();
	//addFbLog("startDeco :"+ix+", top :"+p.t+", right:"+p.r);
	new Effect.Parallel([
        new Effect.Move('deco'+ix, { sync: true, x: -120-p.r, y: p.t, mode: 'absolute' }), 
        new Effect.Morph('deco'+ix, {style: { width: p.w+"px", height: p.h+"px",backgroundColor:p.c }, sync: true})
     ], {duration: 2});
	ix++;
	setTimeout("startDeco("+ix+")",2000);
}
function getDecoParam(){
	var p = new Object();
	p.t = randomXToY(0,600);
	p.r = randomXToY(0,90);
	p.w = randomXToY(10,190);
	p.h=randomXToY(20,300);
	p.c = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
	return p;
}
//function to get random number upto m
function randomXToY(minVal,maxVal,floatVal)
{
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}