/** Generated by js.php */
/**
* Script principal de Dhtml_portal
*
* Ce script nécessite la librairie prototype
* ainsi que styles.js
*
*/

// variables de configuration

// espace maximal des bords de la page
var Portal_padding = '0px'

// espace entre les colonnes
var Portal_column_spacing = '20px' // obsolete

// espace entre les lignes
var Portal_row_spacing = '30px'

// permet de permuter les colonnes
var Portal_move_columns = true

// parametres des colonnes
var browser = navigator.userAgent.toLowerCase();
if (browser.indexOf("msie 6.0") != -1){
	var Columns_width = Array('250px','480px','250px')
}
else {
	var Columns_width = Array('250px','480px','250px')
}


// nombre de colonnes
var Portal_columns = Columns_width.length

// Constructeur du portal
Dhtml_portal = function(top,width,portlets)
{
	// propriétés

	// colonnes occupées
	this.columns = {}

	// top maximum des portlets
	this.top = top
	if(width) this.width = width

	// collection de portlets
	this.portletsConfig = portlets
	this.sorted_portlets = []


}

Dhtml_portal.prototype =
{

	// intialisation du portal
	init: function()
	{
		window.onresize();
		// création de l'objet portal
		this.portal = document.createElement('div')
		$('content').appendChild(this.portal)
		this.portal.id = 'Dhtml_portal'
		this.portal.className = 'Dhtml_portal'
		this.portal.style.display = 'block'
		if(this.width) this.portal.style.width = '100%'

		this.portlets = []
		//this.portal.style.position = 'absolute'
		/*if(this.top)
		{
			this.portal.style.top = parseInt(this.top)+'px'
		}*/
		
		//this.portal.style.top = '100px';

		// application de la configuration
		//this.portal.style.padding = Portal_padding;

		// creation des colonnes
		this.createColumns()

		// ajout des portlets au portal
		for(portlet in this.portletsConfig)
		{
			this.addPortlet(this.portletsConfig[portlet])
		}

		// création des portlets
		this.displayPortlets()
		
		// intialisation du drag and drop
		Sortable.create("column_1",
		{dropOnEmpty:true,scroll:window,scrollSpeed:30,tag:'div',handle:'Dhtml_portlet_header_title',containment:["column_1","column_2","column_3"],constraint:false,onUpdate:updateModules});
		Sortable.create("column_2",
		{dropOnEmpty:true,scroll:window,scrollSpeed:30,tag:'div',handle:'Dhtml_portlet_header_title',containment:["column_1","column_2","column_3"],constraint:false,onUpdate:updateModules});
		Sortable.create("column_3",
		{dropOnEmpty:true,scroll:window,scrollSpeed:30,tag:'div',handle:'Dhtml_portlet_header_title',containment:["column_1","column_2","column_3"],constraint:false,onUpdate:updateModules});
	},


	createColumns: function()
	{
		this.columns = []

		// calcul des largeurs de colonnes
		this.columnWidth = this.getColumnWidth()

		for(var i=1;i<Portal_columns+1;i++)
		{
			// création des div
			this.columns[i] = new Array()

			// largeur de la colonne
			if(Columns_width && Columns_width[(i-1)]) var column_width = Columns_width[(i-1)]
			else var column_width = this.columnWidth

			// création de la colonne
			var column = document.createElement('DIV')
			column.id = 'column_'+i
			column.className = 'Dhtml_portal_column'
			column.style.width = column_width
			column.style.display = 'block'
			column.style['float'] = 'left'
			this.columns[i] = column

			// création du span permettant de déplacer la colonne entière
			var span = document.createElement('SPAN')
			span.id = 'moving_column_'+i
			span.className = 'Dhtml_portal_moving_column'
			span.value = i
			//span.innerHTML = '&nbsp;'
			span.onmouseover = function () { portal.showMoveIcon(this.value) }
			span.onmouseout = function () { portal.hideMoveIcon(this.value) }

			var div1 = document.createElement('div')
			var div2 = document.createElement('div')

			var image = document.createElement('img')
			image.className = 'Dhtml_portal_moving_picture'
			image.id = 'Dhtml_portal_move_icon_'+i
			image.style.display = 'none'
			image.style.position = 'relative'
			image.src = '/img/move.gif'

			div1.appendChild(image)

			var sp = document.createElement('span')
			sp.id = 'toto'
			sp.width = '100%'
			div2.appendChild(sp)

			span.appendChild(div1)
			span.appendChild(div2)

			this.portal.appendChild(column)
		}
		var clear = document.createElement('br')
		clear.style.clear = 'both'
		this.portal.appendChild(clear)

	},

	displayPortlets: function()
	{
		// ordonne les portlets par colonne puis par ligne
		var portlets = this.sorted_portlets.sortBy(function(x) { return x.position; })

		for(i in portlets)
		{
			if(!portlets[i].config) continue
			else this.drawPortlet(portlets[i].config)
		}
	},



	addPortlet: function(portlet)
	{
		// on vérifie que la colonne est déjà enregistrée dans la collection
		if(!this.columns[portlet.column]) portlet.column = 1

		// constitution d'un second tableau pour ordonner les portlets

		// ajout d'un '0' avant la ligne pour gérer les cas de plus de 10 lignes
		if(parseInt(portlet.row)<10) portlet.row = '0'+portlet.row
		var index = parseInt(portlet.column+''+portlet.row)

		// gestion des emplacements "déjà pris"
		while(this.sorted_portlets[index]) index++

		this.sorted_portlets[this.sorted_portlets.length] = {config:portlet,position:index}

		// reference par module_id vers les portlets ajoutés
		var matches = new String(portlet.id).match(/.*_(\d+)$/)
		module_id = new String(matches).split(',')[1]
		this.portlets[module_id] = this.sorted_portlets.length - 1
	},

	drawPortlet: function (portletData,beforeElement) {
		// création du porlet
		var portlet = document.createElement('div')
		portlet.id = portletData.id
		portlet.style.position = 'relative'
		portlet.className = 'Dhtml_portlet'
		portlet.style['float'] = 'left'

		if(portletData.url) portlet.setAttribute('url',portletData.url)
		if(portletData.module) portlet.module = portletData.module
		if(portletData.type) portlet.type = portletData.type
		if(portletData.title) portlet.header_title = portletData.title
		if(portletData.state) portlet.state = portletData.state

		// création du header
		var portlet_header = document.createElement('div')


		portlet_header.className = 'Dhtml_portlet_header'
		portlet_header.id = portlet.id+'_header'
		portlet.appendChild(portlet_header)

		var table_header = document.createElement('table')

		table_header.setAttribute('cellPadding',0)
		table_header.setAttribute('cellSpacing',0)

		// index des cellules ; nécessite une variable
		// car le nombre peut changer selon que l'on insère
		// où non certains boutons (refresh pour le moment)
		var cell_index = 0

		var table_header_row = table_header.insertRow(0)


		// première cellule, avec le lien de minimisation
		var table_header_cell = table_header_row.insertCell(0)
		table_header_cell.id = 'minimize_'+portlet.id;
		table_header_cell.className = 'Dhtml_portlet_header_cell leftcell'
		cell_index++

		//table_header_cell.style.verticalAlign = 'middle'

		var iconSrc = ''
		if(portlet.state == 1 || portlet.state == 0) iconSrc = '/content/contents/get_image/portlet/collapse/png'
		else iconSrc = '/content/contents/get_image/portlet/expand/png'

		var reduceButton = document.createElement('img')
		reduceButton.className = 'pngTrans';
		reduceButton.style.paddingRight = "5px";
		reduceButton.id = portlet.id+'_reduce_icon'
		reduceButton.align = 'absmiddle'
		reduceButton.src = iconSrc

		table_header_cell.onclick = this.togglePortlet

		table_header_cell.appendChild(reduceButton)

		// title
		var table_header_cell = table_header_row.insertCell(cell_index)
		table_header_cell.className = 'Dhtml_portlet_header_cell'
		cell_index++

		table_header_cell.className = 'Dhtml_portlet_header_title'
		table_header_cell.style.width = '100%'
		table_header_cell.innerHTML = portlet.header_title
		table_header_cell.ondblclick = this.togglePortlet



		if(portlet.getAttribute('url'))
		{
			// refresh
			var table_header_cell = table_header_row.insertCell(cell_index)
			table_header_cell.className = 'Dhtml_portlet_header_cell'
			cell_index++

			var refreshIcon = document.createElement('img')
			//refreshIcon.src = '/themes/orange/refresh.png'
			refreshIcon.src = '/content/contents/get_image/portlet/refresh/png';
			refreshIcon.className = 'refreshIcon'
			refreshIcon.onclick = this.refreshPortlet
			refreshIcon.className = 'pngTrans';

			refreshIcon.style.display = 'block'
			refreshIcon.style.paddingRight = '5px';
			table_header_cell.appendChild(refreshIcon)
		}

		// close
		var table_header_cell = table_header_row.insertCell(cell_index)
		table_header_cell.className = 'Dhtml_portlet_header_cell rightcell'
		cell_index++

		var closeIcon = document.createElement('img')
		closeIcon.src = '/content/contents/get_image/portlet/close/png'
		closeIcon.className = 'pngTrans';
		closeIcon.onclick = this.closePortlet
		closeIcon.style.display = 'block'
		table_header_cell.appendChild(closeIcon)



		// insertion du header dans le portlet
		portlet_header.appendChild(table_header)

		// content container ?
		var portlet_content_container = document.createElement('div')
		portlet_content_container.className = 'Dhtml_portlet_content_container'
		portlet.appendChild(portlet_content_container)
		
		var portlet_footer = document.createElement('div')
		portlet_footer.className = 'Dhtml_portlet_footer'
		portlet.appendChild(portlet_footer)
		
		var portlet_footer_left = document.createElement('div')
		portlet_footer_left.className = 'Dhtml_portlet_footer_left'
		portlet_footer.appendChild(portlet_footer_left)
		
		// content
		var centered_content = document.createElement('center')

		var portlet_content = document.createElement('div')
		portlet_content.id = portlet.id+'_content'
		centered_content.appendChild(portlet_content)
		portlet_content_container.appendChild(centered_content)
		portlet_content_container.appendChild(document.createElement('br'))

		portlet_content.className = 'Dhtml_portlet_content'

		if(portletData.height)
		{
			portlet_content.style.minHeight = portletData.height+'px'
			//portlet_content.style.height = portletData.height+'px'
		}

		// on masque les contenus des portlets réduits
		if(portlet.state == 2) portlet_content_container.style.display='none'

		// on affiche les contenus des portlets non réduits
		if(portlet.state == 1) portlet_content_container.style.display='block'

		// on masque les portlets cachés
		if(portlet.state == 0) portlet.style.display='none'


		// ajout du portlet dans la colonne
		var column = portletData.column
		if (beforeElement) {
			$('column_3').insertBefore(portlet,beforeElement);
		} else {
			this.columns[column].appendChild(portlet)
		}
		
		// chargement du contenu si nécessaire
		if(portlet.state != 0 && portlet.getAttribute('url')) fetchContent({portlet_id:portlet.id,url:portlet.getAttribute('url')})

	}
	,
	getColumnWidth: function()
	{
		return Math.round(100 / Portal_columns)+"%"
	},

	raiseError: function(msg)
	{
		alert(msg)
		return
	},

	dump: function(o)
	{
		document.write("<pre>"+_mlt("OBJECT_CONTENT","Contenu de l'objet")+" :\n\n")
		for(i in o)
		{
			if(typeof(o[i]) == "function") continue
			document.write(i + ' ' +o[i]+'\n')
		}
		document.write("</pre>")
	},


	closePortlet: function(e)
	{
		if(!e) {
			e = window.event
		}
		if (e.target) source = e.target;
		else if (e.srcElement) source = e.srcElement;
		if (source.nodeType == 3) {} // defeat Safari bug

		var portlet_id = source.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id
		$(portlet_id).style.display = "none"
		portal.savePortletPreference(portlet_id,'state',0)
	}
	,


	refreshPortlet: function(e)
	{
		if(!e) {
			e = window.event
		}
		if (e.target) source = e.target;
		else if (e.srcElement) source = e.srcElement;
		if (source.nodeType == 3) {} // defeat Safari bug
		var portlet_id = source.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id
		fetchContent({portlet_id:portlet_id,silent:false})
	},


	savePortletsPositions: function(column_id)
	{
		// id de la colonne
		var column = this.columns[column_id]


		// Arguments contenant les différentes informations concernant les portlets
		var portletsData = ''
		var row = 1;
		for(var j=0;j<column.childNodes.length ;j++)
		{
			var portlet = column.childNodes[j]
			if(portlet.style.display == 'none') continue;
			if(portlet.tagName != 'DIV' || portlet.className != 'Dhtml_portlet') continue;

			portletsData += 'portlets['+portlet.id+'][column]='+column_id+'&portlets['+portlet.id+'][row]='+row+'&'
			row++
		}
		new Ajax.Request('/module_preferences/save_portlets_positions',{parameters:portletsData})
	},

	togglePortlet: function(e)
	{

		if(!e) {
			e = window.event
		}
		if (e.target) source = e.target;
		else if (e.srcElement) source = e.srcElement;
		if (source.nodeType == 3) {} // defeat Safari bug

		var i = 0 // soupape de sécurité du while suivant
		while(source.className != 'Dhtml_portlet')
		{
			source = source.parentNode
			if(i++ > 30)
			{
				alert('Error : portlet container was not found');
				return
			}
		}
		var portlet_id = source.id

		var portlet_content = Element.up($(portlet_id+"_content"),'div')

		var icon = $(portlet_id+'_reduce_icon')
		if (portlet_content.style.display=="none"){
			portlet_content.style.display="block"
			icon.src = "/content/contents/get_image/portlet/collapse/png"
			//icon.style.width = "15px";
			//icon.style.height = "10px";
			// on est obligé de faire référence à portal au lieu de this
			// car togglePortlet est déclenchée par un évènement, et que
			// this fait référence à la source (piste à creuser pour récupérer
			// la source des évènements d'ailleurs
			portal.savePortletPreference(portlet_id,'state',1)
		}
		else
		{
			portlet_content.style.display="none"
			icon.src = "/content/contents/get_image/portlet/expand/png"
			//icon.style.height="15px";
			//icon.style.width ="10px";
			
			portal.savePortletPreference(portlet_id,'state',2)
		}
	}
	,
	savePortletPreference: function(portlet_id,preference,value)
	{
		var type = 'module';
		if (portlet_id.match(/rss/)) type = 'rss';

		// recherche de l'id du module
		var matches = new String(portlet_id).match(/.*_(\d+)$/)
		module_id = new String(matches).split(',')[1]
		// alert('Id du module : '+module_id+'\nClef : '+preference+'\nValeur : '+value)
		new Ajax.Request('/module_preferences/save/'+module_id+'/'+type+'/'+preference+'/'+value)

	}
	,
	switchPortlet: function(portlet_id,rss)
	{
		
		if(rss) {
			var id= 'rss_module_'+portlet_id;
		} else {
			var id = 'module_'+portlet_id;
			rss = false;
		}
		var container = $(id); 
		if(container.style.display == 'none')
		{
			loadModule(portlet_id,rss);
			
			if(container.down('img').src.match(/expand\.gif/)) state = 2
			else state = 1
			container.style.display = ''
			portal.savePortletPreference(id,'state',state)
		}
		else {
			$(id).style.display = 'none'
			portal.savePortletPreference(id,'state',0)
		}
	}
	,
	debug: function(key,value)
	{
		if(!this.debugDiv)
		{
			this.debugDiv = document.createElement('DIV')
			this.debugDiv.style.backgroundColor = 'white'
			this.debugDiv.style.border = '1px solid black'
			this.debugDiv.style.position = 'absolute'
			this.debugDiv.style.zIndex = 545435435

			document.body.appendChild(this.debugDiv)
		}
		this.debugDiv.innerHTML += key + ' => ' + value + '<br>'
	}
	,
	showMoveIcon: function(column_id)
	{
		$('Dhtml_portal_move_icon_'+column_id).style.display = 'block'
		$('column_'+column_id).className = 'Dhtml_portal_column_hover'

	}
	,
	hideMoveIcon: function(column_id)
	{
		$('Dhtml_portal_move_icon_'+column_id).style.display = 'none'
		$('column_'+column_id).className = 'Dhtml_portal_column'
	}
}

function loadModule(module_id,rss) {
	if(rss) {
		var id= 'rss_module_'+module_id;
	} else {
		var id = 'module_'+module_id;
		rss = false;
	}
	var container = $(id + '_content');
	var url = $(id).getAttribute('url');
	
	container.innerHTML = "<div style='width:100%;align:center;vertical-align:middle'><center>Loading ...</center></div>";
	
	new Ajax.Updater(
	container,
	url,
	{
		method: 'post',
		evalScripts:true,
		requestHeaders:['Content-Type','text/html;charset=UTF-8']
	});
}

function fetchContent(options,e)
{
	portlet_id = options.portlet_id || ''
	url = options.url || ''
	params = options.parameters || []
	if(options.silent != null) silent = options.silent
	else silent = true

	// on détermine le portlet a mettre a jour
	if(options.target)
	{
		target = $(options.target)
	}
	else if(portlet_id)
	{
		target = $(portlet_id+'_content')
	}
	else
	{
		if(!e) {
			e = window.event
		}
		if (e.target) source = e.target;
		else if (e.srcElement) source = e.srcElement;
		if (source.nodeType == 3) // defeat Safari bug

		//source = Event.element(e)

		var i = 0 // soupape de sécurité du while suivant
		while(source.parentNode.className != 'Dhtml_portlet_content')
		{
			source = source.parentNode
			if(i++ > 30)
			{
				alert('Error : portlet container was not found');
				return
			}
		}

		target = $(source.parentNode.id)
		// portlet_id = source.parentNode.parentNode.parentNode.parentNode.id
	}



	// gestion de l'url
	if(!url)
	{
		url = target.getAttribute('url')
	}
	else
	{
		target.setAttribute('url',url)
	}


	// affichage du message d'attente
	var height =  '100%'

	if(document.all)
	{
		height = target.offsetHeight;
	}
	else
	{
		if ( target.style.display != 'none')
		{
			height = document.defaultView.getComputedStyle(target, "").getPropertyValue("height");
		}
	}


	// gestion des parametres

	if(!silent) target.innerHTML = "<div style='width:100%;height:"+height+";align:center;vertical-align:middle'><center>Loading ...</center></div>";
	//else sloubi = $(updating_portlet_id).innerHTML
	new Ajax.Updater(
	target,
	url,
	{
		method: 'post',
		evalScripts:true,
		requestHeaders:['Content-Type','text/html;charset=UTF-8'],
		parameters:params
	});

}


function updateModules(column)
{

	// Traitement du cas d'une colonne vide

	var sloubi = 0 // compteur de portlets

	for(var j=0;j<column.childNodes.length ;j++)
	{
		var portlet = column.childNodes[j]
		if(portlet.tagName != 'DIV' || portlet.className != 'Dhtml_portlet') continue;
		else sloubi++
	}

	// si il n'y a plus de portlets dans la colonne,
	// on change son style
	if(sloubi == 0) Element.addClassName(column,'Dhtml_portal_empty_column')
	else Element.removeClassName(column,'Dhtml_portal_empty_column')

	var column_id = new String(column.id.match(/.*_(\d+)$/)).split(',')[1]
	setTimeout("portal.savePortletsPositions('"+column_id+"')",500)
}

function updateModule(module_id,silent)
{
	if(!silent) silent = 'false'
	else silent = 'true'

	eval("fetchContent({portlet_id:'module_"+module_id+"',silent:silent})")
}

// affichage d'un contenu en "plein écran"
showFullScreenPortlet = function(content_url)
{
	new Ajax.Updater('fullScreenPortlet',content_url)
	document.body.style.overflow = 'hidden'
	$('content').hide();
	resizeFullScreenPortlet();
	Element.observe(window,"resize",resizeFullScreenPortlet)
	
	$('fullScreenPortlet').show();
}

hideFullScreenPortlet = function()
{
	$('content').show();
	$('fullScreenPortlet').hide();
	document.body.style.overflow = 'auto'
	Element.stopObserving(window,"resize",resizeFullScreenPortlet)
}

resizeFullScreenPortlet = function()
{
	// calcul de la taille de fenêtre
	screenInfos = getScreenSize()
	$('fullScreenPortlet').style.width = (screenInfos.width - 20) + 'px'
	$('fullScreenPortlet').style.height = (screenInfos.height - 75 ) + 'px'
}

getScreenSize = function()
{
	// fonction de support
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			winW = document.documentElement.offsetWidth;
			winH = document.documentElement.offsetHeight;
		}
	}

	return {height:winH,width:winW}
	
}

