var mouseCoord = { 'x':0, 'y':0 };
var coordDivOrg = {'x':0, 'y':0 };
var categories = new Array(); // liste des categories
var centerContent = new Array(475,300);
var gLevel = 0;
var categoriesPosition = new Array();
var categoriesDimensions = new Array();
var isZoomDown = false;
var listCategoriesShow = new Array();
var LEVEL_MAX = 3;
var activeMove = true;
var activeZoom = true;

displayDescription = function( e, categorieNameId )
{
	var event = getEvent(e);
	var offset = $('zoomBox').cumulativeOffset();
	var width = parseInt($('description_'+categorieNameId).style.width);
	if( isExplorer() ){
		$('description_'+categorieNameId).style.top = '25px'; 
		$('description_'+categorieNameId).style.left = Math.round(width/4);
	}
	else{
		$('description_'+categorieNameId).style.top= event.clientY-offset[1]+5; 
		$('description_'+categorieNameId).style.left = event.clientX-offset[0]-Math.round(width/2);
	}
	
	
	$('description_'+categorieNameId).style.display = 'block';
}

hiddenDescription = function( ev, categorieNameId )
{
	$('description_'+categorieNameId).style.display = 'none';
}

isExplorer = function()
{
	if( navigator.appName.indexOf("Explorer") > -1 ){
		return true;
	}
	return false;
}

overBox = function( categorieNameId )
{
	$('box_'+categorieNameId).className =  'box overMouse';
}

outBox = function( categorieNameId )
{
	$('box_'+categorieNameId).className =  'box outMouse';
}

getEvent = function( event )
{
    if( typeof(event) == 'undefined' ){
        return window.event;
    }
    return event;
}

addEvent = function( _this, e )
{
	if( typeof(mouseMove) == 'function' && typeof(getEvent) == 'function')
	{
		if( activeZoom && activeMove )
		{
			_this.onmousemove = mouseMove;
			
			var event = getEvent(e);
			mouseCoord.x = event.clientX;
			mouseCoord.y = event.clientY;
		}
	}
}

mouseMove = function( e )
{
	if( typeof(getEvent) == 'function' )
	{
		var event = getEvent(e);
		var top=0;
		var left=0;
		if( mouseCoord.x != 0 && mouseCoord.y != 0 )
		{
			top = parseInt($('move').style.top);
			left = parseInt($('move').style.left);
			var diff_x = mouseCoord.x - event.clientX;
			var diff_y = mouseCoord.y - event.clientY; 
			top -= diff_y;
			left -= diff_x;
			
		}
		$('zoomBox').style.top  = parseInt($('zoomBox').style.top) + top + 'px';
		$('zoomBox').style.left = parseInt($('zoomBox').style.left) + left + 'px';
		mouseCoord.x = event.clientX;
		mouseCoord.y = event.clientY;
	}
}

releaseMouse = function()
{
	$('move').onmousemove=null;
	coordDivOrg.x = $('zoomBox').style.left;	
	coordDivOrg.y = $('zoomBox').style.top;
}

createCategorie = function( categorieName, infos, level )
{
	var categorieNameId = infos.categorieId.toString();
	var parentId = infos.parentId.toString();
	
	// creer le bloque de la categorie
	newDiv = document.createElement('div');
	newDiv.setAttribute('id', 'box_'+categorieNameId);
	
	// define css text
	// on affiche pas les sous categories à sa creation (pour un effet progessif)
	var cssText = 'width:'+infos.width+';height:'+infos.height+';';
	if( level == (gLevel+1) && level > 0 && !isZoomDown ) cssText += 'display:none;';
	
	// define class name
	var className = 'box outMouse';
		
	// set les attributes style et class selon le navigateur
	if( isExplorer() )
	{
		newDiv.setAttribute('className',className);
		newDiv.style.setAttribute('cssText',cssText);
	}
	else // autre
	{
		newDiv.setAttribute('class',className);
		newDiv.setAttribute('style',cssText);
	}
	
	// set les evenement over,out et click
	newDiv.onmouseover = function(){if(typeof(overBox)=='function')overBox(categorieNameId);};
	newDiv.onmouseout = function(){if(typeof(outBox)=='function')outBox(categorieNameId);}
	newDiv.ondblclick = function(e){if(typeof(selectBox)=='function')selectBox(e,categorieNameId);};
	
	
	// vérifie le parent
	if( infos.parentId == 0 ){
		$('zoomBox').appendChild(newDiv);
	}
	else{ // si le parent n'est pas le bloque principale
		$(parentId).appendChild(newDiv);
	}
	
	// récupération du texte des bloques selon le niveau de zoom
	var resume = '';
	var description = '';
	var content = '';
	if( infos.resumeLevel == gLevel && infos.resume != '' )
	{
		resume = ': '+infos.resume;
	}
	if( infos.descriptionLevel == gLevel && infos.description != '' ) 
	{
		var widthDescripionDiv = $('box_'+categorieNameId).getWidth();
		if( isZoomDown ){
			var widthDescripionDiv = Math.round(widthDescripionDiv / 2);
		}
		resume = ' <img src="images/arrow_desc.png" border="0" onmouseover=\'displayDescription(event,\"'+categorieNameId+'\")\' onmouseout=\'hiddenDescription(event,\"'+categorieNameId+'\")\' />';
		description = '<div class="description" id="description_'+categorieNameId+'" style="left:0;top:0;width:'+widthDescripionDiv+'px">'+infos.description+'</div>';
	}
	if( infos.contentLevel <= gLevel && infos.content != '' ){
		content = infos.content;
	}
	
	// creer la barre de titre
	var newDivTitle = document.createElement('div');
	newDivTitle.setAttribute('id', 'title_'+categorieNameId);
	if( isExplorer() ) newDivTitle.setAttribute('className','box_title');
	else			   newDivTitle.setAttribute('class','box_title');
	newDivTitle.innerHTML = categorieName+resume+description;
	$('box_'+categorieNameId).appendChild(newDivTitle);
	
	// creer le contenu
	var newDivContent = document.createElement('div');
	newDivContent.setAttribute('id', categorieNameId);
	if( isExplorer() ) newDivContent.setAttribute('className','box_content');
	else			   newDivContent.setAttribute('class','box_content');
	if( level > gLevel ){
		if( isExplorer() ) newDivContent.setAttribute('cssText','filter:alpha(opacity=30);');
		else			   newDivContent.setAttribute('style','-moz-opacity:0.3;filter:alpha(opacity=30);')
	}
	
	if( content != ''){
		newDivContent.style.overflowY = 'scroll';
		newDivContent.style.fontSize = '0.4em';
		newDivContent.style.padding = '5px';
		newDivContent.innerHTML = content;
	}
	else
	{
		if( infos.content != '' ){
			newDivContent.innerHTML = infos.content;
			newDivContent.style.fontSize = '0.2em';
			$('box_'+categorieNameId).style.overflow = 'hidden';
			newDivContent.style.padding = '5px';
		}
	}
	$('box_'+categorieNameId).appendChild(newDivContent);
	if( gLevel < LEVEL_MAX )
	{
		var images = $$('#'+categorieNameId+' img');
		var nbImages = images.length;
		for( inc=0; inc<nbImages; inc++ )
		{
			images[inc].style.width = '10%';
			images[inc].style.height = '10%';
		}
	}
	if( content != '' ){
		var titleHeight = $('title_'+categorieNameId).getHeight();
		var boxHeight = $('box_'+categorieNameId).getHeight();
		var contentHeight = Math.round((boxHeight-titleHeight)*100/boxHeight)-2;
		$(categorieNameId).style.height = contentHeight+'%';
		Event.observe($(categorieNameId),'mouseover',function(){activeMove=false;activeZoom=false;});
		Event.observe($(categorieNameId),'mouseout',function(){activeMove=true;activeZoom=true;})
	}
	
	// creer une div clear
	var newDivClear = document.createElement('div');
	if( isExplorer() ) newDivClear.setAttribute('className','clear');
	else			   newDivClear.setAttribute('class','clear');
	$('box_'+categorieNameId).appendChild(newDivClear);
	
	// affiche un message d'infos lorsqu'on atteint le zoom max
	if( gLevel == LEVEL_MAX ){
		$('infoszoom').style.display = 'block';
	}
	else{
		$('infoszoom').style.display = 'none';
	}
	
	// ssi on zoom et que c'est une sous categorie
	// lance l'effet progessif pour l'affichage de la sous categorie
	if( level == (gLevel+1) && level > 0 && !isZoomDown ){
		new Effect.Appear( $('box_'+categorieNameId),{duration:3,from:0.3} );
	}
}

selectBox = function( e, _this )
{
	if( gLevel < LEVEL_MAX && activeZoom )
	{
		isZoomDown = false;
		var event = getEvent(e);
		mouseCoord.x = event.clientX;
		mouseCoord.y = event.clientY;
		++gLevel;
		showCategories(_this);
	}
}

zoomSelection = function( box )
{
	activeZoom = false;
	// calcul de placement
	new Effect.Scale( $('zoomBox'), 150, 
	{
		afterFinish:function()
		{
			activeZoom=true;
			var offset = box.cumulativeOffset();
			var boxDimensions = box.getDimensions();
			var left = centerContent[0] - offset[0] - Math.round(boxDimensions.width/2);
			var top = centerContent[1] - offset[1] - Math.round(boxDimensions.height/2);
			new Effect.Move( $('zoomBox'), {x:left,y:top});
		}
	});
	

}

showCategories = function( categorieSelectionned )
{
	// supression des categories principales
	while( $('zoomBox').hasChildNodes() )
	{
		// sauvegarde la position
		categoriesPosition[$('zoomBox').firstChild.id] = new Object();
		categoriesPosition[$('zoomBox').firstChild.id].x = parseInt($('zoomBox').firstChild.style.left);
		categoriesPosition[$('zoomBox').firstChild.id].y = parseInt($('zoomBox').firstChild.style.top);
		
		//sauvegarde la taille
		categoriesDimensions[$('zoomBox').firstChild.id] = $($('zoomBox').firstChild.id).getDimensions();
			
		// supprime la categorie
		$('zoomBox').removeChild( $('zoomBox').firstChild );
	}
		
	// création des categories
	var incLevel = 0;
	listCategoriesShow = new Array();
	for( incLevel; incLevel <= categories.length; incLevel ++ )
	{
		if( typeof(categories[incLevel]) != 'undefined' )
		{
			var nbCategories = categories[incLevel].length;
			var incCategorie = 0;
			for( incCategorie; incCategorie < nbCategories; incCategorie++ )
			{
				// nom de la categorie
				var categorieName = categories[incLevel][incCategorie];
				var infos = categories[incLevel][categorieName];
				listCategoriesShow.push(categorieName);
				createCategorie( categorieName, infos, incLevel );
			}
		}
	}
	// zoom sur la boite selectionnée
	if( typeof(categorieSelectionned) != 'undefined' ) zoomSelection( $('box_'+categorieSelectionned) );
}

insertCategorie = function( categorie )
{
	if( typeof(categories[categorie.level]) == 'undefined' ) categories[categorie.level] = new Array();
	categories[categorie.level].push(categorie.name);
	categories[categorie.level][categorie.name] = new Object();
	categories[categorie.level][categorie.name].categorieId = categorie.categorieId;
	categories[categorie.level][categorie.name].parentId = categorie.parentId;
	categories[categorie.level][categorie.name].parent = categorie.parent;
	categories[categorie.level][categorie.name].width = categorie.width;
	categories[categorie.level][categorie.name].height = categorie.height;
	if( typeof(categorie.resumeLevel) != 'undefined' ) categories[categorie.level][categorie.name].resumeLevel = categorie.resumeLevel;
	else 											   categories[categorie.level][categorie.name].resumeLevel = -1;
	if( typeof(categorie.descriptionLevel) != 'undefined' ) categories[categorie.level][categorie.name].descriptionLevel = categorie.descriptionLevel;
	else 											        categories[categorie.level][categorie.name].descriptionLevel = -1;
	if( typeof(categorie.contentLevel) != 'undefined' ) categories[categorie.level][categorie.name].contentLevel = categorie.contentLevel;
	else 											    categories[categorie.level][categorie.name].contentLevel = -1;
	if( typeof(categorie.resume) != 'undefined' ) categories[categorie.level][categorie.name].resume = categorie.resume;
	else 									      categories[categorie.level][categorie.name].resume = '';
	if( typeof(categorie.description) != 'undefined' ) categories[categorie.level][categorie.name].description = categorie.description;
	else											   categories[categorie.level][categorie.name].description = '';
	if( typeof(categorie.content) != 'undefined' ) categories[categorie.level][categorie.name].content = categorie.content;
	else											categories[categorie.level][categorie.name].content = '';
	if( typeof(categorie.top) != 'undefined' )   categories[categorie.level][categorie.name].top = categorie.top;
	if( typeof(categorie.left) != 'undefined' )  categories[categorie.level][categorie.name].left = categorie.left;
	if( typeof(categorie.image) != 'undefined' ) categories[categorie.level][categorie.name].image = categorie.image;
}

loadCategoriesComplete = function( xhr, json )
{
	// remplissage du tableau "categories"
	var json = eval('('+xhr.responseText+')');
	LEVEL_MAX = json.zoomMax;
	json.categories.each(insertCategorie);
	
	// affichage des categories
	showCategories();
}

loadCategories = function()
{
	// calcule la taille de la zone
	if (window.innerWidth) centerContent[0] = Math.round(window.innerWidth / 2);
    else if (document.body && document.body.offsetWidth) centerContent[0] = Math.round(document.body.offsetWidth / 2);
    if (window.innerHeight) centerContent[1] = Math.round(window.innerHeight / 2);
 	else if (document.body && document.body.offsetHeight) centerContent[1] = Math.round(document.body.offsetHeight / 2);
 	
 	// récupére les données
	new Ajax.Request( 'scripts/getCategories.php', {method:'post',onComplete:loadCategoriesComplete} );
}

zoomUp = function()
{
	if( gLevel < LEVEL_MAX && activeZoom )
	{
		isZoomDown = false;
		activeZoom = false;
		++gLevel;
		showCategories();
		new Effect.Scale( $('zoomBox'), 150, {afterFinish:function(){activeZoom=true;}} );
	}
}

zoomDown = function()
{
	if( gLevel > 0 && activeZoom )
	{
		isZoomDown = true;
		activeZoom = false;
		--gLevel;
		showCategories();
		new Effect.Scale( $('zoomBox'), 67, {afterFinish:function(){activeZoom=true;activeMove=true;}} );
	}
}

/* GESTION DE LA MOLETTE DE LA SOURIS */
handle = function( delta ) 
{
	if( delta < 0 ) zoomDown();
	else			zoomUp();
}

// calcul pour la gestion de la molette de la souris
wheel = function( e )
{
	if( activeZoom )
	{
		var delta = 0;
		 
		var event = getEvent(e);
		
	    /* IE/Opera. */
	    if (event.wheelDelta) 
	    { 
	    	delta = event.wheelDelta / 120;
	        /** In Opera 9, delta differs in sign as compared to IE.*/
	        if (window.opera) delta = -delta;
	    }
	    else if( event.detail ) /** Mozilla case. */
	    { 
	    	/** In Mozilla, sign of delta is different than in IE.
	         * Also, delta is multiple of 3.
	         */
	        delta = -event.detail / 3;
	    }
	    /** If delta is nonzero, handle it.
	     * Basically, delta is now positive if wheel was scrolled up,
	     * and negative, if wheel was scrolled down.
	     */
	    if( delta ) handle(delta);
	    /** Prevent default actions caused by mouse wheel.
	     * That might be ugly, but we handle scrolls somehow
	     * anyway, so don't bother here..
	     */
	    if( event.preventDefault ) event.preventDefault();
		event.returnValue = false;
	}
}
/* INIT MOUSE SCROLL */
/** DOMMouseScroll is for mozilla. */
/** Else IE/Opera. */
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false);
else 						 window.onmousewheel = document.onmousewheel = wheel;