//general -> see general.js for: gbid(), clearVar(), getHighestDepth()

////////////////////////////////
//------------------------------CONFIG
////////////////////////////////

//defined in the doc body
//var gridOffsetY = <?php echo $offsetY; ?>;
//var highestDepth = <?php echo count($blocks)+1; ?>;
//var lastHighestDepth = highestDepth;
//var mapRatio = <?php echo $mapRatio; ?>;
//var mapOffset = <?php echo $mapOffset; ?>;

//document
var docSize = new Array();

//grid
var selectedBlocks = new Array();

//menu setup
var menucomments = new Array('','open','close');

//map setup
var mapmenuopen=false;

//cat actions
var catmenuopen=false;
var catitemcomments = new Array('','pick','selected','unpick');
var selectedItems = new Array();
var catSelectionMode = "OR"; //can be set to 'OR' or 'AND' -> influence the items displayed

//floating pages
var fpagetime=0;
var fpages = new Array();
//to replace: ID and TITLE
var contentFpage = '<div class="menuItem floatingPageClose" onclick="removeFloatingPage(this.offsetParent.id)"></div><div class="floatingPageTitle"><h1>TITLE</h1></div><div class="floatingPageContent" id="IDContent"></div>';
//reminder of the last page request
var lastFpageRequest=null;
var fpageWidth = 300;
var fpagePosTolerance = -30;
var fpageBorderTolerance = 30;
var fpageBorderMin = 20;
var fpagecomments = new Array('','','close all');
var cellMarkerMargins = new Array(1,0,0,1);


//gallery
var galleryLoadingMessage = 'the gallery is loading';

//animation
var headerSpeed = 5;
var headerX=0;
var headerXtarget = 0;


////////////////////////////////
//------------------------------DOCUMENT VALUES
////////////////////////////////
function getDocumentSize() { if(!docSize.w) { docSize.w=gbid('gridRoot').clientWidth; docSize.h=document.body.clientHeight; } }


////////////////////////////////
//------------------------------GRID
////////////////////////////////
//grid actions
function adaptGridPosition() {
	var ntop = (Math.floor(document.body.clientHeight-clearVar(gbid('gridRoot').style.height))/2)-gridOffsetY;
	if (ntop<0) { ntop=0; }
	gbid('gridRoot').style.top = ntop+'px';
}
function showComment(show,id) {
	if (gbid('CommentBox'+id).style.zIndex!=highestDepth) { gbid('CommentBox'+id).style.zIndex=highestDepth; }
	if (show) { gbid('CommentBox'+id).style.display = 'block'; }
	else if (!show) { gbid('CommentBox'+id).style.display = 'none'; }
}
function appendClass(o,classn,add) {
	if (add) { if (o.className.indexOf(classn)==-1) { o.className+=' '+classn; } }
	else if (!add) {
		var tmpclass = o.className;
		if (tmpclass.indexOf(classn)>-1) { tmpclass = tmpclass.substring(0, tmpclass.indexOf(classn)) + tmpclass.substring(tmpclass.indexOf(classn)+classn.length, tmpclass.length); }
		o.className = tmpclass;
	}
}
function selectBlocksOnCat(cat,select) {
	var allBlocks = gbid('grid').getElementsByTagName('div');
	var results = 0;
	for(var i=0; i<allBlocks.length; i++) {
		//only Box+id are concerned
		if (allBlocks[i].id.indexOf('Box')==0) {
		//selection of a cat
			if((select)&&(cat.length>0)) {
				var allInputs = allBlocks[i].getElementsByTagName('input');
				var found = false;
				for(var u=0; u<allInputs.length; u++) { if (allInputs[u].value==cat) { found = true; break; } }
				//only 1 cat selected => the current blocks is set to hidden
				if ((!found)&&(selectedItems.length==1)) { appendClass(allBlocks[i],'BoxHidden',true); }
				//at least 2 cat already selected => unhide all linked blocks
				else if ((found)&&(selectedItems.length>1)) { appendClass(allBlocks[i],'BoxHidden',false); }
		//deselection of a cat
			} else if((!select)&&(cat.length>0)) {
				//there was only one cat selected => = click on "none"
				if (selectedItems.length<1) { appendClass(allBlocks[i],'BoxHidden',false); }
				//there is other cats selected => check if the blocks are linked to other cats
				else {
					var allCatsIds = '';
					for (var item=0; item<selectedItems.length; item++) { allCatsIds+="|"+selectedItems[item].getElementsByTagName('input')[0].value+"|"; }
					var allInputs = allBlocks[i].getElementsByTagName('input');
					var found = false;
					for(var u=0; u<allInputs.length; u++) {
						if (allCatsIds.indexOf('|'+allInputs[u].value+'|')>-1) {
							found = true;
							break;
						}
					}
					if (found) { appendClass(allBlocks[i],'BoxHidden',false); }
					else { appendClass(allBlocks[i],'BoxHidden',true); }
				}
		//click on "none"
			} else if((!select)&&(cat=='')) {
				appendClass(allBlocks[i],'BoxHidden',false);
			}
		//counting results, and in the same time adapting the map
			if (allBlocks[i].className.indexOf('BoxHidden')==-1) {
				results++;
				appendClass(gbid('mapBox'+allBlocks[i].id.substring(allBlocks[i].id.indexOf('Box')+3,allBlocks[i].id.length)),'mapBoxHidden',false);
			} else {
				appendClass(gbid('mapBox'+allBlocks[i].id.substring(allBlocks[i].id.indexOf('Box')+3,allBlocks[i].id.length)),'mapBoxHidden',true);
			}
		}
	}
	var str = results+" results"; if (results==1) { str = results+" result"; } else if (results==0) { str="no results..."; }
	gbid('catSearchResults').innerHTML = str;
}


////////////////////////////////
//------------------------------MENUS
////////////////////////////////
function addMenuComment(add,id,condition) {
	if (add) {
		if (condition) { gbid(id).innerHTML = menucomments[2]; }
		else { gbid(id).innerHTML = menucomments[1]; }
	} else { gbid(id).innerHTML = menucomments[0]; } }


////////////////////////////////
//------------------------------CATS
////////////////////////////////

//cat menu actions
function showCatMenu() {
	if (catmenuopen) {
		gbid('catList').style.display='none';
		catmenuopen = false;
		addMenuComment(true,'catButtonComment',catmenuopen);
		if(selectedItems.length>0) {
			var allCatsName = '';
			for (var item=0; item<selectedItems.length; item++) { if (allCatsName.length>0) { allCatsName+=","; } allCatsName+=" <b>"+selectedItems[item].getElementsByTagName('b')[0].innerHTML+"</b>"; }
			gbid('catReminderContent').innerHTML = 'selected:'+allCatsName;
			gbid('catReminder').style.display='block';
		}
	} else {
		gbid('catButtonComment').innerHTML = menucomments[2];
		gbid('catList').style.display='block';
		gbid('catReminder').style.display='none';
		if (gbid('catList').style.zIndex<lastHighestDepth) { gbid('catList').style.zIndex=getHighestDepth(); }
		catmenuopen = true;
		addMenuComment(true,'catButtonComment',catmenuopen);
	} }

//cat reminder
function showCatReminder(show) {
	if (show) { gbid('catReminder').style.zIndex = highestDepth+1; }
	else { gbid('catReminder').style.zIndex = 0; }
}

//cat items actions
function addCatItemComment(o,status,add) {
	//depending on the action and the actual content of the comment, the content is adapted
	if((add)&&(status=='over')&&(o.getElementsByTagName('span')[0].innerHTML==catitemcomments[0])) { o.getElementsByTagName('span')[0].innerHTML = catitemcomments[1];}
	else if((add)&&(status=='over')&&(o.getElementsByTagName('span')[0].innerHTML==catitemcomments[2])) { o.getElementsByTagName('span')[0].innerHTML = catitemcomments[3];}
	else if ((!add)&&(status=='over')&&(o.getElementsByTagName('span')[0].innerHTML==catitemcomments[1])) {o.getElementsByTagName('span')[0].innerHTML = catitemcomments[0];}
	else if ((!add)&&(status=='over')&&(o.getElementsByTagName('span')[0].innerHTML==catitemcomments[3])) {o.getElementsByTagName('span')[0].innerHTML = catitemcomments[2];}
	else if ((add)&&(status=='select')) {o.getElementsByTagName('span')[0].innerHTML = catitemcomments[3];}
	else if ((!add)&&(status=='select')) {o.getElementsByTagName('span')[0].innerHTML = catitemcomments[0];}
	else if ((!add)&&(status=='select+over')) {o.getElementsByTagName('span')[0].innerHTML = catitemcomments[1];} }

function setCatSelection(o,val) {
	if (catSelectionMode!=val) { catSelectionMode = val; }
	alert(catSelectionMode);
}

function selectCatItem(o) {
	var found=false;
	for (var i=0; i<selectedItems.length; i++) { if (selectedItems[i]==o) { found=true; break; } }
	if (!found) {
		appendClass(o,'catListItemSelected',true);
		addCatItemComment(o,'select',true);
		selectedItems[selectedItems.length] = o;
		selectBlocksOnCat(o.getElementsByTagName('input')[0].value,true);
	} else {
		appendClass(o,'catListItemSelected',false);
		addCatItemComment(o,'select+over',false);
		newselectedItems = new Array();
		for (var i=0; i<selectedItems.length; i++) { if (selectedItems[i]!=o) { newselectedItems.push(selectedItems[i]); } }
		selectedItems = newselectedItems;
		delete newselectedItems;
		selectBlocksOnCat(o.getElementsByTagName('input')[0].value,false);
	} }

function showAllCats() {
	for (var i=0; i<selectedItems.length; i++) { 
		appendClass(selectedItems[i],'catListItemSelected',false);
		addCatItemComment(selectedItems[i],'select',false);
	}
	selectedItems = new Array();
	selectBlocksOnCat('',false); }


////////////////////////////////
//------------------------------MAP
////////////////////////////////
//map actions
function showMap() {
	if (mapmenuopen) {
		gbid('mapContent').style.display = 'none';
		mapmenuopen=false;
		addMenuComment(true,'mapButtonComment',mapmenuopen);
	} else {
		gbid('mapContent').style.display = 'block';
		if (gbid('mapContent').style.zIndex<lastHighestDepth) { 
			gbid('mapContent').style.zIndex=getHighestDepth();
			gbid('mapWindow').style.width=(Math.ceil(document.body.clientWidth*mapRatio)-2)+'px';
			gbid('mapWindow').style.left=(mapOffset+Math.ceil(document.body.scrollLeft*mapRatio))+'px';
			verifyMapPosition();
		}
		mapmenuopen=true;
		addMenuComment(true,'mapButtonComment',mapmenuopen);
	}
}
function verifyMapPosition() {
	if(clearVar(gbid('mapBg').style.width)+480+mapOffset>document.body.clientWidth) {
		var nleft = document.body.clientWidth-(clearVar(gbid('mapBg').style.width)+480+mapOffset);
		gbid('mapContent').style.left = nleft+'px';
	} else if(clearVar(gbid('mapContent').style.left)!=0) {
		gbid('mapContent').style.left='0px';
	}
}
function mapJumpTo(left,top,width,height) {
	var midwinwidth = Math.floor(document.body.clientWidth*0.5);
		midwinwidth -= Math.floor(width*0.5);
	document.body.scrollLeft = left-midwinwidth;
	if (gbid('cellMarker').style.display!='block') { gbid('cellMarker').style.display='block'; }
	gbid('cellMarker').style.top = (top+cellMarkerMargins[0])+'px';
	gbid('cellMarker').style.left = (left+cellMarkerMargins[3])+'px';
	//gbid('cellMarker').style.height = height+'px';
}


////////////////////////////////
//------------------------------FLOATING PAGES
////////////////////////////////

//GENERIC actions
function addFloatingPage(id) {
	var nfp = new Array();
		nfp.id = id;
		nfp.active = false;
		nfp.loaded = true;
		nfp.open = true;
		nfp.src = null;
		nfp.title = null;
		nfp.content = null;
		nfp.time = -1;
		fpages.push(nfp);
}
function searchFloatingPage(id) {
	var out = null;
	for(var i=0; i<fpages.length;i++) { if(fpages[i].id==id) { out=fpages[i]; break; } }
	return out;
}
function getFloatingPageContentO(id) {
	var out=null;
	var divs=gbid(id).getElementsByTagName('div');
	for(var i=0; i<divs.length; i++) { if(divs[i].className.indexOf('Content')>-1) { out=divs[i]; break; } }
	return out;
}
function getFloatingPageTitleO(id) {
	var out=null;
	var divs=gbid(id).getElementsByTagName('h1');
	if(divs.length>0) { out=divs[0]; }
	return out;
}
function getFloatingPageStatus(id,satus) { return searchFloatingPage(id)[satus]; }
function checkFP(o) { var out=false; for(var i=0; i<fpages.length;i++) { if(fpages[i]==o) { out=true; break; } } return out; }
//search of a free fpage
function searchFreeFloatingPage() {
	var fp = null;
	var found=false;
//it's possible that the page has already been loaded => the fpage just have to be displayed
	for(var i=0; i<fpages.length; i++) { if(fpages[i].src==lastFpageRequest) { fp = fpages[i]; found=true; break; } }
//if the user click on a link before the conten is loaded => the fpage can be reused
	for(var i=0; i<fpages.length; i++) { if(!fpages[i].loaded) { fp = fpages[i]; found=true; break; } }
//all pages are loaded, so seeking a non-active fpage
	if (!found) {
	for(var i=0; i<fpages.length; i++) { if(!fpages[i].active) { fp = fpages[i]; found=true; break; } } }
//all fpages are displayed => seek the oldest one
	if (!found) { var olderfp=fpagetime; for(var i=0; i<fpages.length; i++) { if(fpages[i].time<olderfp) { olderfp=fpages[i].time; fp=fpages[i]; } } }
	return fp;
}
//calculate the position of the fpage
function setFloatingPagePos(fp,x,y) {
	y+=clearVar(gbid('gridRoot').style.top)+Math.floor(Math.random()*fpagePosTolerance);
	x+=Math.floor(Math.random()*fpagePosTolerance);
	gbid(fp.id).style.left=x+'px';
	gbid(fp.id).style.top=y+'px';
	verifyFloatingPagePos(fp,'xy');
}
function verifyFloatingPagePos(fp,axis) {
	//this function verify that the bottom of the fpage is too low regarding the grid pos
	var borderMax = fpageBorderMin+fpageBorderTolerance;
	if (axis.indexOf('y')>-1) {
		var fmax = clearVar(gbid(fp.id).style.top)+gbid(fp.id).clientHeight;
		if ((fmax+borderMax)>docSize.h) { 
			var yval = docSize.h-(gbid(fp.id).clientHeight+(fpageBorderMin+Math.round(Math.random()*fpageBorderTolerance)));
			if (yval<gridOffsetY) { yval=gridOffsetY; }
			gbid(fp.id).style.top = yval+'px';
		} else if (clearVar(gbid(fp.id).style.top)<gridOffsetY) {
			gbid(fp.id).style.top = gridOffsetY+'px';
		}
	}
	if (axis.indexOf('x')>-1) {
		var xval = clearVar(gbid(fp.id).style.left);		
		if(xval<document.body.scrollLeft) { xval+=(document.body.scrollLeft-xval)+(fpageBorderMin+Math.round(Math.random()*fpageBorderTolerance)); }
		else if((xval+fpageWidth)>docSize.w) { xval = docSize.w-(fpageWidth+(fpageBorderMin+Math.round(Math.random()*fpageBorderTolerance))); }
		else if((xval+fpageWidth)>(document.body.clientWidth+document.body.scrollLeft)) { xval = (document.body.clientWidth+document.body.scrollLeft)-(fpageWidth+(fpageBorderMin+Math.round(Math.random()*fpageBorderTolerance))); }
		gbid(fp.id).style.left = xval+'px';
	}
}

function checkCloseAllDisplay() {
	var smtActive = false;
	for(var i=0; i<fpages.length; i++) { if(fpages[i].active) { smtActive = true; break; }}
	if(smtActive&&(gbid('fpages').style.display!='block')) { gbid('fpages').style.display='block'; }
	else if ((!smtActive)&&(gbid('fpages').style.display!='none')) { gbid('fpages').style.display='none'; }
}

//INTERACTIVE actions
function putAboveFloatingPage(o) { if(o.style.zIndex!=lastHighestDepth) { o.style.zIndex=getHighestDepth(); } }
function openFloatingPage(o) {
	var fp = null;
	if(checkFP(o)) { fp=o; }
	else { fp = searchFloatingPage(o.offsetParent.id); }
	if(fp.content==null) { fp.content = getFloatingPageContentO(fp.id); }
	if(fp.title==null) { fp.title = getFloatingPageTitleO(fp.id); }
	if(fp.open) {
		fp.open=false;
		fp.content.style.display='none';
	} else {
		fp.open=true;
		fp.content.style.display='block';
	}
}
function removeFloatingPage(id) {
	searchFloatingPage(id)['active']=false;
	gbid(id).style.display='none';
	checkCloseAllDisplay();
}
function closeAllFpages() {
	for(var i=0; i<fpages.length; i++) { 
		if(fpages[i].active) {
			searchFloatingPage(fpages[i].id)['active']=false;
			gbid(fpages[i].id).style.display='none';
		}
	}
	//hide the menu 'close all'
	gbid('fpages').style.display='none';
}
function addFpagesComment(add,id) {
	if (add) { gbid(id).innerHTML = fpagecomments[2]; }
	 else { gbid(id).innerHTML = fpagecomments[0]; } }

//CONTENT actions
//preparation of a fpage for display
function displayFloatingPage(fp) {
	fp.active=true;
	fp.loaded=false;
	fp.src = null;
//this set the last updated fpage
	fpagetime++;
	fp.time=fpagetime;
//if the fpage is empty -> placemnt of the standard content
	if (gbid(fp.id).innerHTML=='') {
		var tcontent = contentFpage;
			while(tcontent.indexOf('ID')>-1) { tcontent=tcontent.substring(0,tcontent.indexOf('ID'))+fp.id+tcontent.substring(tcontent.indexOf('ID')+2,tcontent.length); }
			while(tcontent.indexOf('TITLE')>-1) { tcontent=tcontent.substring(0,tcontent.indexOf('TITLE'))+'loading'+tcontent.substring(tcontent.indexOf('TITLE')+5,tcontent.length); }
		gbid(fp.id).innerHTML = tcontent;
		fp.content=getFloatingPageContentO(fp.id);
	}
	if(fp.content==null) { fp.content = getFloatingPageContentO(fp.id); }
	if(fp.title==null) { fp.title = getFloatingPageTitleO(fp.id); }
	fp.title.innerHTML='Loading';
	fp.content.innerHTML='please wait';
//if the content has been hide before removing the fpage
	if(!fp.open) { openFloatingPage(fp); }
	gbid(fp.id).style.display='block';
	putAboveFloatingPage(gbid(fp.id));
	checkCloseAllDisplay();
}
//this function is called at the same time a page request is sent
function loadPage(request,posx,posy) {
	//on first loading, storage of the total width of the screen
	getDocumentSize();
	lastFpageRequest=request;
	var fp = searchFreeFloatingPage();
	setFloatingPagePos(fp,posx,posy);
	if(fp.src==lastFpageRequest) {
		if(!fp.active) { gbid(fp.id).style.display='block'; }
		if(!fp.open) { openFloatingPage(fp); }
		putAboveFloatingPage(gbid(fp.id));
	} else { displayFloatingPage(fp); }
	checkCloseAllDisplay();
}

//this function is called when the iframe as finished loading
function placeContent(title,content) {
	var fp = searchFreeFloatingPage();
	if(fp.content==null) { fp.content = getFloatingPageContentO(fp.id); }
	if(fp.title==null) { fp.title = getFloatingPageTitleO(fp.id); }
	if(!fp.active) { gbid(fp.id).style.display='block'; putAboveFloatingPage(gbid(fp.id)); }
	if(!fp.open) { openFloatingPage(fp); }
	if(!(fp.src==lastFpageRequest)) {
		fp.src = lastFpageRequest;
		fp.title.innerHTML = title.innerHTML;
		fp.content.innerHTML = content.innerHTML;
	}
	fp.loaded=true;
	putAboveFloatingPage(gbid(fp.id));
	verifyFloatingPagePos(fp,'y');
	checkCloseAllDisplay();
}

//this function is called when the iframe that loads a page (request from an opened fpage for instance) as finished loading
function placePageContent(request,title,content) {
	loadPage(request,document.body.scrollLeft+150,150);
	placeContent(title,content);
	checkCloseAllDisplay();
}


////////////////////////////////
//------------------------------GALLERY
////////////////////////////////

var galleryOpen = false;
function showGallery() {
	if(galleryOpen) {
		gbid('gallery').style.display='none';
		galleryOpen = false;
	} else {
		gbid('gallery').style.display='block';
		galleryOpen = true;
		adaptGallerySize();
	}
}
function adaptGallerySize() {
	if (galleryOpen) {
		gbid('gallery').style.height = document.body.clientHeight;
		gbid('galleryContentWrapper').style.left = document.body.scrollLeft;
		gbid('galleryContentWrapper').style.height = document.body.clientHeight;
		gbid('galleryContentWrapper').style.width = document.body.clientWidth;
	}
}
function placeGalleryContent(title,content) {
	if(!galleryOpen) { showGallery(); }
	galleryLoading(false);
	gbid('galleryTitle').innerHTML = title.innerHTML;
	gbid('galleryContent').innerHTML = content.innerHTML;
}
function galleryLoading(val) {
	if (val) { gbid('generalMessage').innerHTML=galleryLoadingMessage; gbid('generalMessage').style.display='block'; }
	else { gbid('generalMessage').innerHTML=''; gbid('generalMessage').style.display='none'; }
}
function galleryDisplayBig(id) {
	gbid('BigImage').src=gbid('galleryPath'+id).value;
	gbid('BigComment').innerHTML=gbid('galleryComment'+id).value;
	gbid('BigImageID').value = id;
}
function galleryDisplayNext() {
	var nextImg = parseInt(gbid('BigImageID').value);
	if((nextImg+1)<=parseInt(gbid('numOfThumbs').value)) { nextImg++; }
	else { nextImg=0; }
	galleryDisplayBig(nextImg);
}

////////////////////////////////
//------------------------------ANIMATION
////////////////////////////////

function animHeaderPos() {
	if(headerX!=headerXtarget) { 
		headerX+=Math.ceil((headerXtarget-headerX)/headerSpeed);
		gbid('header').style.left = headerX+'px';
	}
}
//anim main
function anim() {
	animHeaderPos();
}


////////////////////////////////
//------------------------------WINDOW
////////////////////////////////
//window actions
window.onscroll = function() { 
	headerXtarget = Math.abs(document.body.scrollLeft);
	gbid('mapWindow').style.left=mapOffset+Math.ceil(document.body.scrollLeft*mapRatio);
	adaptGallerySize();
}
window.onresize = function() {
	getDocumentSize();
	adaptGridPosition();
	gbid('mapWindow').style.width=Math.ceil(document.body.clientWidth*mapRatio)-2;
	verifyMapPosition();
	adaptGallerySize();
}
window.setInterval('anim()',30);