var OS3Tree = {};

OS3Tree.instances = new Array ();

OS3Tree.ERR_NO_RESULTS = -1;
OS3Tree.ERR_TOP_REACHED = -2;
OS3Tree.ERR_BOTTOM_REACHED = -3;

// ============================================================0
// Tree 
// ============================================================0

OS3Tree._int_events = {};



OS3Tree._int_events [ 'hover' ] = function ( tree, div, node )
{
	if ( tree._curr_node ) tree._curr_node._div.className = ( tree._curr_node == tree._curr_node_sel ? "sel" : "norm" );

	if ( div.className == "sel" )
		div.className = "tree_hover_sel";
	else
		div.className = "tree_hover";

	if ( tree.arrange_branches )
		OS3Tree._show_arrange ( tree, div, node );

	tree._curr_node = node;
	node._div = div;
};


OS3Tree._int_events [ 'out' ] = function ( tree, div, node )
{
	// console.debug ( "OUT: %s", div.id );
	if ( div._stop_out )
	{
		div._stop_out = false;
		return;
	}

	div.className = ( node == tree._curr_node_sel ? "sel" : "norm" );
	if ( tree.arrange_branches )
		OS3Tree._hide_arrange ( tree, div, node );
};

OS3Tree._int_events [ 'btn_down' ] = function ( tree, div, node )
{
        div.className = "btn_down";
};

OS3Tree._int_events [ 'btn_up' ] = function ( tree, div, node )
{
        div.className = "btn_up";
};

OS3Tree._int_events [ 'click' ] = function ( tree, div, node )
{
        if ( ( tree._curr_node_sel ) && ( tree._curr_node_sel == tree._curr_node ) ) 
	{
		tree._curr_node_sel = null;
		tree._curr_node._div.className = 'norm';
		node.is_selected = false;
		return;
	}

	tree.current_clear ();

        tree._curr_node_sel = tree._curr_node;
	tree._curr_node_sel.is_selected = true;
        tree._curr_node._div.className = 'sel';
};

OS3Tree._int_events [ 'node_up' ] = function ( tree, div, node )
{
	console.debug ( "Node UP!" );
};

OS3Tree._int_events [ 'node_down' ] = function ( tree, div, node )
{
	console.debug ( "Node DOWN!" );
};

// {{{ _arrange 
OS3Tree._arrange = {};

OS3Tree._arrange._div = document.createElement ( "div" );
OS3Tree._arrange._div.style.position = "absolute";
OS3Tree._arrange._div.style.right = "0px";
OS3Tree._arrange._div.style.top = "0px";
OS3Tree._arrange._curr_div = null;
OS3Tree._arrange._div.onmouseover = function () { 
	// console.debug ( "STOP: %s", OS3Tree._arrange._curr_div.id ); 
	if ( OS3Tree._arrange._curr_div ) OS3Tree._arrange._curr_div._stop_out = true; 
};
// }}}
// {{{ _show_arrange ( tree, div, node )
OS3Tree._show_arrange = function ( tree, div, node )
{
	// console.debug ( div.innerHTML );

	if ( OS3Tree._arrange._curr_div == div ) return;

	OS3Tree._hide_arrange ();

	OS3Tree._arrange._div.style.width = "4em";
	OS3Tree._arrange._div.style.height = "1em";
	OS3Tree._arrange._div.style.backgroundColor = "red";

	OS3Tree._arrange._curr_div = div;

	// Stop the "out" event on the current div when the "new" div will be appended
	// over it.
	OS3Tree._arrange._curr_div._stop_out = true;

	div.appendChild ( OS3Tree._arrange._div );

	OS3Tree._arrange._div.innerHTML = '<a href="javascript:OS3Tree._node_up(\'' + tree.id + '\',\'' + div.id + '\',\'' + node.id + '\')">^^</a>&nbsp;' + 
					  '<a href="javascript:OS3Tree._node_down(\'' + tree.id + '\',\'' + div.id + '\',\'' + node.id + '\')">vv</a>';
};
// }}}
// {{{ _node_up ( tree_id, div_id, node_id )
OS3Tree._node_up = function ( tree_id, div_id, node_id )
{
	var tree = OS3Tree.instances [ tree_id ];
	var div  = document.getElementById ( div_id );
	var node = tree.nodes [ node_id ];

	OS3Tree.evt ( div, 'node_up' );
	tree.node_up ( node );
};
// }}}
// {{{ _node_down  ( tree_id, div_id, node_id )
OS3Tree._node_down = function ( tree_id, div_id, node_id )
{
	var tree = OS3Tree.instances [ tree_id ];
	var div  = document.getElementById ( div_id );
	var node = tree.nodes [ node_id ];

	OS3Tree.evt ( div, 'node_down' );
	tree.node_down ( node );
};
// }}}
// {{{ _hide_arrange ( tree, div, node )
OS3Tree._hide_arrange = function ( tree, div, node )
{
	if ( ! OS3Tree._arrange._curr_div ) return;

	console.debug ( "HIDE" );

	OS3Tree._arrange._curr_div.removeChild ( OS3Tree._arrange._div );
	OS3Tree._arrange._curr_div = null;
};
// }}}


// {{{ OS3Tree.instance = function ( id )
OS3Tree.instance = function ( id )
{
	this.id = id;

	this.show_checkbox = false;		// Flag T/F. If T, each node will have a checkbox
	this.show_folder_checkbox = true;	// Flag T/F. If T, folders will have checkbox (if show_checkbox is true)
	this.show_expand   = true;	// Flag T/F. If T, each "folder" will have an expand/collapse button
	this.folders_collapsed  = true;	// Flag T/F. If T, folders starts in "collapsed" mode
	this.expand_limit = 0;		// A value reppresenting the level of folders to show

	this.arrange_branches = false;	// Flag T/F. If T, tree branches can be moved with buttons

	this.status_img = [ 'empty', 'half', 'full' ];

	this.width = 0;		// Tree width & height. You *MUST* specify the type (CSS mode )
	this.height = 0;
	this.scrollbars = true;

	this.expand_request = null;  // Callback to be defined called when the user clicks on the "+" button
				     // exapand_request ( node_instance )

	this._events = {};		// Tree custom events
	this._blocked_events = {};	// Tree blocked events

	// ==========================================================================================================================
	// Public Methods
	// ==========================================================================================================================
	this.node_up = function ( node )
	{
		var lst, pos, l;

		if ( node.parent )
			lst = node.parent.list;
		else
			lst = this.list;

		pos = lst.indexOf ( node );
		if ( pos == 0 ) return;

		var prev = lst [ pos -1 ];
		var node_div = document.getElementById ( node.tree.id + ":" + node.id ).parentNode;
		var prev_div = document.getElementById ( prev.tree.id + ":" + prev.id ).parentNode;
		var container = prev_div.parentNode;

		container.removeChild ( node_div );
		container.insertBefore ( node_div, prev_div );

		lst [ pos ] = prev;
		lst [ pos -1 ] = node;
	};

	this.node_down = function ( node )
	{
		var lst, pos, l;

		if ( node.parent )
			lst = node.parent.list;
		else
			lst = this.list;

		pos = lst.indexOf ( node );
		if ( pos == ( lst.length -1 ) ) return;

		var next = lst [ pos + 1 ];
		var node_div = document.getElementById ( node.tree.id + ":" + node.id ).parentNode;
		var next_div = document.getElementById ( next.tree.id + ":" + next.id ).parentNode;
		var container = next_div.parentNode;

		container.removeChild ( next_div );
		container.insertBefore ( next_div, node_div );

		lst [ pos ] = next;
		lst [ pos +1 ] = node;

	};

	// {{{ add_node ( parent_node, text, id, val, onclick )
	/*
		Adds a node to the tree.

		INPUTS:
			- parent_node: 	the node that will contain this node
			- text:		text to be shown
			- id:		(optional) an ID value to be used to search the node
			- val:		(optional) value to be returned if the node is selected.
					This is used only when the OS3Tree has the ``show_checkbox`` atribute
					set to true.

		RESULT: - a valid node structure

	*/
	this.add_node = function ( parent_node, text, id, val, onclick )
	{
		var node;

		if ( ! id ) 
		{
			if ( ! parent_node )
				id = this.list.length +1;
			else
				id = parent_node.id + "_" + ( parent_node.list.length +1 );
		}

		node = new OS3Tree.Node.instance ( parent_node, text, id, val, onclick, this );

		node.expand_request = this.expand_request;
		
		// Add the new node to the ordered list
		// If ``parent_node`` is null, the new node is added to the
		// root list
		if ( ! parent_node ) 
			this.list.push ( node );
		else
		{
			parent_node.list.push ( node );
			parent_node._nodes ++;
		}


		// The ``id`` of the new node is added to the associative
		// array used to identify nodes by id
		this.nodes [ id ] = node;

		return node;
	};
	// }}}
	// {{{ add_folder ( parent_node, text, id, val, onclick )
	this.add_folder 	= function ( parent_node, text, id, val, onclick )
	{
		var n = this.add_node ( parent_node, text, id, val, onclick );

		n._is_folder = true;
		return n;
	};
	// }}}
	// {{{ get_node_by_id ( id )
	this.get_node_by_id 	= function ( id )
	{
		return this.nodes [ id ];
	};
	// }}}
	// {{{ render ( html_id )
	this.render = function ( id )
	{
		var n;
		var l = this.list.length;
		var s;

		if ( ! id ) id = this.html_id;

		s = '<div id="tree:' + id + '" class="os3tree" style="overflow: ';

		if ( this.scrollbars ) 
			s += "auto;";
		else
			s += "none;";

		if ( this.width ) s += " width: " + this.width + ";";
		if ( this.height ) s += " height: " + this.height + ";";
		s += '"';

		// if ( this.arrange_branches ) s += ' onmouseout="OS3Tree._hide_arrange()" ';
		
		s += '>';

		this.html_id = id;

		for ( n = 0; n < l; n ++ ) s += this.list [ n ].render ();

		s += '</div>';

		document.getElementById ( this.html_id ).innerHTML = s;

		if ( ( this._post_render.length ) && ( this.expand_request ) )
		{
			for ( n = 0; n < this._post_render.length; n ++ )
				this.expand_request ( this._post_render [ n ] );
		}
	};
	// }}} 

	this.current_clear = function ()
	{
        	if ( this._curr_node_sel ) 
		{
			this._curr_node_sel._div.className = 'norm';
			this._curr_node_sel.is_selected = false;
			this._curr_node_sel = null;
		}
	};

	this.current_get = function ()
	{
		return this._curr_node_sel;
	};

	// {{{ get_selection ( folders_only )
	this.get_selection	= function ( folders_only )
	{
		var arr = new Array ();
		var l = this.list.length;
		var t;

		if ( ! folders_only ) folders_only = false;

		for  ( t = 0; t < l; t ++ ) this.list [ t ].get_selection ( arr, folders_only );

		return arr;
	};
	// }}}
	// {{{ mk_list ( mode, val )
	// Mode: 
	//		1 - Text
	//		2 - Val
	this.mk_list		= function ( mode, val )
	{
		this.res_list = new Array ();

		var l = this.list.length;
		var t;

		for  ( t = 0; t < l; t ++ ) this.list [ t ].mk_list ( mode, val );

		this.res_list_index = -1;

		return this.res_list.length;
	};
	// }}}
	// {{{ show_result_prev ()
	this.show_result_prev = function ()
	{
		if ( this.res_list.length == 0 ) return OS3Tree.ERR_NO_RESULTS;
		if ( this.res_list_index == -1 ) return OS3Tree.ERR_TOP_REACHED;
		
		var n = this.res_list [ this.res_list_index  -- ];
		var e = document.getElementById ( n.tree.id + ":" + n.id );

		n.open_parent ();

		this._hl_element ( e );

		return 0;
	};
	// }}}
	// {{{ show_result_next ()
	this.show_result_next	= function ()
	{

		if ( this.res_list.length == 0 ) return OS3Tree.ERR_NO_RESULTS;
		if ( this.res_list_index == this.res_list.length -1 ) return OS3Tree.ERR_BOTTOM_REACHED;
		
		var n = this.res_list [ ++ this.res_list_index ];
		var e = document.getElementById ( n.full_id );

		n.open_parent ();

		this._hl_element ( e );

		document.location = "#" + n.id;

		return 0;
	};
	// }}}
	// {{{ clear ()
	this.clear =  function ()
	{
		var n, l = this.list.length;
	  
		for ( n = 0; n < l; n ++ ) this.list [ n ].change_status ( 0 );
	};
	// }}}

	this.block_event = function ( event_name, mode )
	{
		if ( mode === undefined ) mode = true;
		this._blocked_events [ event_name ] = mode;
	};

	this.set_event = function ( evt_name, cback )
	{
		this._events [ evt_name ] = cback;
	};

	this.del_node = function ( node )
	{
		var lst = this.list;
		var t, l;
		var p = node.parent;

		if ( p ) lst = p.list;

		l = lst.length;

		for ( t = 0; t < l; t ++ )
			if ( lst [ t ] == node )
			{
				this._del_node ( t, lst );
				break;
			}

		if ( p ) 
		{
			p._nodes --;
			p.refresh ();
		} else {
			this._nodes --;
			this.render ();
		}

		if ( node == this._curr_node_sel )
			this._curr_node_sel = null;
		
	};

	this._del_node = function ( pos, lst )
	{
		var node = lst [ pos ];
		var t, l = lst.length - 1;

		for ( t = l; t >= 0; t -- )
			this._del_node ( t, node.list );

		lst.splice ( pos, 1 );
	};

	// ==========================================================================================================================
	// Private Methods
	// ==========================================================================================================================
	// {{{ _hl_element ( e )
	this._hl_element = function ( e )
	{
		var main_div;

		if ( this.res_list_element )
		{
			this.res_list_element.style.backgroundColor = this.res_list_element.old_col;
			this.res_list_element = null;
		}

		if ( ! e ) return;

		e.old_col = e.style.backgroundColor;
		e.style.backgroundColor = "red";
		this.res_list_element = e;

		main_div = document.getElementById ( "tree:" + this.html_id );

		main_div.scrollTop = e.offsetTop - 10;
	};
	// }}}


	// ==========================================================================================================================
	// Private Attributes
	// ==========================================================================================================================
	this.nodes = new Array();	// Nodes by id
	this.list  = new Array();	// Nodes by order (only if parent_node is NULL)
	this.html_id = 0;		// HTML id for the element to be replaced by OS3Tree

	this._post_render = new Array ();
	this.res_list = new Array();
	this.res_list_index = -1;
	this.res_list_element = null;

	// Register the Tree instance
	OS3Tree.instances [ this.id ] = this;
};
// }}}
// {{{ OS3Tree.expand ( img, force_mode )
OS3Tree.expand = function ( img, force_mode )
{
	var folder = img.parentNode;
	var e = folder.lastChild;
	var node = OS3Tree.get_node_by_id ( folder.id );

	if ( node._is_folder && node._nodes == 0 )
	{
		img.className = 'wait';
		node.expand_request ( node );
		return;
	} 

	if ( e.style.display == force_mode ) return;

	// if ( force_mode ) alert ( force_mode + " - " + e.style.display );

	if ( force_mode )
	{
		if ( force_mode == 'block' )
		{
			e.style.display = 'block';
			img.className = 'minus';
		} else {
			e.style.display = 'none';
			img.className = 'plus';
		}
	} else {
		if ( e.style.display != 'none' )
		{
			e.style.display = 'none';
			img.className = 'plus';
		} else {
			e.style.display = 'block';
			img.className = 'minus';
		}
	}
};
// }}}
// {{{ OS3Tree.get_tree_by_id ( id )
OS3Tree.get_tree_by_id = function ( id )
{
	return OS3Tree.instances [ id ];
};
// }}}
// {{{ OS3Tree.node_select ( tree_id, node_id, status, img )
OS3Tree.node_select = function ( tree_id, node_id, status, img )
{
	var new_status = 0;
	var t = OS3Tree.instances [ tree_id ];
	var n = t.nodes [ node_id ];

	if ( n.status == 0 ) return n.change_status ( 2 );

	return n.change_status ( 0 );
};
// }}}
// {{{ OS3Tree.get_node_by_id ( node_id )
OS3Tree.get_node_by_id = function ( node_id )
{
	var data = node_id.split ( ":" );
	var tree = OS3Tree.instances [ data [ 1 ] ];
	return tree.nodes [ data [ 2 ] ];
};
// }}}
OS3Tree.evt = function ( div, event_name )
{
	var values = div.id.split ( ":" );
	var tree_name = values [ 0 ];	// Tree name
	var tree = OS3Tree.instances [ tree_name ];
	var node = tree.nodes [ values [ values.length -1 ] ];

        if ( tree._blocked_events [ event_name ] ) return;
        if ( OS3Tree._int_events [ event_name ] ) OS3Tree._int_events [ event_name ] ( tree, div, node );
        if ( tree._events [ event_name ] ) tree._events [ event_name ] ( tree, event_name, div, node );
};


// ============================================================0
// Tree Node
// ============================================================0

OS3Tree.Node = {};

// {{{ OS3Tree.Node.instance ( parent_node, text, id, val, onclick, _tree )
OS3Tree.Node.instance = function ( parent_node, text, id, val, onclick, _tree )
{
	this.parent = parent_node;
	this.text   = text;
	this.id	    = id;
	this.val    = val;
	this.onclick = onclick;
	this.tree   = _tree;
	this.status = 0;	// 0 == empty, 1 == half (folders only), 2 == full
	this.full_id = _tree.id + ":" + this.id;
	this.expand_request = null;

	this.is_selected = false;

	this.list   = new Array ();

	if ( this.parent )
		this.level  = this.parent.level + 1;
	else
		this.level = 1;

	// {{{ render ()
	this.render = function ()
	{
		var s = '';
		var l = this.list.length;
		var n, cl;
		var img, show_hidden = false;

		s = '<a name="' + this.full_id + '"></a>';
		
		if ( ! this._is_folder )
		{
			s += '<div class="node"><div class="void"></div>'; 
			s += this._mk_chkbox ( this, false );
			s += this._mk_events ( this );
			s += '</div>';

			return s;
		}

		s += '<div class="folder" id="folder:' + this.full_id + '">';

		if ( this.tree.show_expand ) 
		{
			if ( ( this.tree.folders_collapsed ) && ( this.level > this.tree.expand_limit ) ) show_hidden = true;

			// if ( show_hidden == false ) callback_la_prima_volta
			if ( ( show_hidden == false ) && ( this._is_folder ) ) this.tree._post_render.push ( this );

			s += '<div id="handle:' + this.full_id + '" onclick="OS3Tree.expand(this)" class="';

			if ( show_hidden ) 
				s += 'plus';
			else
			{
				if ( this._is_folder )
				{
					if ( this._nodes )
						s += 'minus';
					else
						s += 'wait';
					// s += 'plus';
				} else
					s += 'minus';
			}

			s += '"></div>';
		}

		s += this._mk_chkbox ( this, true );
		s += this._mk_events ( this );
		s += '<div class="folder_box"';
		if ( show_hidden ) s += ' style="display: none"';
		s += '>';

		for ( n = 0; n < l; n ++ ) s += this.list [ n ].render ();

		if ( this.tree.show_expand ) s += '</div>';
		s += '</div>';

		return s;
	};
	// }}}
	// {{{ change_status ( new_status )
	this.change_status = function ( new_status )
	{
		if ( this.status == new_status ) return;		// Do nothing if status has not changed

		var l = this.list.length;
		var n;
		var img = document.getElementById ( this._mk_img_id ( this ) );

		this.status = new_status;
		img.className = this.tree.status_img [ this.status ];

		if ( new_status == 2 ) this._add_node ( this.parent, new_status );
		else if ( new_status == 0 ) this._del_node ( this.parent, new_status );

		for ( n = 0; n < l; n ++ ) this.list [ n ].change_status ( new_status );
	};
	// }}}
	//  {{{ get_selection ( arr, folders_only )
	this.get_selection = function ( arr, folders_only )
	{
		var l = this.list.length;
		var t;

		if ( this.status == 2 )
		{
			if ( this.val )
				arr [ this.id ] = this.val;
			else
				arr [ this.id ] = true;

			if ( folders_only ) return;
		}

		for ( t = 0; t < l; t ++ ) this.list [ t ].get_selection ( arr, folders_only );
	};
	// }}}
	// {{{ mk_list ( mode, val )
	this.mk_list = function ( mode, val )
	{
		var l = this.list.length;
		var t;

		switch ( mode )
		{
			case 1: 	// Text
				if ( this.text.toLowerCase().indexOf ( val.toLowerCase () ) != -1 ) this.tree.res_list.push ( this );
				break;

			case 2:		// Value
				if ( this.val == val ) this.res_list.push ( this );
				break;
		}

		for ( t = 0; t < l; t ++ ) this.list [ t ].mk_list ( mode, val );
	};
	// }}}
	// {{{ expand ( mode )
	this.expand = function ( mode )
	{
		var img_name = "handle:" + this.full_id;

		if ( mode == true ) mode = "block";
		else if ( mode == false ) mode = "none";

		OS3Tree.expand ( document.getElementById ( img_name ), mode );
	};
	// }}}
	// {{{ open_parent ()
	this.open_parent   = function ()
	{
		if ( ! this.parent ) return;

		this.parent.expand ( true );
		this.parent.open_parent ();
	};
	// }}}
	// {{{ expand_done ( elems )
	this.expand_done   = function ( elems )
	{
		var img = document.getElementById ( 'handle:' + this.full_id );
		var l, t, n, node, s, folder;

		if ( ! elems ) 
		{
			// TODO: uscire senza togliendo il piu'
			return;
		}

		l = elems.length;
		for ( t = 0; t < l; t ++ )
		{
			n = elems [ t ];

			node = this.tree.add_node ( this, ( n.text ? n.text : 'NO TEXT' ), n.id, n.val, n.onclick );
			node._is_folder = n.folder ? true : false;
			node.status = this.status == 0 ? 0 : 2;
		}

		this.refresh ();

		folder = document.getElementById ( 'folder:' + this.full_id ).lastChild;
		folder.style.display = 'block';
		img.className = 'minus';
	};
	// }}}
	// {{{ refresh ()
	this.refresh = function ()
	{
		var l, s, folder, n;

		l = this._nodes;
		s = '';

		folder = document.getElementById ( 'folder:' + this.full_id ).lastChild;
		
		for ( n = 0; n < l; n ++ ) s += this.list [ n ].render ();

		folder.innerHTML = s;
	};
	// }}}

	this._selected	   = 0; // Numero di nodi selezionati
	this._nodes	   = 0; // Numero di nodi figli

	// {{{ _add_node ( parent, child_status )
	this._add_node = function ( parent, child_status )
	{
		if ( ! parent ) return;

		var img = document.getElementById ( this._mk_img_id ( parent ) );

		if ( child_status == 2 ) parent._selected ++;
		if ( parent._selected >= parent._nodes )
		{
			parent._selected = parent._nodes;

			if ( parent.status != 2 )
			{
				parent.status = 2;
				this._add_node ( parent.parent, parent.status );
			}
		} else {
			parent.status = 1;
			this._add_node ( parent.parent, parent.status );
		}

		if ( img ) img.className = parent.tree.status_img [ parent.status ];
	};
	// }}}
	// {{{ _del_node ( parent, child_status )
	this._del_node = function ( parent, child_status )
	{
		if ( ! parent ) return;

		var img = document.getElementById ( this._mk_img_id ( parent ) );

		if ( child_status == 0 ) parent._selected --;
		if ( parent._selected <=  0 )
		{
			parent._selected = 0;
			if ( parent.status != 0 )
			{
				parent.status = 0;
				this._del_node ( parent.parent, parent.status );
			}
		} else {
			if ( parent.status != 1 ) this._del_node ( parent.parent, parent.status );
			parent.status = 1;
		}

		if ( img ) img.className = parent.tree.status_img [ parent.status ];
	};
	// }}}
	// {{{ _mk_img_id ( n )
	this._mk_img_id = function ( n )
	{
		return "img:" + n.tree.id + ":" + n.id;
	};
	// }}}
	// {{{ _mk_chkbox ( n, is_folder )
	this._mk_chkbox = function ( n, is_folder )
	{
		if ( ! n.tree.show_checkbox ) return '';
		if ( is_folder && ! n.tree.show_folder_checkbox ) return '<div class="space"></div>';

		var s = '';

		if ( ! is_folder ) s += '<div class="space"></div>';

		s += '<div id="' + this._mk_img_id ( n ) + '"  class="' + n.tree.status_img [ n.status ] + '" ';
		s += ' onclick="OS3Tree.node_select(\'' + n.tree.id + '\', \'' + n.id + '\' )" ';
		s += '><\/div>';


		return s;
	};
	// }}}
	// {{{ _mk_onclick ( n )
	this._mk_onclick = function ( n ) 
	{
		if ( ! n.onclick ) return n.text;

		return '<a href="javascript:' + n.onclick + '(\'' + n.tree.id + '\', \'' + n.id + '\')">' + n.text + '<\/a>';
	};
	// }}}
	// {{{ _mk_events ( n )
	this._mk_events = function ( n )
	{
		var s = '', id;
		// var padding = 11;
		var class_name;

		// if ( this.tree.show_checkbox ) padding += 11;
		// if ( ! n._is_folder ) s += '<div class="full"></div>';
		if ( n.is_selected )
			class_name = "sel";
		else
			class_name = "norm";

		s += '<div '

		id = this.tree.id + ":" + this.id;

		s += ' id="' + id + '" ';

		s += " onmouseover=\"OS3Tree.evt(this,'hover')\"";
		s += " onmouseout=\"OS3Tree.evt(this,'out')\"";
		s += " onmousedown=\"OS3Tree.evt(this,'btn_down')\"";
		s += " onmouseup=\"OS3Tree.evt(this,'btn_up')\"";
		s += " onclick=\"OS3Tree.evt(this,'click')\"";
		s += " ondblclick=\"OS3Tree.evt(this,'dblclick')\"";

		// s += ' class="' + class_name + '" style="padding-left: ' + padding + 'px;">' + this._mk_onclick ( this );
		s += ' class="' + class_name + '">' + this._mk_onclick ( this );

		s += '<\/div>';

		return s;
	};
	// }}}
};
// }}}


var OS3Tabs = {};
// OS3Tabs._events = {};
OS3Tabs._int_events = {};
OS3Tabs._instances = {};

OS3Tabs._int_events [ 'hover' ] = function ( tabs, div )
{
	if ( tabs._curr_tab ) tabs._curr_tab.className = ( tabs._curr_tab == tabs._curr_tab_sel ? "sel" : "tab" );
	div.className = "tab_hover";
	tabs._curr_tab = div;
};

OS3Tabs._int_events [ 'out' ] = function ( tabs, div )
{
 	div.className = ( div == tabs._curr_tab_sel ? "sel" : "tab" );
};

OS3Tabs._int_events [ 'btn_down' ] = function ( tabs, div )
{
 	div.className = "btn_down";
};

OS3Tabs._int_events [ 'btn_up' ] = function ( tabs, div )
{
 	div.className = "btn_up";
};

OS3Tabs._int_events [ 'click' ] = function ( tabs, div )
{
	var d = tabs._tabs_ref [ div.id ];

	if ( ! d )
	{
		d = document.getElementById ( tabs._tabs_names_ref [ div.id ] );
		if ( d ) 
			tabs._tabs_ref [ div.id ] = d;
		else
		{
			console.warn ( "OS3Tabs: div: %s does not exist.", tabs._tabs_names_ref [ div.id ] );
			return;
		}
	}

	if ( ( tabs._curr_tab_sel ) && ( tabs._curr_tab_sel == tabs._curr_tab ) ) return;

	if ( tabs._curr_tab_sel ) tabs._curr_tab_sel.className = 'tab';

	tabs._curr_tab_sel = tabs._curr_tab;
	if ( tabs._curr_div_shown ) tabs._curr_div_shown.style.display = 'none';

	d.style.display = 'block';

	tabs._curr_div_shown = d;
	tabs._curr_tab.className = 'sel';
};

/*
This function is the event dispatcher
It takes:
	
	- event_name:	- Name of the event
	- instance	- Name of the instance
	- group_name	- Name of the group which is firing the event
	- pos		- Tab position which is firing the event
*/
OS3Tabs.evt = function ( div, event_name, instance, group_name, pos )
{
	if ( div._disabled ) return;

	var tabs = OS3Tabs._instances [ instance ];

	if ( tabs._blocked_events [ event_name ] ) return;
	if ( OS3Tabs._int_events [ event_name ] ) OS3Tabs._int_events [ event_name ] ( tabs, div );
	if ( tabs._events [ event_name ] ) tabs._events [ event_name ] ( tabs, event_name, div, tabs._curr_div_shown, pos );

	// console.debug ( "Event: %s - instance: %s - group: %s, pos: %d", event_name, instance, group_name, pos );
};

OS3Tabs.instance = function ( prefix )
{
	this._prefix  = prefix;
	this._events  = {}; 
	this._blocked_events = {};		// Events that should not be called
	this._tabs    = { 'default' : [] };
	this._tabs_ref = {};
	this._tabs_names_ref = {};
	this._divs_ref = {};
	this._group_names = [ 'default' ];	// Group names (in order)

	this._curr_group = this._tabs [ 'default' ];
	this._curr_group_name = 'default';

	this.tab_width = 0;
	this.tab_height = 0;

	this.render = function ()
	{
		var t, l = this._group_names.length;
		var grp;
		var s = '', ss;
		var header;
		var style = '';
		var rows = 0;

		for ( t = 0; t < l; t ++ )
		{
			grp = this._tabs [ this._group_names [ t ] ];
			if ( ! grp.length ) continue;
			rows ++;
			s += this._render_grp ( grp, this._group_names [ t ] );
		}

		header = document.getElementById ( this._prefix + '_header' );

		if ( ! header )
		{		
			console.warn ( "OS3Tabs: ERROR: Could not find: %s div for headers", this._prefix + "_header" );
			return;
		}
		if ( this.tab_height ) header.style.height = this._calc_header_height ( rows );

		header.innerHTML = s;
	};

	this._calc_header_height = function ( rows )
	{
		var split = this.tab_height.split ( /(mm|px|pt|ex|em|%)/i );
		if ( split.length < 2 ) return "";

		var v = parseInt ( split [ 0 ] );
		var mis = split [ 1 ];
		var res = ( v * rows ) + mis;

		return res;
	};

	this.set_tab_title = function ( title, group_name, pos )
	{
		var id = this._mk_tab_id ( this._prefix, group_name, pos );
		var d = document.getElementById ( id );

		d.innerHTML = title;
	};

	this.block_event = function ( event_name, mode )
	{
		if ( mode === undefined ) mode = true;
		this._blocked_events [ event_name ] = mode;
	};

	this._render_grp = function ( grp, grp_name )
	{
		var t, l, s = '', events, events_meta, id, style = '';
		var gname;

		l = grp.length;

		s += '<div id="' + this._mk_tab_row_id ( this._prefix, grp_name ) + '" class="row" >';

		if ( this.tab_width ) style += 'width: ' + this.tab_width;

		if ( style ) style = ' style="' + style + '" ';

		events_meta = "'" + this._prefix + "','" + grp_name + "'";
		for ( t = 0; t < l; t ++ )
		{
			events  = "onmouseover=\"OS3Tabs.evt(this,'hover'," + events_meta + "," + t + ")\" ";
			events += "onmouseout=\"OS3Tabs.evt(this,'out'," + events_meta + "," + t + ")\" ";
			events += "onmousedown=\"OS3Tabs.evt(this,'btn_down'," + events_meta + "," + t + ")\" ";
			events += "onmouseup=\"OS3Tabs.evt(this,'btn_up'," + events_meta + "," + t + ")\" ";
			events += "onclick=\"OS3Tabs.evt(this,'click'," + events_meta + "," + t + ")\" ";
			events += "ondblclick=\"OS3Tabs.evt(this,'dblclick'," + events_meta + "," + t + ")\" ";
			id=' id="' + this._mk_tab_id ( this._prefix, grp_name, t ) + '" ';
			s += '<div class="tab" ' + id + events + style + '>' + grp [ t ] + '<\/div>';
		}
		s += '<\/div>';

		return s;
	}

	this._mk_tab_row_id = function ( prefix, grp_name )
	{
		return prefix + ":" + grp_name + ":tab_row";
	};

	this._mk_tab_id = function ( prefix, grp_name, pos )
	{
		return prefix + ":" + grp_name + ":" + pos;
	};

	this.set_event = function ( evt_name, cback )
	{
		this._events [ evt_name ] = cback;
	};

	this.clear = function ()
	{
		this._tabs    = { 'default' : [] };
		this._tabs_ref = {};
		this._tabs_names_ref = {};
		this._divs_ref = {};
		this._group_names = [ 'default' ];	// Group names (in order)
		this._curr_group = this._tabs [ 'default' ];
		this._curr_group_name = 'default';
	};

	// {{{ set_group ( group_name )
	this.set_group = function ( group_name )
	{
		if ( ! this._tabs [ group_name ] )
		{
			this._group_names.push ( group_name );
			this._tabs [ group_name ] = [];
		}

		this._curr_group = this._tabs [ group_name ];
		this._curr_group_name = group_name;
	};
	// }}}
	// {{{ add ( title, div_name )
	this.add = function ( title, div_name )
	{
		var pos = this._curr_group.length;
		var id = this._mk_tab_id ( this._prefix, this._curr_group_name, pos );

		this._curr_group.push ( title );
		this._tabs_ref [ id ] = null; // document.getElementById ( div_name );
		this._tabs_names_ref [ id ] = div_name;

		this._divs_ref [ div_name ] = id;
	};
	// }}}

	this.send_event = function ( div_name, evt )
	{
		var id = this._divs_ref [ div_name ];
		var div = document.getElementById ( id );

		this._curr_tab = div;
		OS3Tabs.evt ( div, evt, this._prefix );
	};

	this.enable_tab = function ( div_name, enable )
	{
		var id = this._divs_ref [ div_name ];
		var div = document.getElementById ( id );

		if ( ! div [ "_disabled" ] && enable ) return;
		if ( div [ "_disabled" ] && ! enable ) return;

		if ( enable )
		{
			div._disabled = false;
			div.className = "tab";
		}
		else
		{
			div._disabled = true;
			div.className = "disabled";
		}
	};


	OS3Tabs._instances [ this._prefix ] = this;
};




function SmoothRoll ( table_id )
{
	this._container = document.getElementById ( table_id );
	this._items = [];

	this._start = 0;
	this._rows_to_show = 0;
	this._stopped = true;
	this._scrollable = true;

	this.min_row_height = 10;
	this.scroll_speed = 1;
	this.scroll_time = 100;

	this.clear = function ()
	{
		if ( this._interval ) clearInterval ( this._interval );

		this._stopped = true;
		this._scrollable = true;
		this._start = 0;
		this._rows_to_show = 0;
		this._interval = null;

		this._items = [];
	};

	this.init = function ()
	{
		this._start = 0;
		this._len = this._items.length;

		this._first_render ();
	};

	this.add_item = function ( txt )
	{
		this._items.push ( txt );
	};

	this.start = function ()
	{
		var _obj = this;

		if ( ! this._stopped ) return;

		this._stopped = false;
		this._interval = setInterval ( function () { _obj.scroll ( - _obj.scroll_speed ); }, this.scroll_time );
	};

	this.stop = function ()
	{
		if ( this._interval ) clearInterval ( this._interval );
		this._stopped = true;
	};

	this._first_render = function ()
	{
		var t, i;
		var tr, td, row, el;
		var _obj = this;

		this._table = document.createElement ( 'table' );
		//this._table.style.position = "relative";
		this._table.style.display = "inline-block";
		this._table.style.top = "0";
		this._table.style.left = "0";
		this._table_body = document.createElement ( 'tbody' );

		this._table.appendChild ( this._table_body );
		this._container.appendChild ( this._table );

		this._rows_to_show = 0;

		this._table.onmouseover = function () { _obj.stop (); };
		this._table.onmouseout  = function () { _obj.start (); };
		this._table.style.width = this._container.clientWidth + "px";

		while ( ( this._table.clientHeight - this.min_row_height ) < this._container.clientHeight  )
		{
			el = this._rows_to_show ++;
			if ( el >= this._len ) break;
			
			row = this._items [ el ];

			tr = document.createElement ( 'tr' );
			td = document.createElement ( 'td' );
			tr.appendChild ( td );

			td.innerHTML = row;

			this._table_body.appendChild ( tr );

			this._start ++;
			//console.debug ( this._table.clientHeight );
		}

		if ( this._rows_to_show > this._len ) this._scrollable = false;

		this._rows_to_show -= 1;
		this._table_pos = 0;

		this._calc_row_height ();
	};

	this._calc_row_height = function ()
	{
		this._row_height = this._table_body.firstChild.clientHeight;
	};

	this.scroll = function ( delta )
	{
		if ( ! this._scrollable ) return;

		this._table_pos += delta;

		// FIXME: forse c'e' da controllare in modo differente per
		// gli offset superiori e quelli inferiori
		if ( Math.abs ( this._table_pos ) > ( this._row_height + Math.abs ( delta )  ) )
		{
			this._model_scroll_up ();
		}

		this._table.style.marginTop = this._table_pos + "px";
	};

	this._model_scroll_up = function ()
	{
		var t, data_row;
		var pos;
		// Rimuovo la prima riga
		var row = this._table_body.firstChild;

		if ( ! row || ! row.firstChild ) return;

		// Mi sposto con l'offset di visualizzazione di un elemento
		pos = this._start = ( this._start + 1 ) % this._len;

		// prendo la prossima row
		data_row = this._items [ pos ];

		row.firstChild.innerHTML = data_row;

		this._table_body.removeChild ( row );
		this._table.style.marginTop = "0px";
		this._table_body.appendChild ( row );
		this._table_pos = 0;
		this._calc_row_height ();

		// console.debug ( "SCROLL" );
	};
}


/*
 * liwe.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */

/*
 *
 *	2009-04-16:	- Added the ``strong_debug`` flag to the liwe base class (default to ``false``).
 *
 *
 *	2009-03-06:	- $() and $v() are now here and not in utils.js
 *			- $() now can have a second optional argument to set the innerHTML.
 */

// PUBLIC: liwe
var liwe = {};
liwe.utils = {};
liwe.fx = {};

liwe.strong_debug = false;

// Library base
liwe._libbase = "";

liwe.ajax_url = "/ajax.php";

// Try to be compatible with other browsers
// Only use firebug logging when available
// (this code is a modified version of firebugx.js, written
// by Joe Hewitt)
if ( ! window [ "console" ] ) window.console = {};

try
{
	liwe._console = window.console [ "debug" ];
} catch ( e ) {
	window.console = {};
	liwe._console = null;
}

if ( ! liwe._console )
{
	var names = [ "log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", 
		      "timeEnd", "count", "trace", "profile", "profileEnd" ];

	for ( var i = 0; i < names.length; ++i )
		window.console [ names [ i ] ] = function() {};
}

liwe.set_libbase = function ( libbase_url )
{
	if ( libbase_url )
	{
		liwe._libbase = libbase_url;
		return;
	}

	var scripts = document.getElementsByTagName ( "script" );
	var l = scripts.length;
	var t, s, pos, path = "";

	for ( t = 0; t < l; t ++ )
	{
		s = scripts [ t ].src;

		if ( ! s ) continue;

		if ( s.match ( /liwe.*js/ ) )
		{
			s = s.replace ( /.*os3phplib.send_gzip.php.fname=/, "" );
			pos = s.lastIndexOf ( "/" );
			if ( pos != -1 ) path = s.slice ( 0, pos + 1 );
		}
	}

	if ( path ) liwe._libbase = path;
	else liwe._libbase = "/os3jslib";
};

liwe.set_libbase ();

// =============================================================================
// UTILS
// =============================================================================
liwe.utils.WAIT_TIMEOUT = 2000; // Milli seconds
liwe.utils.WAIT_TIME = 50; // Milli seconds

liwe.utils.wait_def = function ( name, cback, vars, time )
{
	if ( ! liwe.utils.is_def ( name ) ) 
	{
		if ( ! time ) time = 0;
		if ( time > liwe.utils.WAIT_TIMEOUT )
		{
			if ( liwe.strong_debug ) alert ( "Failed: " + name );
			return;
		}

		setTimeout ( function () { liwe.utils.wait_def ( name, cback, vars, time + liwe.utils.WAIT_TIME ); }, liwe.utils.WAIT_TIME );
        } else {
		if ( typeof ( cback ) != 'object' ) cback ( vars );
	}
};

liwe.utils.append_js = function ( script_file )
{
        var head = document.getElementsByTagName ( "head" ) [ 0 ];
        var new_script = document.createElement ( "script" );

        new_script.src = script_file;
        new_script.type = "text/javascript";
        head.appendChild ( new_script );
};


liwe.utils.is_def = function ( name )
{
	var is_def = false;
	var l;

	if ( typeof name == "string" )
	{
		var items = name.split ( "." );
		var s = '';

		s = items [ 0 ];
		l = items.length;

		for ( t = 0; t < l; t ++ )
		{
			// console.debug ( "Check for: " + s );
			eval ( "is_def = ( typeof ( " + s + " ) != 'undefined' );" );
			if ( ! is_def ) return false;
			if ( ! items [ t + 1 ] ) break;

			s += "." + items [ t + 1 ];
		}
		return true;
	}

	var t;
	var n;

	l = name.length;

	for ( t = 0; t < l; t ++ )
	{
		n = name [ t ];
		eval ( "is_def = ( typeof ( " + n + " ) != 'undefined' );" );

		if ( ! is_def ) return false;
	}

	return true;
};

liwe.browser = {};

liwe.browser.version = navigator.appVersion;
liwe.browser.has_dom = document.getElementById ? 1 : 0;
liwe.browser.ie = ( typeof window [ "ActiveXObject" ] != "undefined" ); //window.ActiveXObject != null );
liwe.browser.gecko = ( navigator.userAgent.toLowerCase().indexOf ( "gecko" ) != -1 ) ? 1 : 0;
liwe.browser.opera = ( navigator.userAgent.toLowerCase().indexOf ( "opera" ) != -1 ) ? 1 : 0;

// =============================================================================
// POSTLOADER
// =============================================================================

liwe.postload = {};

// The time (in millis) before a specified file is timedout
liwe.postload.WAIT_TIMEOUT = 30000; // 30 seconds (time is in millis)

// Millis to check for a specified file
liwe.postload.WAIT_TIME = 50; // 50 milli seconds
liwe.postload.events = {};

// This event is fired when a SINGLE SCRIPT has been loaded
// cback: script_loaded ( script_name )
liwe.postload.events [ 'script_load' ] = null;	

// This event is fired whenever PostLoader thinks it is good to
// update your load status info
// cback: script_update ( items_loaded, tot_items )
liwe.postload.events [ 'update' ] = null;

// This event is fired when PostLoader has finished to load
// ALL scripts defined.
// cback: script_completed ()
liwe.postload.events [ 'completed' ] = null;

/* FILES fields values:
#
#	0 - priority
#	1 - file name
#	2 - check_for
#	3 - cback
#	4 - vars
#	5 - is loaded
*/
liwe.postload._files = [];
liwe.postload._loaded_files = 0;

liwe.postload.add = function ( fname, check_for, pri, cback, vars )
{
	if ( ! pri ) pri = 1;

	if ( liwe.utils.is_def ( check_for ) ) return;

	liwe.postload._files.push ( [ pri, fname, check_for, cback, vars, 0 ] );
};

liwe.postload.load = function ()
{
	var t, l, itm;

	liwe.postload._files.sort ();

	l = liwe.postload._files.length;

	// keep count of loaded files
	liwe.postload._loaded_files = 0;

	for ( t = 0; t < l; t ++ )
	{
		itm = liwe.postload._files [ t ];
		// Files already in memory are skipped
		if ( itm [ 5 ] ) liwe.postload._loaded ( t ); 

		liwe.utils.append_js ( itm [ 1 ] );
		liwe.utils.wait_def ( itm [ 2 ], liwe.postload._loaded, t );
	}
};

liwe.postload._loaded = function ( pos )
{
	liwe.postload._loaded_files += 1;

	var itm = liwe.postload._files [ pos ];

	itm [ 5 ] = 1;

	if ( liwe.postload.events [ 'script_loaded' ] )
		liwe.postload.events [ 'script_loaded' ] ( itm [ 1 ] );

	if ( itm [ 3 ] ) itm [ 3 ] ( itm [ 4 ] );

	if ( liwe.postload.events [ 'update' ] )
		liwe.postload.events [ 'update' ] ( liwe.postload._loaded_files, liwe.postload._files.length );

	if ( ! ( liwe.postload._files.length - liwe.postload._loaded_files ) )
		if ( liwe.postload.events [ 'completed' ] ) liwe.postload.events [ 'completed' ] ();
};


liwe._clear_dom = function ( e )
{
	var i, l = e.childNodes.length;
	for ( i = 0; i < l; i ++ )
	{
		var el = e.childNodes [ i ];

		//PULIZIA
		var v;
		for ( v in el )
		{
			if ( v.charAt ( 0 ) != "_" ) continue;

			console.debug ( v );

			if ( v == "_listeners" )
			{
				var listeners = [].concat ( el [ v ] );
				var vi, vl = listeners.length;
				for ( vi = 0; vi < vl; vi ++ )
				{
					var lid = listeners [ vi ];
					var rec = _all [ lid ];
					if ( rec ) liwe.events.del ( rec.target, rec.type, rec.listener );
				}
			}

			try
			{
				el [ v ] = null;
			}
			catch (e)
			{
			}
		} 

		liwe._clear_dom ( el );
	}
};


function $ ( name, inner_html, warn )
{
	var e = document.getElementById ( name );

	if ( ! e ) 
	{
		if ( warn ) console.warn ( "Element: %s not found", name );
		return null;
	}

	if ( typeof inner_html == "undefined" )
		return e;

	// liwe._clear_dom ( e );

	e.innerHTML = inner_html;
	return e;
}

function $v ( name, def_val )
{
	var d = document.getElementById ( name );
	if ( ! d ) return def_val;

	return d.value;
}



/*
 * object_enh.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */
// PUBLIC: iterate
Object.prototype.iterate = function ( cback )
{
	var k;

	for ( k in this )
	{
		if ( typeof ( this [ k ] ) == 'function' ) continue;
		cback ( this [ k ], k );
	}
};

Object.prototype.keys = function ()
{
	var res = [];

	this.iterate ( function ( v, k ) { res.push ( k ); } );

	return res;
};

Object.prototype.values = function ()
{
	var res = [];

	this.iterate ( function ( v ) { res.push ( v ); } );

	return res;
};

// PUBLIC: debugDump
Object.prototype.debugDump = function ( dump_funcs, lvl )
{
	var s = '';
	var k;

	if ( ! lvl ) lvl = '';

	for ( k in this )
	{
		if ( typeof ( this [ k ] ) == 'function' ) 
		{
			if ( dump_funcs ) s += lvl + 'function ' + k + ' ()\n';
		} else {
			if ( typeof ( this [ k ] ) == 'object' )
			{
				s += lvl + k + ":\n" + this [ k ].debugDump ( dump_funcs, lvl + "-----  " );
			} else {
				s += lvl + k + ": " + this [ k ] + "\n";
			}
		}
	}

	return s;
};

// PUBLIC: count
Object.prototype.count = function ()
{
	var k;
	var res = 0;
	
	for ( k in this )
	{
		if ( ( typeof ( this [ k ] ) == 'function' ) ) continue;
		res ++;
	}

	return res;
};

// PUBLIC: get
Object.prototype.get = function ( name, def_val )
{
	var res = this [ name ];

	if ( typeof ( res ) == 'undefined' ) return def_val;

	return res;
};

// PUBLIC: getName
Object.prototype.getName = function ()
{
	if ( this.name ) return this.name;

	var s = "" + this;
	var v = s.match ( /^function  *([_a-zA-Z$][_a-zA-Z0-9$]*)  *.*/ ); //new RegExp ( "^function  *(.*) *\(" ) )

	if ( ! v ) return '';

	return v [ 1 ];
};

// PUBLIC: inherits
Object.prototype.inherits = function ( p )
{
	var name;

	this.parent = p;
	for ( name in p )
	{
		if ( typeof this [ name ] == 'undefined' ) this [ name ] = p [ name ];
	}
};


// PUBLIC: clone
Object.prototype.clone = function ()
{
        var res ={};
        var name;

        for ( name in this ) res [ name ] = this [ name ];

        return res;
};




/*
 * array_enh.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */
// PUBLIC: toSourceString
Array.prototype.toSourceString = function ( include_funcs )
{
	var s = '{';
	var k, v;
	var is_first = true;

	for ( k in this )
	{
		if ( ( typeof ( this [ k ] ) == 'function' ) && ( ! include_funcs ) ) continue;

		if ( ! is_first ) s += ", ";
		s += "'" + k + "' : '" + this [ k ] + "'";
		is_first = false;
	}

	s += "}";

	return s;
};

// PUBLIC: count
Array.prototype.count = function ()
{
	var k;
	var res = 0;
	
	for ( k in this )
	{
		if ( ( typeof ( this [ k ] ) == 'function' ) ) continue;
		if ( k == '__arr' ) continue;
		res ++;
	}

	return res;
};

// PUBLIC: fromObject
Array.fromObject = function ( a, include_funcs )
{
	var arr = new Array ();
	var k, v;

	for ( k in a ) 
	{
		if ( ( ! include_funcs ) && ( typeof ( a [ k ] ) == 'function' ) ) continue;

		arr [ k ] = a [ k ];
	}

	return arr;
};

// PUBLIC: fromForm
Array.fromForm = function ( form_id, max_depth )
{
	var arr = new Array ();
	var f = document.getElementById ( form_id );
	
	if ( ! max_depth ) max_depth = 0;

	_form_add_elems ( f, arr, max_depth, 0 );

	return arr;
};

// PUBLIC: find
Array.prototype.find = function ( key, case_sens, include_funcs )
{
	var k;
	var c = 0;

	if ( ! case_sens ) key = key.toLowerCase ();

	for ( k in this )
	{
		if ( ( typeof ( this [ k ] ) == 'function' ) && ( ! include_funcs ) ) continue;

		k = this [ k ];
		if ( ! case_sens ) k = k.toLowerCase ();
		if ( k == key ) return c;
			
		c++;
	}

	return -1;
};

// PUBLIC: toObject
Array.toObject = function ( arr )
{
	var res = {};
	var k;

	for ( k in arr )
	{
		if ( ( typeof ( arr [ k ] ) == 'function' ) ) continue;
		
		res [ k ] = arr [ k ];
	}

	return res;
};

// PUBLIC: del
Array.prototype.del = function ( pos, how_many )
{
	if ( ! how_many ) how_many = 1;

	var to_del = Array();

	var start = pos;
	var stop = pos + how_many;

	var k, count = -1, i;
	for ( k in this )
	{
		count++;

		if ( count < start ) 	  continue;
		else if ( count >= stop ) break;

		to_del.push ( k );
	}

	for ( i = 0; i < to_del.length; i++ )
	{
		delete this [ to_del [ i ] ];
	}
};

// PUBLIC: delKey
Array.prototype.delKey = function ( k )
{
	delete this [ k ];
};


if ( Array.prototype.indexOf == null )
{
	Array.prototype.indexOf = function ( item )
	{
		var t, l = this.length;
		for ( t = 0; t < l; t ++ )
			if ( this [ t ] == item ) return t;
		return -1;
	};
}


function _form_add_elems( node, arr, max_depth, curr_depth )
{
	var inps, sels, txts, t, n;

	inps = node.getElementsByTagName ( "input" );
	sels = node.getElementsByTagName ( "select" );
	txts = node.getElementsByTagName ( "textarea" );

	for ( t = 0; t < inps.length; t ++ )
	{
		n = inps [ t ];
		if ( ( ( n.type == 'radio' ) || ( n.type == 'checkbox' ) ) && ( n.checked == false ) ) continue;
		arr [ n.name ] = n.value;
	}

	for ( t = 0; t < sels.length; t ++ ) arr [ sels [ t ].name ] = sels [ t ].value;
	for ( t = 0; t < txts.length; t ++ ) arr [ txts [ t ].name ] = txts [ t ].value;
}


/* Implement array.push for browsers which don't support it natively. 
   Copyright 2005 Mark Wubben 
*/
if ( Array.prototype.push == null )
{
	Array.prototype.push = function() 
	{
		for( var i = 0; i < arguments.length; i++ )
			this [ this.length ] = arguments [ i ];

		return this.length;
	};
}



/*
 * string_enh.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 *
 *  2009-07-09: Fix htmlEntities now skips ";" "="
 *  2009-06-16: Fix htmlEntities now works again and skips "<" ">", '"', "'", "\r", "\n"
 *  2009-04-16: Fix htmlEntities RegExp to skip "-", "(" and ")"
 *  2009-01-14:	Added the String.buffer class
 */

// PUBLIC: startsWith
String.prototype.startsWith = function ( str )
{
	if ( this.substr ( 0, str.length ) == str ) return ( true );
	
	return ( false );
};

// PUBLIC: endsWith
String.prototype.endsWith = function ( str )
{
	if ( this.substr ( this.length - str.length ) == str ) return ( true );
	
	return ( false );
};

// PUBLIC: buffer
String.buffer = function ()
{
	this._buf = [];

	this.add = function ()
	{
		var t, l = arguments.length;

		for ( t = 0; t < l; t ++ )
			this._buf.push ( arguments [ t ] );

		return this;
	};

	this.get = function ( sep )
	{
		if ( ! sep ) sep = "";

		return this._buf.join ( sep );
	};

	this.length = function () { return this._buf.length; };

	this.clear = function () { this._buf = []; };

	this.toString = function () { return this.get ( "" ); };
};

String._re_htmlentities_invalid = /([^a-zA-Z0-9,.:;=!?+\/_ |@-\\(\\)<>\n\r'"&#-])/g;
String.prototype.htmlEntities = function ()
{
        function _ch ( m )
        {
                return ( "&#" + m.charCodeAt ( 0 ) + ";" );
        }

        return this.replace ( String._re_htmlentities_invalid, _ch );
};

String._re_entities_decl = /&#([^;]*);/g;
String.prototype.entities2char = function ()
{
	function _ch ( m, p1 )
	{
		return String.fromCharCode ( parseInt ( p1, 10 ) );
	}

	return this.replace ( String._re_entities_decl, _ch );
};


// PUBLIC: join
String.prototype.join = function ( arr )
{
	var l = arr.length;
	var k, t;
	var s = '';
	var is_first = true;

	for ( t = 0; t < l; t ++ )
	{
		if ( typeof ( arr [ t ] ) == 'function' ) continue;
		if ( ! is_first ) s += this;
		s += arr [ t ];
		is_first = false;
	}

	return s;
};

// PUBLIC: LStrip
String.prototype.LStrip = function ()
{
	return this.replace ( /^\s+/, "" );
};

// PUBLIC: RStrip
String.prototype.RStrip = function ()
{
	return this.replace ( /\s+$/, "" );
};

// PUBLIC: Strip
String.prototype.Strip = function () { return this.replace ( /^\s+|\s+$/,"" ); };

// PUBLIC: isUpper
String.prototype.isUpper = function () 
{
	var l = this.length;
	var c, t;

	if ( ! l ) return false;

	for ( t = 0; t < l; t ++ )
	{
		c = this [ t ].toUpperCase ();
		if ( c != this [ t ] ) return false;
	}

	return true;
	
};

// PUBLIC: isLower
String.prototype.isLower =  function () 
{
	var l = this.length;
	var c, t;

	if ( ! l ) return false;

	for ( t = 0; t < l; t ++ )
	{
		c = this [ t ].toLowerCase ();
		if ( c != this [ t ] ) return false;
	}

	return true;
	
};

String.basename = function ( s, sep )
{
	if ( ! sep ) sep = "/";

	return s.split ( sep ).slice ( -1 );
};

String.dirname = function ( s, sep )
{
	if ( ! sep ) sep = "/";

	return sep.join ( ( s.split ( sep ) ).slice ( 0, -1 ) );
};

// PUBLIC: format
String.format = function ()
{
	function re_replace ( v )
	{
		var m = v.match ( _re_replace );
		var val = args [ ++count ];

		return _string_re_replace ( m, val );
	}

	var _re_replace = /%([0+#-]*)([0-9]*)(\.{0,1})([0-9]*)([dsqm])/;
	var re = /%[0+#-]*[0-9]*\.{0,1}[0-9]*[dsqm]/gi;
	var fmt = arguments [ 0 ];	// The first param is the string format
	var count = 0;
	var args = arguments;

	return fmt.replace ( re, re_replace );
};

// PUBLIC: formatDict
String.formatDict = function ( fmt, dict )
{
	function re_replace ( v )
	{
		var m = v.match ( _re_replace );
		var val = dict [ m [ 1 ] ];
		var p1 = m.shift ();

		m.shift ();
		m.unshift ( p1 );
		return _string_re_replace ( m, val );
	}

	var _re_replace = /%\(([^)]*)\)([0+#-]*)([0-9]*)(\.{0,1})([0-9]*)([dsqm])/;
	var re = /%\([a-z0-9_-]+\)[0+#-]?[0-9]*\.?[0-9]*[dsqm]/gi;

	if ( fmt == "" ) return "";

	if ( ! fmt )
	{
		console.warn ( "No FMT for the following dict: %o", dict );

		return "";

		// fmt = "";
	}
	
	return fmt.replace ( re, re_replace );
};

function _string_re_replace ( matches,  value )
{
	var flags = matches [ 1 ];
	var width = ( matches [ 2 ] ? parseInt ( matches [ 2 ] ) : 0 );
	var precision = ( matches [ 4 ] ? parseInt ( matches [ 4 ] ) : 0 );
	var type = matches [ 5 ];
	var res = '';
	var pad_char = ' ';
	var pad_left = false;
	var show_sign = false;

	if ( flags.indexOf ( '-' ) >= 0 ) pad_left = true;
	if ( flags.indexOf ( '0' ) >= 0 ) pad_char = '0';
	if ( flags.indexOf ( '+' ) >= 0 ) show_sign = true;

	if ( pad_char == '0' && pad_left ) pad_char = ' ';

	switch ( type )
	{
		case 'm':	// Money
			if ( typeof ( Money ) != 'undefined' )
			{
				res = Money.fromLongInt ( value );
			} else
				res = value;

			break;
			
		case 'd':
			res  = _string_mkpad ( true, value, precision, width, pad_char, false, pad_left, show_sign );
			break;

		case 'q':
			value = value.replace ( /'/g, "\\'" );
			// Non mettere break, deve finire al case 's'

		case 's':
			res  = _string_mkpad ( false, value, precision, width, pad_char, true, pad_left, false );
			break;
	}

	return res;
}

function _string_mkpad ( is_num, v, prec, width, pad_char, trunc, pad_left, show_sign )
{
	var sign = '';

	if ( is_num )
	{
		v = parseInt ( v );
		if ( v < 0 ) sign = '-';
		else if ( show_sign ) sign = '+';

		v = Math.abs ( v );
	}

	v = String ( v );

	if ( ! width && ! prec ) return v;

	var len, t, i;

	if ( is_num )
	{
		len = prec - v.length;
		if ( len > 0 ) for ( t = 0; t < len; t ++ ) v = "0" + v;
	}

	v = sign + v;

	len = width - v.length;
	if ( len > 0 )
	{
		for ( t = 0; t < len; t ++ )
			v = ( pad_left ? v + pad_char : pad_char + v );
	}

	if ( ! is_num && prec )
	{
		return v.slice ( 0, prec );
	}

	return  v;
}



/*
 * ajax_manager.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 *
 *       2009-05-04:	ADD: new static function AJAXManager.handle_easy
 *
 *       2009-01-24:	ADD: this.cbacks for:
 *
 *       			- serialize	serialize data
 *       			- req-start	request start
 *       			- req-end	request end
 *       			- req-error	request error
 *
 *       		ENH: AJAX Manager is now more "liwe"ized
 *       		ENH: removed String and Array enhancement dependencies
 *
 *       		DEP: error_handler has been DEPRECATED
 *       		DEP: start_req_handler has been DEPRECATED
 *       		DEP: end_req_handler has been DEPRECATED
 *
 */

// PUBLIC: ajax_response

// PUBLIC: AJAXManager
// PUBLIC  easy
// PUBLIC: request
function AJAXManager ()
{
	this._reqs = [];
	this._in_list = 0;
	this._in_abort = false;

	this.url = liwe.ajax_url;

	this.cbacks = {	"serialize" : null, 
			"req-start" : null, 
			"req-end" : null, 
			"req-error" : null 
		      };

	// {{{ request ( url, vars, callback, easy, sync )
	this.request = function ( url, vars, callback, easy, sync ) 
	{
		var req = null;
		var id = '';
		var t;
		var res = '';
		var self = this;
		var s;

		if ( ! url ) url = this.url;

		if ( vars ) 
		{
			for ( t in vars ) 
			{
				if ( typeof ( vars [ t ] ) == 'undefined' ) continue;
				if ( typeof ( vars [ t ] ) == 'function' ) continue;
				if ( ( typeof ( vars [ t ] ) == 'object' ) && ( vars [ t ] == null ) ) continue;

				/*
					This is a hack for IE, since it considers functions as objects (!!!)
				*/
				if ( typeof ( vars [ t ] ) == 'object' )
				{
					s = vars [ t ].toString ();
					if ( s.match ( /^function/ ) ) continue;
				}

				if ( vars [ t ] == '__arr' ) continue;

				if ( ( typeof ( vars [ t ] ) == 'string' ) || ( typeof ( vars [ t ] ) == 'number' ) )
				{
					res += t + "=" + this._ajax_escape ( vars [ t ] ) + "&";
				} else {
					try 
					{
						res += t + "=" + this._ajax_escape ( vars [ t ].toJSONString() ) + "&";
					} catch ( e ) {
						res += t + "=" + this._ajax_escape ( vars [ t ] ) + "&";
					}
				}
			}

			res = res.substr ( 0, res.length - 1 ); //  + "&";
		}

		req = this._build_req_obj ();


		// The request callback
		var _obj = this;
		if ( this.error_handler )
		{
			console.warn ( "AJAXManager.error_handler is DEPRECATED. Use cbacks [ 'req-error' ] instead." );
			req.onreadystatechange = function () { _obj._req_change ( req, callback, easy, _obj.error_handler ); };
		} else
			req.onreadystatechange = function () { _obj._req_change ( req, callback, easy, _obj.cbacks [ 'req-error' ] ); };

		var async = true;
		if ( sync ) async = false;

		// if (erroneously) the url starts with two "//", Firefox throws a security error
		url = url.replace ( /^\/\//g, "/" );

		req.open ( "POST", url, async );
		req.setRequestHeader ( 'Content-Type', 'application/x-www-form-urlencoded' );
		req.send ( res );

		if ( easy )
		{
			if ( this.start_req_handler ) 
			{
				console.warn ( "AJAXManager.start_req_handler is DEPRECATED. Use cbacks [ 'req-start' ] instead." );
				this.start_req_handler ( req );
			}

			if ( this.cbacks [ 'req-start' ] ) this.cbacks [ 'req-start' ] ( req );
		}
	};
	// }}}
	// {{{ easy ( arr, cback )
	this.easy    = function ( arr, cback ) { this.request ( null, arr, cback, true ); };
	// }}}
	// {{{ _build_req_obj ()
	this._build_req_obj = function ()
	{
		var req;

		/*@cc_on @*/
		/*@if (@_jscript_version >= 5)
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch ( E ) {
				req = false;
			}
		}
		@end @*/

		if ( ! req && typeof XMLHttpRequest != 'undefined' ) 
		{
			try {
				req = new XMLHttpRequest();
			} catch (e) {
				req=false;
			}
		}

		if ( ! req && window.createRequest ) 
		{
			try {
				req = window.createRequest();
			} catch (e) {
				req=false;
			}
		}

		/*
		if ( window.XMLHttpRequest )		// Mozilla, Safari, Konqueror, Netscape...
		{
			req = new XMLHttpRequest ();
		} else {
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {
				try {
					req = new ActiveXObject("Microsoft.XMLHTTP");
				} catch ( e ) {
					req = null;
					console.error ( "XMLHTTP Request object not available." );
				}
			}
		}

		*/

		this._reqs.push ( req );

		return req;
	};
	// }}}
	// {{{ _req_change ( req, callback, easy, err_handler )
	this._req_change = function ( req, callback, easy, err_handler )
	{
		if ( ! easy ) 
		{
			if ( callback ) callback ( req );
		} else {
			var in_abort = this._in_abort;

			// Remove the req from the Request Pool
			if ( req.readyState == 4 ) 
			{
				if ( this.end_req_handler ) 
				{
					console.warn ( "AJAXManager.end_req_handler is DEPRECATED. Use cbacks [ 'req-end' ] instead." );
					this.end_req_handler ( req );
				}

				if ( this.cbacks [ 'req-end' ] ) this.cbacks [ 'req-end' ] ( req );


				this._remove_req ( req );

				if ( in_abort ) return;

				AJAXManager.handle_easy ( req.responseText, callback, err_handler );
			}
		}
	};
	// }}}

	

	this.error_handler = null;		// DEPRECATED
	this.start_req_handler = null;		// DEPRECATED
	this.end_req_handler = null;		// DEPRECATED

	// {{{ _remove_req ( req )
	this._remove_req = function ( req )
	{
		var t, l = this._reqs.length;

		if ( this._in_list ) 
		{
			var obj = this;

			setTimeout ( function () { obj._remove_req ( req ); }, 100 );
			return;
		}

		this._in_list = 1;

		for ( t = 0; t < l; t ++ )
		{
			if ( this._reqs [ t ] == req ) break;
		}
		if ( t < l )
			this._reqs.splice ( t, 1 );

		this._in_list = 0;
	};
	// }}}
	// {{{ abort ( cback )
	this.abort = function ( cback )
	{
		var t, l = this._reqs.length;

		if ( this._in_list ) 
		{
			var obj = this;

			//console.debug ( "In list: " + this._in_list );
			setTimeout ( function () { obj.abort (); }, 100 );
			return;
		}

		this._in_list = 2;
		this._in_abort = true;

		for ( t = 0; t < l; t ++ )
		{
			try
			{
				this._reqs [ t ].abort ();
			} catch ( e ) {
			}
		}

		this._in_abort = false;
		this._in_list = 0;

		if ( cback ) cback ();
	};
	// }}}
	
	this._ajax_escape = function ( s )
	{
		if ( this.cbacks [ 'serialize' ] )
			s = this.cbacks [ 'serialize' ] ( s );

		s = escape ( s );
		s = s.replace ( /\+/g, "%2B" );
		return s;
	};
}

AJAXManager.handle_easy = function ( responseText, callback, err_handler )
{
	var resp_txt = responseText.replace ( /^\s+/, "" );

	if ( resp_txt.substr ( 0, "var ajax".length ) == 'var ajax' )
	{
		try {
			eval ( resp_txt );
			if ( ajax_response [ 'err_code' ] )
			{
				if ( ! err_handler )
				{
					if ( ajax_response [ 'err_descr' ] )
					{
						console.error ( ajax_response [ 'err_descr' ] );
						alert ( ajax_response [ 'err_descr' ] );
					} else {
						console.error ( "Generic Request error. Error code: " + ajax_response [ 'err_code' ] );
					}
				} else
					err_handler ( ajax_response );

				return;
			}
		} catch ( e ) {
			console.error ( "ERROR IN EVAL: %s - (except: %o)", responseText, e );
			return;
		}

		if ( callback && typeof ( callback ) == 'function' ) callback ( ajax_response );
	} else
		console.error ( "Request ERROR: " + responseText );
};

liwe.AJAX = new AJAXManager ();

liwe.AJAX._multi = {};
liwe.AJAX._multi_data = {};

liwe.AJAX.add = function ( name, action, dict, cback )
{
	var multi;
	var data;

	if ( ! name   ) name = "AJAX";
	if ( ! action ) action = null;


	multi = this._multi [ name ];
	if ( ! multi ) 
	{
		multi = [];
		data  = {};
	} else {
		data = this._multi_data [ name ];
	}

	if ( data [ 'running' ] ) 
	{
		console.error ( "Requests are already running for: %s", name );
		return;
	}

	multi.push ( [ action, dict, cback ] );
	this._multi [ name ] = multi;
	this._multi_data [ name ] = data;

	console.debug ( "Multi: %s - Len: %d", name, multi.length );
};

liwe.AJAX.start = function ( name, cback )
{
	var multi, data, t, l, req, func;

	multi = this._multi [ name ];
	if ( ! multi ) 
	{
		console.error ( "There is no multi group called: %s", name );
		return;
	}

	data = this._multi_data [ name ];
	data [ 'running' ] = true;
	data [ 'len' ] = multi.length;
	data [ 'count' ] = 0;

	l = multi.length;
	var i;
	for ( t = 0; t < l; t ++ )
	{
		req = multi [ t ];

		liwe.AJAX._send ( name, req, cback );
	}
};

liwe.AJAX._send = function ( name, req, cback ) 
{
	this.request ( req [ 0 ], req [ 1 ], function ( v ) { liwe.AJAX._req_cback ( name, v, req, cback ); }, true );
};

liwe.AJAX._req_cback = function ( name, v, req, cback )
{
	var multi = liwe.AJAX._multi [ name ];
	var data = liwe.AJAX._multi_data [ name ];

	if ( req [ 2 ] ) req [ 2 ] ( v );
	

	data [ 'count' ] += 1;

	if ( data [ 'count' ] == data [ 'len' ] ) 
	{
		if ( cback ) cback ();
		liwe.AJAX._multi [ name ] = null;
		liwe.AJAX._multi_data [ name ] = null;
	}
};


liwe.events = {};

if ( document.addEventListener )
{
	// W3C DOM 2 Events model
	liwe.events.add 	= function ( target, type, listener ) { target.addEventListener ( type, listener, false ); };
	liwe.events.del 	= function ( target, type, listener ) { target.removeEventListener ( type, listener, false ); };
	liwe.events.prevent 	= function ( e ) { e.preventDefault (); };
	liwe.events.stop 	= function ( e ) { e.stopPropagation(); };

	liwe.events.source  	= function ( e ) { return e.target; };
	liwe.events.keycode 	= function ( e ) { return e.which; };
} else if ( document.attachEvent ) {
	// Internet Explorer Events model

	liwe.events.add		= function ( target, type, listener )
	{
		// prevent adding the same listener twice, since DOM 2 Events ignores
		// duplicates like this
		if ( liwe.events._find ( target, type, listener) != -1 ) return;

		// _cback calls listener as a method of target in one of two ways,
		// depending on what this version of IE supports, and passes it the global
		// event object as an argument
		var _cback = function ()
		{
			var e = window.event;

			if ( Function.prototype.call )
				listener.call ( target, e );
			else {
				target._curr_listener = listener;
				target._curr_listener ( e )
				target._curr_listener = null;
			}
		};

    		// add _cback using IE's attachEvent method
    		target.attachEvent ( "on" + type, _cback );

    		// create an object describing this listener so we can clean it up later
    		var rec =
    		{
      			target: target,
      			type: type,
      			listener: listener,
      			_cback: _cback
    		};

    		// get a reference to the window object containing target
    		var targetDocument = target.document || target;
    		var targetWindow = targetDocument.parentWindow;

    		// create a unique ID for this listener
    		var listenerId = "l" + liwe.events._list_counter++;

    		// store a record of this listener in the window object
    		if ( !targetWindow._all ) targetWindow._all = {};
    		targetWindow._all [ listenerId ] = rec;

    		// store this listener's ID in target
    		if ( ! target._listeners ) target._listeners = [];
    		target._listeners [ target._listeners.length ] = listenerId;

    		if ( ! targetWindow._unload_added )
    		{
      			targetWindow._unload_added = true;
      			targetWindow.attachEvent ( "onunload", liwe.events._del_all );
    		}
  	};

  
	liwe.events.del = function ( target, type, listener )
	{
		// find out if the listener was actually added to target
		var listenerIndex = liwe.events._find ( target, type, listener );
		if ( listenerIndex == -1 ) return;

		// get a reference to the window object containing target
		var targetDocument = target.document || target;
		var targetWindow   = targetDocument.parentWindow;

		// obtain the record of the listener from the window object
		var listenerId = target._listeners [ listenerIndex ];
		var rec = targetWindow._all [ listenerId ];

		// remove the listener, and remove its ID from target
		target.detachEvent ( "on" + type, rec._cback );
		target._listeners.splice ( listenerIndex, 1 );

		// remove the record of the listener from the window object
		delete targetWindow._all [ listenerId ];
	};

	liwe.events.prevent = function ( e ) { e.returnValue = false; };
	liwe.events.stop = function ( e ) { e.cancelBubble = true; };
	liwe.events.source   = function ( e ) { return event.srcElement; };
	liwe.events.keycode  = function ( e ) { return event.keyCode; };

	liwe.events._find = function ( target, type, listener )
	{
		// get the array of listener IDs added to target
		var listeners = target._listeners;
		if ( !listeners ) return -1;

		// get a reference to the window object containing target
		var targetDocument = target.document || target;
		var targetWindow   = targetDocument.parentWindow;

		// searching backward ( to speed up onunload processing ), find the listener
		for ( var i = listeners.length - 1; i >= 0; i-- )
		{
			// get the listener's ID from target
			var listenerId = listeners [ i ];

			// get the record of the listener from the window object
			var rec = targetWindow._all [ listenerId ];

			// compare type and listener with the retrieved record
			if (rec.type == type && rec.listener == listener) return i;
		}

		return -1;
	};

	liwe.events._del_all = function()
	{
		var targetWindow = this;

		for ( id in targetWindow._all )
		{
			var rec = targetWindow._all [ id ];
			if ( typeof ( rec ) == "function" ) continue;

			rec.target.detachEvent ( "on" + rec.type, rec._cback );
			delete targetWindow._all[id];
		}
	};

  	liwe.events._list_counter = 0;
}


liwe.events.add_by_id = function ( id, event_name, func )
{
	liwe.events.add ( document.getElementById ( id ), event_name, func );
};

/*
EXAMPLES

liwe.events.add ( window, 'load', on_load, false );
*/


/*
 * dom.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */
 
/*
 * 	2009-09-07:	Added the $c() function is like a getAllElementsByClassName ( element, class_name, [ starting_container == document ] )
 */

liwe.dom = {};

// PUBLIC: get_offset_top
liwe.dom.get_offset_top = function ( elm )
{
  	var o_top    = elm.offsetTop;
  	var o_parent = elm.offsetParent;

  	while ( o_parent && o_parent.tagName != "HTML" )
	{
		// if ( o_parent.style.position == 'absolute' ) return o_top;
    		o_top += o_parent.offsetTop;
    		o_parent = o_parent.offsetParent;
  	}
 
  	return o_top;
};

// PUBLIC: get_offset_left
liwe.dom.get_offset_left = function ( elm )  
{
	var o_left = elm.offsetLeft;
  	var o_parent = elm.offsetParent;

  	while ( o_parent )
	{
		// if ( o_parent.style.position == 'absolute' ) return o_left;
		// console.debug ( "parent: %o - o_parent: %s - left: %s", o_parent, o_parent.offsetParent, o_left );
		// if ( ! o_parent.offsetParent.offsetParent ) break;
    		o_left += o_parent.offsetLeft;
    		o_parent = o_parent.offsetParent;
  	}
 
  	return o_left;
};

// PUBLIC: append_css
liwe.dom.append_css = function ( css_file, id, as_first )
{
	var head = document.getElementsByTagName ( "head" ) [ 0 ];
	var new_css = document.createElement ( "link" );

	new_css.href = css_file;
	new_css.type = "text/css";
	new_css.rel  = "stylesheet";
	if ( id ) new_css.id = id;

	if ( as_first )
		head.insertBefore ( new_css, head.firstChild );
	else
		head.appendChild ( new_css );
};


// PUBLIC: get_padding_width
liwe.dom.get_padding_width = function ( el )
{
	var oldw = el.clientWidth;
	var neww;

	el.style.width = "0px";
	neww = el.clientWidth;

	el.style.width = ( oldw - neww ) + "px";

	return neww;
};

// PUBLIC: get_padding_height
liwe.dom.get_padding_height = function ( el )
{
	var oldh = el.clientHeight;
	var newh;

	el.style.height = "0px";
	newh = el.clientHeight;

	el.style.height = ( oldh - newh ) + "px";

	return newh;
};

liwe.dom.get_size = function ( el )
{
	return [ el.clientWidth, el.clientHeight ];
};

// PUBLIC: os3_get_window_size
liwe.dom.get_window_size = function ()
{
	var s = document.createElement ( "div" );
	s.style.position = "absolute";
	s.style.bottom = "0px";
	s.style.right  = "0px";
	s.style.width  = "1px";
	s.style.height  = "1px";
	s.style.visibility = "hidden";
	document.body.appendChild ( s );

	var w, h;
	w = os3_get_offset_left ( s ) + s.clientWidth;
	h = os3_get_offset_top ( s ) + s.clientHeight;

	document.body.removeChild ( s );

	return { "width": w, "height": h };
};

// PUBLIC: create_element
liwe.dom.create_element = function ( tag, name, parent )
{
	if ( ! parent ) parent = document.body;

	// if ( document.ActiveXObject ) tag = '<' + tag + ' name="' + name + '">';
	if ( document.all ) tag = '<' + tag + ' name="' + name + '">';

	var e = document.createElement ( tag );
	e.style.position = 'absolute';
	e.style.top = "0px";
	e.style.right = "0px";
	e.id = name;
	e.name = name;
	parent.appendChild ( e );
	
	return e;
};

liwe.dom.remove_element = function ( e, parent )
{
	if ( ! parent ) parent = document.body;

	parent.removeChild ( e );
};

liwe.dom.get_event_pos = function ( e )
{
	var posx = 0, posy = 0;

	if ( e == null ) e = window.event;
	if ( e.pageX || e.pageY )
	{
		posx = e.pageX; 
		posy = e.pageY;
	} else if ( e.clientX || e.clientY ) {
	 	if ( document.documentElement.scrollTop )
		{
	 		posx = e.clientX + document.documentElement.scrollLeft;
	 		posy = e.clientY + document.documentElement.scrollTop;
	 	} else {
	 		posx = e.clientX + document.body.scrollLeft;
	 		posy = e.clientY + document.body.scrollTop;
	 	}
	 }

	return [ posx, posy ];
};

liwe.dom.has_class = function ( el, class_name )
{
	var pattern = new RegExp ( "(^| )" + class_name + "( |$)" );

	if ( pattern.test ( el.className ) ) return true;

	return false;
};

liwe.dom.add_class = function ( target, class_name )
{
	if ( liwe.dom.has_class ( target, class_name ) ) return;

	if ( target.className == "" ) 
		target.className = class_name;
	else
		target.className += " " + class_name;
};

liwe.dom.del_class = function ( target, class_name )
{
	var pattern = new RegExp ( "(^| )" + class_name + "( |$)" );

	target.className = target.className.replace ( pattern, "$1" ).replace ( / $/, "" );
};

Object.prototype.hide = function ()
{
	if ( ! this.style || this.style.display == 'none' ) return;

	this._old_display = this.style.display;
	this.style.display = 'none';
};

Object.prototype.show = function ()
{
	if ( ! this.style ) return;

	if ( this._old_display )
		this.style.display = this._old_display;
	else
		this.style.display = 'block';

	this._old_display = null;
};

liwe.dom.tableize = function ()
{
	if ( ( ! liwe.browser.ie ) && ( ! liwe.browser.version < 8 ) ) return;
	
	function _replace ( table_start, table )
	{
		var parent = table_start.parentNode;
		var next_sibling = table_start.nextSibling;
		parent.removeChild ( table_start );
		parent.insertBefore ( table, next_sibling );
	}

	function _add_cell ( row, div )
	{
		var c;
		cell = document.createElement ( "td" );
		cell.setAttribute ( "vAlign", "top" );
		cell.className = div.className;

		c = cell.appendChild ( div.firstChild.cloneNode ( true ) );
		c.style.display = "block";

		row.appendChild ( cell );
	}

	var divs = document.getElementsByTagName ( "div" );
	var t, l = divs.length, div;
	var table = null, tbody = null;
	var row = null, cell = null;
	var table_start = null;

	for ( t = 0; t < l; t ++ )
	{
		div = divs [ t ];
		if ( ! div.className ) continue;

		if ( div.className.indexOf ( 'table' ) != -1 )
		{
			if ( table_start )
			{
				_replace ( table_start, table );
				table = null;
			}

			table_start = div;
			table = document.createElement ( "table" );
			tbody = document.createElement ( "tbody" );
			table.appendChild ( tbody );
			table.className = div.className;
			table.style.border = "1px dotted black";
		} else if ( div.className.indexOf ( "cell-first" ) != -1 ) {
			row = document.createElement ( "tr" );
			tbody.appendChild ( row );
			_add_cell ( row, div );
		} else if ( div.className.indexOf ( "cell" ) != -1 ) {
			_add_cell ( row, div );
		}
	}

	if ( table )
		_replace ( table_start, table );
};

function $c ( element, class_name, base )
{
	if ( ! base ) base = document;
	var elements = base.getElementsByTagName ( element );
	var t, l = elements.length;
	var res = [], el;

	for ( t = 0; t < l; t ++ )
	{
		el = elements [ t ];
		if ( el.className.indexOf ( class_name ) == -1 ) continue;

		res.push ( el );
	}

	return res;
}


/*
 * utils.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */

/*
 *
 *
 */

// PUBLIC: max
liwe.utils.max = function ()
{
	if ( ! arguments.length ) return 0;

	var m = 0;
	var t;

	for ( t = 0; t < arguments.length; t ++ )
		if ( m < arguments [ t ] ) m = arguments [ t ];

	return m;
};

// PUBLIC: min
liwe.utils.min = function ()
{
	if ( ! arguments.length ) return 0;

	var m = arguments [ 0 ];
	var t;

	for ( t = 1; t < arguments.length; t ++ )
		if ( m > arguments [ t ] ) m = arguments [ t ];

	return m;
};

// PUBLIC: date2str
// Mode:
//
//	0 - YYYY MM DD	( default )
//	1 - DD MM YYYY
// 	2 - MM DD YYYY
liwe.utils.date2str = function ( date, mode )
{
	var s = new String ( date );
	var v = s.match ( new RegExp ( "([0-9]{4}).([0-9]{1,2}).([0-9]{1,2})" ) );

	if ( ! mode ) mode = 0;

	switch ( mode )
	{
		case 1:
			s = v [ 3 ] + "-" + v [ 2 ] + "-" + v [ 1 ];
			break;
		case 2:
			s = v [ 2 ] + "-" + v [ 3 ] + "-" + v [ 1 ];
			break;

		default:
			s = v [ 1 ] + "-" + v [ 2 ] + "-" + v [ 3 ];
	}

	return s;
};

// PUBLIC: call
// Chiama una funzione passando un array di parametri
liwe.utils.call = function ( func_name, this_arg, arg_array )
{
	var i, l = arg_array.length;
	var s = "this_arg." + func_name + " ( ";
	
	for ( i = 0; i < l; i++ )
	{
		if ( i > 0 ) s += ", ";
		s += "arg_array[" + i + "]";
	}

	s += " );";

	return eval ( s );
};

// Formats a result list iterating on the list ``lst`` and using String.formatDict with
// the three templates str_row [mandatory], str_start [optional] and str_end [optional]
// Returns the formatted string
liwe.utils.format_list = function ( lst, str_row, str_start, str_end )
{
	var s = new String.buffer ();
	var t, l = lst.length;

	if ( ! l ) return '';

	if ( str_start ) s.add ( str_start );
	for ( t = 0; t < l; t ++ )
		s.add ( String.formatDict ( str_row, lst [ t ] ) );

	if ( str_end ) s.add ( str_end );

	return s.toString ();
};

liwe.utils._ents = null;

liwe.utils.map_entities = function ( txt )
{
	if ( ! liwe.utils_ents )
	{
		liwe.utils._ents = {
			 "&#8217;": "'",
			 "&#224;": "&agrave;",
			 "&#232;": "&egrave;",
			 "&#233;": "&eacute;",
			 "&#242;": "&ograve;",
			 "&#249;": "&ugrave;",
			 "&#8220;": '"',
			 "&#8221;": '"',
			 "&#8211;": "-",
			 "%u2013" : "-",
			 "%u2019" : "'",
		         "%u201C" : '"',
		         "%u201D" : '"'
		};

		var reg_exp = "";
		var ents = [];

		liwe.utils._ents.iterate ( function ( v, k ) { ents.push ( k ); } );
		reg_exp = "(" + "|".join ( ents ) + ")";

		liwe.utils._ents_re = RegExp ( reg_exp, "g" );
	}

	txt = txt.replace ( /&#37;/g, "%" );

	return txt.replace ( liwe.utils._ents_re, function ( k ) { return liwe.utils._ents [ k ]; } );
};


/*
 *
 * 	2009-04-05:	NEW: get_current_obj() - returns an object of the current history hash
 *
 */
liwe.history = {};

liwe.history.listener_callback = {};

liwe.history.cbacks = {
	"before-add" : null,
	"before-module" : null
};

liwe.history._load = function ()
{
	liwe.history._is_ie = ( document.all && navigator.userAgent.toLowerCase().indexOf ( 'msie' ) != -1 );

	liwe.history._blank_page = liwe._libbase + "/data/history_blank.html";

	liwe.history._data_storage = [];
	
	if ( liwe.history._is_ie )
		liwe.history._int_create_iframe ();

	document.write ( '<form style="display: none;"><input id="historyDataText" type="text" value="" \/><\/form>' );
};

liwe.history.init = function ()
{
	liwe.history._saved_location = liwe.history.get_current_location();

	setInterval ( liwe.history._int_check_location, 100 );

	setTimeout ( liwe.history._init_done, 200 );
};


liwe.history._init_done = function ()
{
	var hdt = document.getElementById ( "historyDataText" );
	
	if ( hdt.value )
		liwe.history._data_storage  = hdt.value.parseJSON();

	liwe.history._int_call_listener();
};


liwe.history._int_create_iframe = function ()
{
	var loc = liwe.history.get_current_location();
	
	liwe.history._adding = true;
	
	document.write ( "<iframe style='border: 2px; width: 1px; "
                               + "height: 1px; position: absolute; bottom: 0px; "
                               + "right: 0px; display: none;' "
                               + "name='liwe.historyFrame' id='liwe.historyFrame' src='" + liwe.history._blank_page + "?" + loc + "'>"
                               + "<\/iframe>" );

	liwe.history._iframe = document.getElementById ( "liwe.historyFrame" );

	window._os3_history_cb = liwe.history._int_iframe_location_changed;
};


liwe.history.get_current_location = function ()
{
	var loc = window.location.hash;
	if ( loc.length > 0 && loc.charAt ( 0 ) == '#' )
		loc = loc.slice ( 1 );
	return loc;
};

liwe.history.get_current_obj = function ()
{
	var loc = liwe.history.get_current_location ().split ( "," );
	var t, l = loc.length;
	var res = {}, p;

	for ( t = 0; t < l; t ++ )
	{
		p = loc [ t ].split ( "=" );
		res [ p [ 0 ] ] = p [ 1 ];
	}

	return res;
};


liwe.history._int_call_listener = function ()
{
	if ( ! liwe.history.listener_callback ) return;

	var id = liwe.history.get_current_location ();
	var dict = liwe.history._str2dict ( id );
	var data, module;

	if ( typeof dict [ "__dk" ] != "undefined" )
	{
		var key = parseInt ( dict [ "__dk" ] );
		data = liwe.history._data_storage [ key ];
		delete dict [ "__dk" ];
	}

	if ( typeof dict [ "__m" ] != "undefined" )
		module = dict [ "__m" ];
	else
		module = "__DEFAULT__";

	if ( ! liwe.history.listener_callback [ module ] ) return;

	liwe.history._listener_call = true;
	try
	{
		liwe.history.listener_callback [ module ] ( dict, data );
	}
	finally
	{
		liwe.history._listener_call = false;
	}
};


liwe.history.set_listener = function ( listener, module )
{
	if ( ! module ) module = "__DEFAULT__";
	liwe.history.listener_callback [ module ] = listener;
};


liwe.history.add = function ( dict, data )
{
	return liwe.history.add_module ( null, dict, data );
};


liwe.history.add_module = function ( module, dict, data )
{
	if ( ! dict ) dict = {};

	if ( liwe.history._listener_call ) return;
	if ( dict.get ( "__nh" ) == 1 ) return;

	if ( liwe.history.cbacks [ 'before-add' ] )
	{
		// NOTE: function should return TRUE to block event propagation
		var block = liwe.history.cbacks [ 'before-add' ] ( module, dict, data );

		if ( block ) return;
	}

	if ( data )
	{
		var key = liwe.history._data_storage.length.toString();
		liwe.history._data_storage.push ( data );
		dict [ "__dk" ] = key;

		var s = liwe.history._data_storage.toJSONString();
		var is = document.getElementById ( "historyDataText" );
		is.value = s;
	}

	if ( module ) dict [ "__m" ] = module;

	var id = liwe.history._dict2str ( dict );
	window.location.hash = id;
	liwe.history._saved_location = id;

	if ( liwe.history._is_ie )
	{
		liwe.history._adding = true;
		liwe.history._iframe.src = liwe.history._blank_page + "?" + id;
	}
};


liwe.history.replace = function ( module, dict, data )
{
	if ( liwe.history._listener_call ) return;

	if ( dict.get ( "__nh" ) == 1 ) return;

	var key = (liwe.history._data_storage.length - 1).toString();
	liwe.history._data_storage [ liwe.history._data_storage.length - 1 ] = data;
	dict [ "__dk" ] = key;

	var s = liwe.history._data_storage.toJSONString();
	var is = document.getElementById ( "historyDataText" );
	is.value = s;

	if ( module ) dict [ "__m" ] = module;

	var loc = String ( location ).split ( '#' ) [ 0 ];
	var id = liwe.history._dict2str ( dict );
	window.location.replace ( loc + "#" + id );
	liwe.history._saved_location = id;

	if ( liwe.history._is_ie )
	{
		liwe.history._adding = true;
		liwe.history._iframe.src = liwe.history._blank_page + "?" + id;
	}
};


liwe.history._dict2str = function ( dict )
{
	var str = "";
	var is_first = true;
	
	var k, v;
	for ( k in dict )
	{
		v = dict [ k ];
		if ( typeof ( v ) == 'function' ) continue;

		if ( is_first ) is_first = false;
		else str += ",";
		
		str += k;
		if ( v != null && v != undefined )
		{
			v = v.toString();
			str += "=" + liwe.history._escape_value ( v );
		}

	}

	return str;
};


liwe.history._str2dict = function ( str )
{
	var tok;

	var dict = {};

	str = liwe.history._lstrip ( str );

	while ( str.length > 0 )
	{
		// cerco la virgola divisoria
		var cpos = str.indexOf ( "," );
		while ( cpos < str.length - 1 && str.charAt ( cpos + 1 ) == ',' )
			cpos = str.indexOf ( ",", cpos + 2 );

		if ( cpos == -1 )
		{
			tok = str;

			str = "";
		} else {
			tok = str.slice ( 0, cpos );

			str = str.slice ( cpos + 1 );
			str = liwe.history._lstrip ( str );
		}

		// splittiamo sull'uguale
		var splt = tok.split ( "=" );
		var k = splt [ 0 ];
		var v = liwe.history._join ( "=", splt.slice ( 1 ) );
		v = v.replace ( ",,", "," );

		dict [ k ] = unescape(v);
	}

	return dict;
};


liwe.history._escape_value = function ( v )
{
	return v.replace ( ",", ",," );
};


liwe.history._lstrip = function ( s )
{
	while ( s.length > 0 && s.charAt ( 0 ) == ' ' )
		s = s.slice ( 1 );

	return s;
};


liwe.history._join = function ( sep, arr )
{
	var l = arr.length;
	if ( l == 0 ) return "";
	
	var s = arr [ 0 ];
	for ( var i = 1; i < l ; i++ )
		s += sep + arr [ i ];

	return s;
};


liwe.history._int_iframe_location_changed = function ( id )
{
	if ( liwe.history._adding )
	{
		liwe.history._adding = false;
		return;
	}

	if ( id.length > 0 && id.charAt ( 0 ) == '?' )
		id = id.slice ( 1 );

	window.location.hash = id;
	liwe.history._saved_location = id;

	liwe.history._int_call_listener ();
};


liwe.history._int_check_location = function ()
{
	var loc = liwe.history.get_current_location();
	if ( loc == liwe.history._saved_location )
		return;

	liwe.history._saved_location = loc;

	if ( liwe.history._is_ie )
		liwe.history._iframe.src = liwe.history._blank_page + "?" + loc;
	else
		liwe.history._int_call_listener();
};

liwe.history._load();


/*
    json.js
    2007-01-10

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2007.
*/

if (!Object.prototype.toJSONString) {
    Array.prototype.toJSONString = function () {
        var a = ['['], b, i, l = this.length, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(s);
            b = true;
        }

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'undefined':
            case 'function':
            case 'unknown':
                break;
            case 'object':
                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        p(v.toJSONString());
                    }
                } else {
                    p("null");
                }
                break;
            default:
                p(v.toJSONString());
            }
        }
        a.push(']');
        return a.join('');
    };

    Boolean.prototype.toJSONString = function () {
        return String(this);
    };

    Date.prototype.toJSONString = function () {

        function f(n) {
            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getFullYear() + '-' +
                f(this.getMonth() + 1) + '-' +
                f(this.getDate()) + 'T' +
                f(this.getHours()) + ':' +
                f(this.getMinutes()) + ':' +
                f(this.getSeconds()) + '"';
    };

    Number.prototype.toJSONString = function () {
        return isFinite(this) ? String(this) : "null";
    };

    Object.prototype.toJSONString = function () {
        var a = ['{'], b, i, v;

        function p(s) {
            if (b) {
                a.push(',');
            }
            a.push(i.toJSONString(), ':', s);
            b = true;
        }

        for (i in this) {
            if (this.hasOwnProperty(i)) {
                v = this[i];
                switch (typeof v) {
                case 'undefined':
                case 'function':
                case 'unknown':
                    break;
                case 'object':
                    if (v) {
                        if (typeof v.toJSONString === 'function') {
                            p(v.toJSONString());
                        }
                    } else {
                        p("null");
                    }
                    break;
                default:
                    p(v.toJSONString());
                }
            }
        }
        a.push('}');
        return a.join('');
    };


    (function (s) {
        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };

        s.parseJSON = function (filter) {
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(this)) {
                    var j = eval('(' + this + ')');
                    if (typeof filter === 'function') {
                        function walk(k, v) {
                            if (v && typeof v === 'object') {
                                for (var i in v) {
                                    if (v.hasOwnProperty(i)) {
                                        v[i] = walk(i, v[i]);
                                    }
                                }
                            }
                            return filter(k, v);
                        }
                        return walk('', j);
                    }
                    return j;
                }
            } catch (e) {
            }
            throw new SyntaxError("parseJSON");
        };

        s.toJSONString = function () {
            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                    var c = m[b];
                    if (c) {
                        return c;
                    }
                    c = b.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}


/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
	Modified version by Fabio Rotondo for the LiWE project	
*/

var MD5 = {};

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
MD5.hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
MD5.b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
MD5.chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
MD5.hex_md5 = function ( s ) 
{ 
	return MD5._binl2hex ( MD5._core_md5 ( MD5._str2binl ( s ), s.length * MD5.chrsz ) ); 
};

MD5.b64_md5 = function ( s )
{ 
	return MD5._binl2b64 ( MD5._core_md5 ( MD5._str2binl ( s ), s.length * MD5.chrsz ) );
};

MD5.str_md5 = function ( s )
{ 
	return MD5._binl2str ( MD5._core_md5 ( MD5._str2binl ( s ), s.length * MD5.chrsz ) );
};

MD5.hex_hmac_md5 = function ( key, data ) 
{ 
	return MD5._binl2hex ( MD5._core_hmac_md5 ( key, data ) ); 
};

MD5.b64_hmac_md5 = function ( key, data ) 
{ 
	return MD5._binl2b64 ( MD5._core_hmac_md5 ( key, data ) ); 
};

MD5.str_hmac_md5 = function ( key, data ) 
{ 
	return MD5._binl2str ( MD5._core_hmac_md5 ( key, data ) ); 
};

/*
 * Perform a simple self-test to see if the VM is working
 */
MD5.test = function ()
{
  return MD5.hex_md5 ( "abc" ) == "900150983cd24fb0d6963f7d28e17f72";
};

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
MD5._core_md5 = function ( x, len )
{
  /* append padding */
  x [ len >> 5 ] |= 0x80 << ( ( len ) % 32 );
  x [ ( ( ( len + 64 ) >>> 9 ) << 4 ) + 14 ] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;
  var i, l = x.length;

  for ( i = 0; i < l + 32; i ++ )
	  if ( typeof ( x [ i ] ) == "undefined" )
		  x [ i ] = 0;

  for ( i = 0; i < l; i += 16 )
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = MD5._ff ( a, b, c, d, x [ i + 0 ], 7 , -680876936 );
    d = MD5._ff ( d, a, b, c, x [ i + 1 ], 12, -389564586 );
    c = MD5._ff ( c, d, a, b, x [ i + 2 ], 17,  606105819 );
    b = MD5._ff ( b, c, d, a, x [ i + 3 ], 22, -1044525330 );
    a = MD5._ff ( a, b, c, d, x [ i + 4 ], 7 , -176418897 );
    d = MD5._ff ( d, a, b, c, x [ i + 5 ], 12,  1200080426 );
    c = MD5._ff ( c, d, a, b, x [ i + 6 ], 17, -1473231341 );
    b = MD5._ff ( b, c, d, a, x [ i + 7 ], 22, -45705983 );
    a = MD5._ff ( a, b, c, d, x [ i + 8 ], 7 ,  1770035416 );
    d = MD5._ff ( d, a, b, c, x [ i + 9 ], 12, -1958414417 );
    c = MD5._ff ( c, d, a, b, x [ i + 10 ], 17, -42063 );
    b = MD5._ff ( b, c, d, a, x [ i + 11 ], 22, -1990404162 );
    a = MD5._ff ( a, b, c, d, x [ i + 12 ], 7 ,  1804603682 );
    d = MD5._ff ( d, a, b, c, x [ i + 13 ], 12, -40341101 );
    c = MD5._ff ( c, d, a, b, x [ i + 14 ], 17, -1502002290 );
    b = MD5._ff ( b, c, d, a, x [ i + 15 ], 22,  1236535329 );

    a = MD5._gg ( a, b, c, d, x [ i+ 1 ] , 5 , -165796510 ) ;
    d = MD5._gg ( d, a, b, c, x [ i+ 6 ] , 9 , -1069501632 ) ;
    c = MD5._gg ( c, d, a, b, x [ i+11 ] , 14,  643717713 ) ;
    b = MD5._gg ( b, c, d, a, x [ i+ 0 ] , 20, -373897302 ) ;
    a = MD5._gg ( a, b, c, d, x [ i+ 5 ] , 5 , -701558691 ) ;
    d = MD5._gg ( d, a, b, c, x [ i+10 ] , 9 ,  38016083 ) ;
    c = MD5._gg ( c, d, a, b, x [ i+15 ] , 14, -660478335 ) ;
    b = MD5._gg ( b, c, d, a, x [ i+ 4 ] , 20, -405537848 ) ;
    a = MD5._gg ( a, b, c, d, x [ i+ 9 ] , 5 ,  568446438 ) ;
    d = MD5._gg ( d, a, b, c, x [ i+14 ] , 9 , -1019803690 ) ;
    c = MD5._gg ( c, d, a, b, x [ i+ 3 ] , 14, -187363961 ) ;
    b = MD5._gg ( b, c, d, a, x [ i+ 8 ] , 20,  1163531501 ) ;
    a = MD5._gg ( a, b, c, d, x [ i+13 ] , 5 , -1444681467 ) ;
    d = MD5._gg ( d, a, b, c, x [ i+ 2 ] , 9 , -51403784 ) ;
    c = MD5._gg ( c, d, a, b, x [ i+ 7 ] , 14,  1735328473 ) ;
    b = MD5._gg ( b, c, d, a, x [ i+12 ] , 20, -1926607734 ) ;

    a = MD5._hh ( a, b, c, d, x [ i+ 5 ] , 4 , -378558 ) ;
    d = MD5._hh ( d, a, b, c, x [ i+ 8 ] , 11, -2022574463 ) ;
    c = MD5._hh ( c, d, a, b, x [ i+11 ] , 16,  1839030562 ) ;
    b = MD5._hh ( b, c, d, a, x [ i+14 ] , 23, -35309556 ) ;
    a = MD5._hh ( a, b, c, d, x [ i+ 1 ] , 4 , -1530992060 ) ;
    d = MD5._hh ( d, a, b, c, x [ i+ 4 ] , 11,  1272893353 ) ;
    c = MD5._hh ( c, d, a, b, x [ i+ 7 ] , 16, -155497632 ) ;
    b = MD5._hh ( b, c, d, a, x [ i+10 ] , 23, -1094730640 ) ;
    a = MD5._hh ( a, b, c, d, x [ i+13 ] , 4 ,  681279174 ) ;
    d = MD5._hh ( d, a, b, c, x [ i+ 0 ] , 11, -358537222 ) ;
    c = MD5._hh ( c, d, a, b, x [ i+ 3 ] , 16, -722521979 ) ;
    b = MD5._hh ( b, c, d, a, x [ i+ 6 ] , 23,  76029189 ) ;
    a = MD5._hh ( a, b, c, d, x [ i+ 9 ] , 4 , -640364487 ) ;
    d = MD5._hh ( d, a, b, c, x [ i+12 ] , 11, -421815835 ) ;
    c = MD5._hh ( c, d, a, b, x [ i+15 ] , 16,  530742520 ) ;
    b = MD5._hh ( b, c, d, a, x [ i+ 2 ] , 23, -995338651 ) ;

    a = MD5._ii ( a, b, c, d, x [ i+ 0 ] , 6 , -198630844 ) ;
    d = MD5._ii ( d, a, b, c, x [ i+ 7 ] , 10,  1126891415 ) ;
    c = MD5._ii ( c, d, a, b, x [ i+14 ] , 15, -1416354905 ) ;
    b = MD5._ii ( b, c, d, a, x [ i+ 5 ] , 21, -57434055 ) ;
    a = MD5._ii ( a, b, c, d, x [ i+12 ] , 6 ,  1700485571 ) ;
    d = MD5._ii ( d, a, b, c, x [ i+ 3 ] , 10, -1894986606 ) ;
    c = MD5._ii ( c, d, a, b, x [ i+10 ] , 15, -1051523 ) ;
    b = MD5._ii ( b, c, d, a, x [ i+ 1 ] , 21, -2054922799 ) ;
    a = MD5._ii ( a, b, c, d, x [ i+ 8 ] , 6 ,  1873313359 ) ;
    d = MD5._ii ( d, a, b, c, x [ i+15 ] , 10, -30611744 ) ;
    c = MD5._ii ( c, d, a, b, x [ i+ 6 ] , 15, -1560198380 ) ;
    b = MD5._ii ( b, c, d, a, x [ i+13 ] , 21,  1309151649 ) ;
    a = MD5._ii ( a, b, c, d, x [ i+ 4 ] , 6 , -145523070 ) ;
    d = MD5._ii ( d, a, b, c, x [ i+11 ] , 10, -1120210379 ) ;
    c = MD5._ii ( c, d, a, b, x [ i+ 2 ] , 15,  718787259 ) ;
    b = MD5._ii ( b, c, d, a, x [ i+ 9 ] , 21, -343485551 ) ;

    a = MD5._safe_add ( a, olda ) ;
    b = MD5._safe_add ( b, oldb ) ;
    c = MD5._safe_add ( c, oldc ) ;
    d = MD5._safe_add ( d, oldd ) ;
  }

  return Array ( a, b, c, d ) ;
}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
MD5._cmn = function ( q, a, b, x, s, t )
{
  return MD5._safe_add ( MD5._bit_rol ( MD5._safe_add ( MD5._safe_add ( a, q ), MD5._safe_add ( x, t ) ), s ), b );
};

MD5._ff = function ( a, b, c, d, x, s, t )
{
  return MD5._cmn ( ( b & c ) | ( ( ~b ) & d ), a, b, x, s, t );
};

MD5._gg = function  ( a, b, c, d, x, s, t )
{
  return MD5._cmn ( ( b & d ) | ( c & ( ~d ) ), a, b, x, s, t );
};
MD5._hh = function  ( a, b, c, d, x, s, t )
{
  return MD5._cmn ( b ^ c ^ d, a, b, x, s, t );
};
MD5._ii = function  ( a, b, c, d, x, s, t )
{
  return MD5._cmn ( c ^ ( b | ( ~d ) ), a, b, x, s, t );
};

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
MD5._core_hmac_md5 = function ( key, data )
{
  var bkey = str2binl ( key );

  if ( bkey.length > 16 ) bkey = _core_md5 ( bkey, key.length * MD5.chrsz );

  var ipad = Array ( 16 ), opad = Array ( 16 );

  for ( var i = 0; i < 16; i++ )
  {
    ipad [ i ] = bkey [ i ] ^ 0x36363636;
    opad [ i ] = bkey [ i ] ^ 0x5C5C5C5C;
  }

  var hash = MD5._core_md5 ( ipad.concat ( MD5._str2binl ( data ) ), 512 + data.length * MD5.chrsz );
  return MD5._core_md5 ( opad.concat ( hash ), 512 + 128 );
};

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
MD5._safe_add = function ( x, y )
{
  var lsw = ( x & 0xFFFF ) + ( y & 0xFFFF );
  var msw = ( x >> 16 ) + ( y >> 16 ) + ( lsw >> 16 );

  return ( msw << 16 ) | ( lsw & 0xFFFF );
};

/*
 * Bitwise rotate a 32-bit number to the left.
 */
MD5._bit_rol = function ( num, cnt )
{
  return ( num << cnt ) | ( num >>> ( 32 - cnt ) );
};

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
MD5._str2binl = function ( str )
{
  var bin = Array();
  var mask = ( 1 << MD5.chrsz ) - 1;

  for ( var i = 0; i < str.length * MD5.chrsz; i += MD5.chrsz )
  {
    if ( typeof ( bin [ i >> 5 ] ) == "undefined" )
	bin [ i >> 5 ] = 0;

    bin [ i >> 5 ] |= ( str.charCodeAt ( i / MD5.chrsz ) & mask ) << ( i % 32 );
  }

  return bin;
};

/*
 * Convert an array of little-endian words to a string
 */
MD5._binl2str = function ( bin )
{
  var str = "";
  var mask = ( 1 << MD5.chrsz ) - 1;

  for ( var i = 0; i < bin.length * 32; i += MD5.chrsz )
    str += String.fromCharCode ( ( bin [ i >> 5 ] >>> ( i % 32 ) ) & mask );

  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
MD5._binl2hex = function ( binarray )
{
  var hex_tab = MD5.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";

  for ( var i = 0; i < binarray.length * 4; i++ )
  {
    str += hex_tab.charAt ( ( binarray [ i >> 2 ] >> ( ( i % 4 ) * 8 + 4 ) ) & 0xF ) +
           hex_tab.charAt ( ( binarray [ i >> 2 ] >> ( ( i % 4 ) * 8 ) ) & 0xF );
  }

  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
MD5._binl2b64 = function ( binarray )
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";

  for ( var i = 0; i < binarray.length * 4; i += 3 )
  {
    var triplet = ( ( ( binarray [ i >> 2 ] >> 8 * ( i   %4 ) ) & 0xFF ) << 16 )
                | ( ( ( binarray [ i + 1 >> 2 ] >> 8 * ( ( i + 1 ) % 4 ) ) & 0xFF ) << 8 )
                | ( ( binarray [ i + 2 >> 2 ] >> 8 * ( ( i + 2 ) % 4 ) ) & 0xFF );

    for ( var j = 0; j < 4; j++ )
    {
       if ( i * 8 + j * 6 > binarray.length * 32 ) str += b64pad;
       else str += tab.charAt ( ( triplet >> 6 * ( 3 - j ) ) & 0x3F );
    }
  }
  return str;
}


liwe.lightbox = {};

// {{{ base docs
/**
Lightbox
========

Lightbox is a class aimed to display temporary modal forms to the user.

Lightbox is a *static* class, you don't have to instantiate it by yourself in your code.
You can access it with ``liwe.lightbox`` static class.

Lightbox requesters are stacked like a pile one over the other. You can programmatically create any number of lightboxes and the most recent one will always be visible over
all the previous lightboxes created.

You can only remove the top lightbox on the stack, using the ``liwe.lightbox.close()`` method.

.. warning:: 
	``lightbox.events`` not documented yet

*/
// }}}


liwe.lightbox.opacity = 70;
liwe.lightbox.fade = false;
liwe.lightbox._is_show = false;

liwe.lightbox._back_div  = null;
liwe.lightbox._front_div = [];

liwe.lightbox._max_zindex  = null;
liwe.lightbox._max_zindex_el  = 'div';

liwe.lightbox.events = {
	"click" : null,
	"close" : null
};

// {{{ liwe.lightbox.create ( id, w, h, x, y )
/**
.. function:: liwe.lightbox.create ( id, w, h, [ x, [ y ] ] )

	Creates a new lightbox area.

	:param id: the new lightbox id. This id can then be used to modify lightbox content. This field is mandatory.
	:param w:  lightbox width (in pixels). This field is mandatory.
	:param h:  lightbox height (in pixels). This field is mandatory.
	:param x:  lightbox x position (in pixels) This field is optional. If not passed the lightbox x position
		   will be computed to put the lightbox in the middle of the screen.

	:param y:  lightbox y position (in pixels). This field is optional. If not passed the lightbox y position
		   will be computed to put the lightbox in the middle of the screen.

	:rtype: this function returns nothing.
*/
liwe.lightbox.create = function ( id, w, h, x, y )
{
	var back = liwe.lightbox._add_back_div ();
	var div  = liwe.lightbox._add_front_div ( id, w, h, x, y );

	return div;
};
// }}}
// {{{ liwe.lightbox.created ()
/**
.. function:: liwe.lightbox.created ()

	This function simply checks if at least one lightbox is currently shown on the screen.
	This function returns ``true`` if there is at least one lightbox currently shows, ``false`` otherwise.

	:rtype: returns ``true`` if there is at least one lightbox currently shows, ``false`` otherwise.
*/
liwe.lightbox.created = function ()
{
	return liwe.lightbox._back_div != null;
};
// }}}
// {{{ liwe.lightbox.close ()
/**
.. function:: liwe.lightbox.close ()

	This function closes the topmost lightbox currenlty shown on the browser window.
*/
liwe.lightbox.close = function ()
{
	var d;

	d = liwe.lightbox._front_div.pop ();
	liwe.dom.remove_element ( d );

	if ( liwe.lightbox.events [ 'close' ] ) liwe.lightbox.events [ 'close' ] ();

	liwe.dom.remove_element ( liwe.lightbox._back_div );
	liwe.lightbox._back_div = null;
};
// }}}
// {{{ liwe.lightbox.show ()
/**
.. function:: liwe.lightnox.show ()

	This function shows on browser window the last created lightbox.
*/
liwe.lightbox.show = function ()
{
	var div = liwe.lightbox._front_div [ liwe.lightbox._front_div.length -1 ];

	liwe.fx.set_opacity ( liwe.lightbox._back_div, liwe.lightbox.opacity );
	liwe.lightbox._back_div.style.display = "block";

	if ( liwe.lightbox.fade )
	{
		liwe.fx.set_opacity ( div, 0 );
		div.style.display = "block";

		liwe.fx.fade_in ( div );
	} else 
		liwe.fx.set_opacity ( div, 100 );
};
// }}}
// {{{ liwe.lightbox.easy ( id, title, w, h, x, y )
/**
.. function:: liwe.lightnox.easy ( id, title, w, h, x, y )

	This is a commodity function that will call the ``liwe.lightbox.create()`` method to build a new lightbox,
	sets a custom layout (with a close button on the upper right corner of the lightbox screen) and then calls
	the ``liwe.lightbox.show()`` to show it to the user.

	:param id: the new lightbox id. This id can then be used to modify lightbox content. This field is mandatory.
	:param title: the lightbox title that will be shown on the window bar.
	:param w:  lightbox width (in pixels). This field is mandatory.
	:param h:  lightbox height (in pixels). This field is mandatory.
	:param x:  lightbox x position (in pixels) This field is optional. If not passed the lightbox x position
		   will be computed to put the lightbox in the middle of the screen.

	:param y:  lightbox y position (in pixels). This field is optional. If not passed the lightbox y position
		   will be computed to put the lightbox in the middle of the screen.

	:rtype: this function returns nothing.
*/
liwe.lightbox.easy = function ( id, title, w, h, x, y )
{
	var div = liwe.lightbox.create ( id + "_win", w, h, x, y );
	var s;

	div.className = "lightbox_easy";

	s  = '<div class="title">' + title;
	s += '<div class="close" onclick="liwe.lightbox.close()"></div></div><div id="' + id + '"></div>';

	div.innerHTML = s;

	// TODO: fare il "pallino"

	liwe.lightbox.show ();
};
// }}}

// PRIVATE METHODS

// {{{ liwe.lightbox._add_back_div ()
liwe.lightbox._add_back_div = function ()
{
	var d = liwe.lightbox._back_div;
	var max_zindex = ( ! liwe.lightbox._max_zindex ) ? liwe.lightbox._get_highest_zindex () : liwe.lightbox._max_zindex;
	
	if ( ! d ) 
	{
		d = liwe.dom.create_element ( "div", "liwe_lightbox" );

		d.style.display = 'none';
		d.style.backgroundColor = "black";

		liwe.lightbox._back_div = d;
	}

	var size = liwe.lightbox._get_size ();
	
	d.style.zIndex = max_zindex + 10;
	d.style.width  = size.bw + "px"; // "100%";
	d.style.height = size.bh + "px";
	d.style.top = 0;
	d.style.left = 0;
	d.style.position = "absolute";

	liwe.events.add ( d, "click", liwe.lightbox._back_click );

	return d;
};
// }}}
// {{{ liwe.lightbox._back_click ()
liwe.lightbox._back_click = function ()
{
	if ( liwe.lightbox.events [ 'click' ] ) liwe.lightbox.events [ 'click' ] ();
};
// }}}
// {{{ liwe.lightbox._add_front_div ( idm wm h, x, y )
liwe.lightbox._add_front_div = function ( id, w, h, x, y )
{
	var d = liwe.lightbox._back_div;
	var div = liwe.dom.create_element ( "div", id );
	var max_zindex = ( ! liwe.lightbox._max_zindex ) ? liwe.lightbox._get_highest_zindex () : liwe.lightbox._max_zindex;
	var res;

	w += 80;
	h += 80;

	res = this._calc_size ( w, h, x, y );

	w = res [ 0 ];
	h = res [ 1 ];
	x = res [ 2 ];
	y = res [ 3 ];

	console.debug ( "FRONT DIV: X: " + x + " - " + y + " - " + w + " - " + h );

	div.style.zIndex = max_zindex + 5;
	div.style.width  = w + "px";
	div.style.height = h + "px";
	div.style.left = x + "px";
	div.style.top  = y + "px";

	liwe.lightbox._front_div.push ( div ); // = div;
	liwe.lightbox._front_div_id = id; 

	return div;
};
// }}}

liwe.lightbox.set_size = function ( w, h, x, y )
{
	var res;
	var div = document.getElementById ( liwe.lightbox._front_div_id );

	if ( ! div ) 
	{
		console.warning ( "Could not find DIV: %s", liwe.lightbox._front_div_id );
		return;
	}

	res = this._calc_size ( w, h, x, y );

	w = res [ 0 ];
	h = res [ 1 ];
	x = res [ 2 ];
	y = res [ 3 ];

	div.style.width  = w + "px";
	div.style.height = h + "px";
	div.style.left = x + "px";
	div.style.top  = y + "px";
};

liwe.lightbox._get_size = function ()
{
	var bw, bh, sh, sw;
	var D = document;

	bh = Math.max (
		Math.max ( D.body.offsetHeight, D.documentElement.offsetHeight ),
		Math.max ( D.body.clientHeight, D.documentElement.clientHeight ),
		window.innerHeight
	);

	bw = Math.max (
		Math.max ( D.body.offsetWidth, D.documentElement.offsetWidth ),
		Math.max ( D.body.clientWidth, D.documentElement.clientWidth ),
		window.innerWidth
	);

	//KARMA
	bh = Math.max ( D.body.offsetHeight, D.documentElement.offsetHeight, D.body.clientHeight, D.documentElement.clientHeight, window.innerHeight ? window.innerHeight : 0 );

	//KARMA
	bw = Math.max ( D.body.offsetWidth, D.documentElement.offsetWidth, D.body.clientWidth, D.documentElement.clientWidth, window.innerWidth ? window.innerWidth : 0 );

	/*
	sh = Math.max ( Math.max ( D.body.scrollHeight, D.documentElement.scrollHeight ), bh );
	sw = Math.max ( Math.max ( D.body.scrollWidth, D.documentElement.scrollWidth ), bw );
	*/

	sw = Math.max ( Math.max ( D.body.scrollWidth, D.documentElement.scrollWidth ) );
	// sh = Math.max ( Math.max ( D.body.scrollHeight, D.documentElement.scrollHeight ) );
	sh = Math.max ( D.body.scrollTop, D.documentElement.scrollTop );

	console.debug ( "Get Size: bw: " + bw + " - " + bh + " - sw: " + sw + " - " + sh );

	return { 'bh' : bh, 'bw' : bw, 'sh' : sh, 'sw' : sw };
};

liwe.lightbox._calc_size = function ( w, h, x, y )
{
	var size = liwe.lightbox._get_size () ;

	if ( ! w ) w = 0;
	if ( ! h ) h = 0;
	if ( ! x ) x = 0;
	if ( ! y ) y = 0;

	y = size.sh + 5;
	x = Math.abs ( size.bw - w ) / 2;
// y = Math.abs ( size.bh - h ) / 2;

	return [ w, h, x, y ];
};

liwe.lightbox._get_highest_zindex = function ()
{
	var el = liwe.lightbox._max_zindex_el;
	var z = 0, tmp, val;
	var elems = document.getElementsByTagName ( el );
	for ( var c = 0; c < elems.length; c++ )
			{
				//if ( document.defaultView ) val = document.defaultView.getComputedStyle ( elems[c], null ).getPropertyValue ( 'z-index' );
				if ( elems [ c ].currentStyle ) val = elems [ c ].currentStyle [ 'zIndex' ];
				if ( window.getComputedStyle ) val = window.getComputedStyle ( elems[c], null ).getPropertyValue ( 'z-index' );

				tmp = parseInt ( val, 10 );
			
				if ( ( ! isNaN ( tmp ) ) && ( tmp  > z ) ) z = tmp;
			} 
	return z;
};


/*
 * fx.js
 *
 * Copyright (C) 2006 - OS3 srl - http://www.os3.it
 *
 * Written by: Fabio Rotondo - fabio.rotondo@os3.it
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * version 2 of the License ONLY.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this software; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * NOTE: this is the GPL version of the library. If you want to include this 
 *       library inside a CLOSED SOURCE / PROPRIETARY software, you need 
 *       to purchase a COMMERCIAL LICENSE. See http://www.os3.it/license/
 *       for more info.
 */

// liwe.fx = {};	// Defined in liwe.js

liwe.fx.priv = {};	// Private methods

// PUBLIC: liwe.fx.set_opacity
//
// Setta la trasparenza dell'oggetto ``e``
// con il valore di alpha ``val``.
// ``val`` deve essere compreso tra 0 e 100
//
// Restituisce il valore di ``val`` assegnato all'oggetto
liwe.fx.set_opacity = function ( e, val )
{
        if ( val > 100 ) val = 100;
        if ( val < 0 ) val = 0;

        if ( e.filters )
        {
                if ( ! e.filters.alpha ) e.style.filter = "alpha(opacity=" + val + ")";
                e.filters.alpha.opacity = val;
        } else e.style.MozOpacity = val / 100;

	return val;
};



// DataSet 2.0
//
// 2009-01-10: 	- Dataset row now contain also:
//
// 			- ``_ds_row_num`` : the current row num
// 			- ``_ds_bg``:	a 0 / 1 value to distinguish odd / even rows
function DataSet ( name, ajax_cgi )
{
	DataSet._instances [ name ] = this;

	this.name = name;

	this.ajax = ajax_cgi;
	this.ajax_req = DataSet.ajax;
	this.num_rows = 0;	// Rows in totale dalla query
	this.rows = {};	// Rows in memoria
	this.len  = 0;		// Numero di rows in memoria
	this.page = 0;		// Pagina corrente
	this.lines_per_page = 10; // Linee per pagina
	this.from_row = 0;
	this.to_row   = 0;
	this.curr_doc = 0;	// Valore ordinale del documento corrente in FulShow
	this.paginator_links = 10;

	this.templates = {
				'table_start'  : '<table border="1" width="100%">',
				'table_end'    : '</table>',
				'table_header' : '',
				'table_footer' : '',
				'table_row'    : '',
				'prev_page'    : '',
				'next_page'    : '',
				'dash'         : ' - ',
				'next_doc'  : '',
				'prev_doc'  : ''
			 };

	
	this.cbacks = { 
		// Funzione ridefinibile da parte dell'utente per manipolare i dati
		// nel momento che vengono inseriti nell'array del DataSet
		'fill_manip' : null, 
		'prefetch_start' : null,
		'prefetch_end'   : null,
		'fill_start'   : null,
		'fill_end'   : null,
		'show_results' : null,
		'row_manip': null
	};

	// PRIVATE ATTRS
	this._attrs = {};
	this._form_fields = null;	// Campi della ricerca
	this._dest_div = null;
	this._fill_cback = null;

	// ========================================================================================
	// METHODS
	// ========================================================================================

	this._init_paginator = function ()
	{
		if ( ! window [ "Paginator" ] ) return null;

		var p = new Paginator ();

		p.templates [ 'pag-first' ] = "&lt;&lt;&lt;";
		p.templates [ 'pag-first-lnk' ] = "javascript:DataSet.page('" + this.name + "',0)";
		p.templates [ 'pag-last' ] = "&gt;&gt;&gt;";
		p.templates [ 'pag-last-lnk' ] = "javascript:DataSet.page('" + this.name + "',%(_TOT_PAGES)s)";
		p.templates [ 'pag-prev' ] = "&lt;";
		p.templates [ 'pag-prev-lnk' ] = "javascript:DataSet.page('" + this.name + "',%(_PREV)s)";
		p.templates [ 'pag-next' ] = '&gt;';
		p.templates [ 'pag-next-lnk' ] = "javascript:DataSet.page('" + this.name + "',%(_CURR_PAGE)s+1)";
		p.templates [ 'pag-pos' ] = '%(_PAGE)s';
		p.templates [ 'pag-pos-lnk' ] = "javascript:DataSet.page('" + this.name + "',%(_NUM)s)";
		p.templates [ 'pag-sep' ] = '|';
		p.templates [ 'pag-link-space' ] = '';

		return p;
	};

	this.paginator = this._init_paginator ();

	// This function sets the fields for the DataSet search
	this.set_fields = function ( fields )
	{
		this._form_fields = fields.clone ();
		this.clear ();
	};

	this.get_fields = function () { return this._form_fields; }

	this.del_field = function ( name ) { delete this._form_fields [ name ]; };

	this.rename_field = function ( old_field_name, new_field_name )
	{
		this._form_fields [ new_field_name ] = this._form_fields [ old_field_name ];
		delete this._form_fields [ old_field_name ];
	};

	this.clear = function ()
	{
		this.page = 0;
		this.num_rows = 0;
		this.from_row = 0;
		this.to_row   = this.lines_per_page;
		this.rows = {};
		this.len = 0;

		if ( this._form_fields )
		{
			this._form_fields [ "_X_START_POINT" ] = 0;
			this._form_fields [ "_X_PAGE" ] = 0;
		}

		this._attrs = {};
	};

	this.fill = function ( fill_callback, replace )
	{
		var _obj = this;

		if ( fill_callback ) this._fill_cback = fill_callback;

		if ( ! this._form_fields ) 
		{
			this._fill_cback ( this );
			return;
		}

		if ( this.cbacks [ 'fill_start' ] ) this.cbacks [ 'fill_start' ] ( this );

		this._form_fields [ '_X_LINES' ] = this.lines_per_page; 

		this.ajax_req ( this.ajax, this._form_fields, function ( vars ) { _obj._fill_done ( vars, _obj._fill_cback, replace ); } );
	};

	this._fill_done = function ( vars, cback, replace )
	{
		var t, len = parseInt ( vars [ 'lines' ] );

		if ( vars [ '_X_START_POINT' ] )		
			this.from_row = vars [ '_X_START_POINT' ];
		else 
			this.from_row = vars [ 'from_row' ];

		if ( ! this.from_row ) this.from_row = 0;

		for ( t = 0; t < len; t ++ )
		{
			if ( ! vars [ 'row' + t ] ) break;

			vars [ "row" + t ] [ 'ds_name' ] = this.name;

			var row = vars [ 'row' + t ];
			var row_index = row [ '_pos' ]; // this.from_row + t;

			if ( this.cbacks [ 'fill_manip' ] )
				this.rows [ row_index ] = this.cbacks [ 'fill_manip' ].call ( this, row );
			else
				this.rows [ row_index ] = row;
		}

		// FABIO: aggiunto 2009-07-13
		// FIXME: forse non serve
		this.to_row = this.from_row + len;

		this.num_rows = vars [ 'rows' ];

		if ( this.cbacks [ 'fill_end' ] ) this.cbacks [ 'fill_end' ] ( this, vars );

		if ( cback ) cback ( this );
	};

	this.needs_prefetch = function ( row_num )
	{
		if ( row_num >= this.num_rows ) row_num = this.num_rows -1;
		if ( this.rows [ row_num ] ) return false;

		var start = Math.floor ( row_num / this.lines_per_page ) * this.lines_per_page;
		var end   = start + this.lines_per_page -1;

		if ( end >= this.num_rows ) end = this.num_rows -1;

		if ( ! this.rows [ start ] ) return true;
		if ( ! this.rows [ end ] ) return true;

		return false;
	};

	this.prefetch = function ( num, cback )
	{
		if ( ! this.needs_prefetch ( num ) ) return cback ( this );

		var start = Math.floor ( num / this.lines_per_page ) * this.lines_per_page;

		this._form_fields [ '_X_START_POINT' ] = start;

		if ( this.cbacks [ 'prefetch_start' ] ) this.cbacks [ 'prefetch_start' ] ( this );

		this.fill ( cback );

		return true;
	};


	this.get_row = function ( num )
	{
		var row;

		if ( num >= this.num_rows ) return null;

		row = this.rows [ num ];

		return row;
	};

	this.filter_date = function ( s )
	{
		var g = parseInt ( s.replace ( /[^0-9]*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/, "$1" ) );
		var m = parseInt ( s.replace ( /[^0-9]*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/, "$2" ) );
		var a = s.replace ( /.*([0-9][0-9]*)-([0-9][0-9]*)-([0-9][0-9][0-9][0-9]).*/, "$3" );
		var pre = s.replace ( /([^0-9]*)[0-9][0-9]*-[0-9][0-9]*-[0-9][0-9][0-9][0-9].*/, "$1" );
		var post = s.replace ( /.*[0-9][0-9]*-[0-9][0-9]*-[0-9][0-9][0-9][0-9](.*)/, "$1" );

		if ( g < 10 ) g = "0" + g;
		if ( m < 10 ) m = "0" + m;

		return pre + g + "/" + m + "/" + a + post;
	};

	this.show_results_table = function ( dest_div, render_cback )
	{
		console.warn ( "DataSet WARNING: show_results_table() has been deprecated. Use render()" );
		this.render ( dest_div, render_cback );
	};

	this.render = function ( dest_div, render_cback )
	{
		var _obj = this;

		if ( ! dest_div ) dest_div = this._dest_div;
		this._dest_div = dest_div;

		this.prefetch ( this.from_row, function ( ds ) { _obj._render_done ( dest_div, render_cback ); } );
	};

	this._render_done = function ( dest_div, render_cback )
	{
		var s = '';

		this._prepare_pagination ();

		s = this.to_string ();

		$( dest_div ).innerHTML = s;

		if ( ! render_cback ) render_cback = this.cbacks [ 'show_results' ];
		if ( render_cback ) render_cback ( this );
	};

	this.refresh = function ( cback )
	{
		this._form_fields [ '_X_START_POINT' ] = this.from_row;
		this.fill ( cback, true );
	};

	this.to_string = function ()
	{
		var s = '';
		var t, row;

		s += String.formatDict ( this.templates [ 'table_start' ], this._attrs );
		s += String.formatDict ( this.templates [ 'table_header' ], this._attrs );

		// Ho messo <= in 'to_row' perche' altrimenti salta la prima riga
		// for ( t = 0; t < this.len; t ++ )
		for ( t = this.from_row; t < this.to_row ; t ++ )
		{
			row = this.get_row ( t ); 
			//console.debug ( "ROW: %s" + row );

			if ( ! row ) continue;

			if ( t > this.num_rows ) break;

			row [ 'ds_name' ] = this.name;
			row [ '_ds_row_num' ] = t;
			row [ '_ds_bg' ] = t % 2;

			if ( this.cbacks [ "row_manip" ] ) this.cbacks [ "row_manip" ] ( this, row );

			s += String.formatDict ( this.templates [ 'table_row' ], row );
		}

		s += String.formatDict ( this.templates [ 'table_footer' ], this._attrs );
		s += String.formatDict ( this.templates [ 'table_end' ], this._attrs );

		return s;
	};

	this._prepare_pagination = function ()
	{
		var delta    = this.to_row - this.from_row;
		var res, to_row, num_rows;

		res = this.from_row + 1;
		to_row = this.to_row;
		num_rows = this.num_rows;

		if ( to_row > num_rows ) to_row = num_rows;

		if ( num_rows <= this.lines_per_page )
			this._attrs [ 'docs_shown' ] = to_row;
		else
			this._attrs [ 'docs_shown' ] = res + " - " + to_row + " di " + num_rows;

		this._attrs [ 'from_row' ] = res;
		this._attrs [ 'to_row' ] = to_row;
		this._attrs [ 'num_rows' ] = num_rows;

		if ( this.page ) 
			this._attrs [ '_prev_page' ] = "javascript:DataSet.page('" + this.name + "'," + ( this.page -1 ) +")";
		else
			this._attrs [ '_prev_page' ] = null;

		if ( this.to_row < this.num_rows )
			this._attrs [ '_next_page' ] = "javascript:DataSet.page('" + this.name + "'," + ( this.page +1 ) + ")";
		else
			this._attrs [ '_next_page' ] = null;

		if ( this._attrs [ '_prev_page' ] )
			this._attrs [ 'prev_page' ] = String.formatDict ( this.templates [ 'prev_page' ], this._attrs );
		else
			this._attrs [ 'prev_page' ] = "&nbsp;";

		if ( this._attrs [ '_next_page' ] )
			this._attrs [ 'next_page' ] = String.formatDict ( this.templates [ 'next_page' ], this._attrs );
		else
			this._attrs [ 'next_page' ] = "&nbsp;";

		if ( this.page && ( this.to_row < this.num_rows ) )
			this._attrs [ 'dash' ] = this.templates [ "dash" ];
		else
			this._attrs [ 'dash' ] = "";

		if ( this.paginator )
		{
			this.paginator.init ( this.num_rows, this.lines_per_page, this.paginator_links );
			this.paginator.set_page ( this.page );
			this._attrs [ "paginator" ] = this.paginator.mk_str ();
		}
		else
			this._attrs [ "paginator" ] = "Include paginator.js";
	};

	this.show_page = function ( page )
	{
		this.page = page;

		this.from_row = this.lines_per_page * page;
		this.to_row = this.lines_per_page * ( page +1 );

		this.render ();
	};

	this.format_str = function ( template )
	{
		return String.formatDict ( template, this._attrs );
	};

	this.set_curr_doc   = function ( pos ) { 
		if ( pos === undefined ) pos = -1;
		this.curr_doc = pos; 
	};

	this.prepare_result_navi = function ( cback )
	{
		var _obj = this;

		if ( this.curr_doc == -1 ) return;

		this.prefetch ( this.curr_doc + 2, function ( ds ) { _obj.result_navi ( ds, cback ); } );
	};

	this.result_navi = function ( ds, cback )
	{
		if ( this._form_fields && this.needs_prefetch ( this.curr_doc +2 ) ) 
		{
			var _obj = this;
			this.prefetch ( this.curr_doc +2, function ( ds ) { _obj.result_navi ( ds, cback ); } );
			return;
		}

		var s = '';
		var row;
		
		if ( this.curr_doc > 0 )
		{
			// Posso tornare indiretro
			row = this.rows [ this.curr_doc -1 ];
			this._attrs [ 'prev_doc' ] = String.formatDict ( this.templates [ 'prev_doc' ], row );

			// 'javascript:DataSet.doc(\'' + this.name + '\',\'' + row.get ( 'id' ) + '\',{pos: ' + ( this.curr_doc -1 ) + '})';
		} else
			this._attrs [ 'prev_doc' ] = null;

		if ( this.curr_doc < this.num_rows -1 )
		{
			// Posso andare avanti
			row = this.rows [ this.curr_doc +1 ];
			this._attrs [ 'next_doc' ] = String.formatDict ( this.templates [ 'next_doc' ], row );
			// this._attrs [ 'next_doc' ] = 'javascript:DataSet.doc(\'' + this.name + '\',\'' + row.get ( 'id' ) + '\',{pos: ' + ( this.curr_doc +1 ) + '})';
		} else
			this._attrs [ 'next_doc' ] = null;

		if ( cback ) cback ( ds );
	}

}

DataSet._instances = {};

DataSet.get = function ( instance_name )
{
	return DataSet._instances [ instance_name ];
};

DataSet.page = function ( name, page_no )
{
	var ds = DataSet._instances [ name ];

	ds.show_page ( page_no );
};

DataSet.ajax = function ( ajax, fields, cback ) { liwe.AJAX.request ( ajax, fields, cback, true ); };


liwe.cookie = {};

/*
	Funzione per calcolare la data di scadenza.
	
	INPUT:
		- days
		- hours
		- minutes

		Somma di giorni/ore/minuti da sommare a ``now``
		per la validita' del cookie. I valori sono tutti
		interi. E' possibile passare numeri negativi.
*/
liwe.cookie.get_exp_date = function ( days, hours, minutes )
{
	var exp_date = new Date ();

	exp_date.setDate ( exp_date.getDate () + parseInt ( days ) );
	exp_date.setHours ( exp_date.getHours () + parseInt ( hours ) );
	exp_date.setMinutes ( exp_date.getMinutes () + parseInt ( minutes ) );

	return exp_date.toGMTString ();
};


// Rimuove un cookie (lo fa scadere).
// I parametri ``path`` e ``domain`` sono opzionali.
liwe.cookie.del = function ( name, path, domain )
{
	if ( this.get ( name ) )
	{
		document.cookie = name + "=" + 
			( ( path ) ? 	"; path=" + path : "" ) +
		 	( ( domain ) ? 	"; domain=" + domain : "" ) +
			"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
};

/*
	Restituisce il valore di un cookie dato il nome
*/
liwe.cookie.get = function ( name )
{
	var arg = name + "=";
	var alen = arg.length;	
	var clen = document.cookie.length;
	var i = 0;

	while ( i < clen )
	{
		var j = i + alen;
		if ( document.cookie.substring ( i, j ) == arg ) return liwe.cookie._get_val ( j );

		i = document.cookie.indexOf ( " ", i ) + 1;
		if ( i == 0 ) break;
	}

	// Se sono arrivato fino a qui, non ho trovato il cookie ``name`` e quindi
	// restituisco stringa vuota.
	return "";
};

// Setta un cookie i parametri oltre ``name`` e ``value`` sono opzionali
liwe.cookie.set = function ( name, value, expires, path, domain, secure )
{
	document.cookie = name + "=" + escape ( value ) + 
		( ( expires ) ? "; expires=" + expires : "" ) +
		( ( path )    ? "; path=" + path : "" ) +
		( ( domain )  ? "; domain=" + domain : "" ) +
		( ( secure )  ? "; secure" : "" );
};

/* =====================================================================
   FUNZIONI INTERNE
 ==================================================================== */

liwe.cookie._get_val = function ( offset )
{
	var end_str = document.cookie.indexOf ( ";", offset );

	if ( end_str == -1 ) end_str = document.cookie.length;

	return unescape ( document.cookie.substring ( offset, end_str ) );
};


var kernel = {};
var modules = {};


kernel.StopExecutionException = {};


kernel.load = function ()
{
	kernel._ajax_reqs = 0;

	if ( $ ( "ajax_wait" ) )
	{
		if ( liwe.AJAX [ "cbacks" ] )
		{
			liwe.AJAX.cbacks [ "req-start" ] = kernel._start_ajax_req;
			liwe.AJAX.cbacks [ "req-end" ] = kernel._end_ajax_req;
		}
		else
		{
			liwe.AJAX.start_req_handler = kernel._start_ajax_req;
			liwe.AJAX.end_req_handler = kernel._end_ajax_req;
		}
	}

	if ( liwe.AJAX [ "cbacks" ] )
		liwe.AJAX.cbacks [ "req-error" ] = kernel._error_handler;
	else
		liwe.AJAX.error_handler = kernel._error_handler;

	kernel._init_login ();

	kernel._check_logged ();

	if ( window [ "DataSet" ] )
	{
		DataSet.ajax = function ( ajax, fields, cback ) {
			kernel.ajax ( "/cgi-bin/FulQuery", fields, cback );
		};
	}
};


kernel._check_logged = function ()
{
	kernel.command ( "get_opere", {},
		function ( v )
		{
			if ( v [ "login" ] )
				Login.render_logged ( v, site.login_div_name );
			else
				kernel.on_login ( v );
		}
	);
};


kernel._init_login = function ()
{
	if ( site && site.login_form_data )
	{
		Login.templates [ 'logged' ] = site.templates [ 'logged' ];

		Login.init ( 
				site.login_form_data.get ( 'div_logged', '' ),
				site.login_form_data.get ( 'form_id', '' ),
				site.login_form_data.get ( 'login_id', '' ),
				site.login_form_data.get ( 'pwd_id', '' ),
				site.login_form_data.get ( 'btn_id', '' )
			);
	}

	Login.events [ 'login' ] = kernel.on_login;
	//Login.render ();
};


kernel.on_login = function ( v )
{
	function _set_listener ( mod )
	{
		liwe.history.set_listener ( function ( dict, data ) { kernel._mod_listener ( mod, dict, data ); }, mod );
	}

	kernel.user_info = v;

	var mod;
	for ( mod in modules )
	{
		if ( typeof modules [ mod ] == "function" ) continue;
		_set_listener ( mod );
	}

	if ( site.on_login )
	{
		try
		{
			site.on_login ( v );
		}
		catch ( e )
		{
			if ( e != kernel.StopExecutionException )
				throw e;
		}
	}

	liwe.history.set_listener ( function ( dict, data ) { kernel._mod_listener ( site.default_module, dict, data ); } );
	liwe.history.init ();
};


kernel.init_module = function ( mod_name, dict, data )
{
	try
	{
		var mod = modules [ mod_name ];

		var navi_path_data = null;
		if ( data )
		{
			data = data.clone ();
			navi_path_data = data.get ( "_navi_path_data" );
			if ( navi_path_data )
				delete data [ "_navi_path_data" ];

			if ( data.count () == 0 )
				data = null;
		}

		kernel.init ( mod_name, dict, data, navi_path_data, function ()
		{
			site.init ( mod_name, dict, data );
			mod.init ( dict, data );
		} );

		/*
		if ( dict [ "__sy" ] )
			window.scrollTo ( 0, parseInt ( dict [ "__sy" ], 10 ) );
		*/
	}
	catch ( e )
	{
		if ( e != kernel.StopExecutionException )
			throw e;
	}
};


kernel._mod_listener = function ( mod_name, dict, data )
{
	var mod = modules [ mod_name ];
	if ( mod ) kernel.init_module ( mod_name, dict, data );
};


kernel._start_ajax_req = function ( req )
{
	kernel._ajax_reqs ++;
	
	var div = $ ( "ajax_wait" );
	if ( div ) div.style.display = "block";
};

kernel._end_ajax_req = function ( req )
{
	if ( ! --kernel._ajax_reqs )
	{
		var div = $ ( "ajax_wait" );
		if ( div ) div.style.display = "none";
	}
};


kernel.init = function ( module, dict, data, navi_path_data, cback )
{
	var navi_path = site.navi_path;
	var add = false;
	var replace = false;

	if ( ! dict ) dict = {};
	var mask = dict.get ( "mask", "m:main" );
	if ( mask.substr ( 0, 2 ) == "m:" )
	{
		dict [ "mask" ] = mask.substr ( 2 );
	}
	else if ( mask.substr ( 0, 2 ) == "a:" )
	{
		dict [ "mask" ] = mask.substr ( 2 );
		add = true;
	}
	else if ( mask.substr ( 0, 2 ) == "r:" )
	{
		dict [ "mask" ] = mask.substr ( 2 );
		add = true;
		replace = true;
	}
	else
	{
		var mode = site.get ( "navi_path_reset_mode", "on_request" );
		if ( mode != "always" )
			add = true;
	}

	function _post_init ()
	{
		if ( kernel.module )
		{
			if ( modules [ kernel.module ] && modules [ kernel.module ][ "fini" ] )
				modules [ kernel.module ].fini ();
		}

		kernel.module = module;
		kernel.history_dict = dict;
		kernel.history_data = data;

		kernel._ajax_error_handlers = {};

		cback ();
	}

	if ( navi_path )
	{
		if ( NaviPath._version == 1 )
		{
			if ( add )
			{
				if ( navi_path_data ) navi_path.set_status ( navi_path_data );
				if ( replace ) navi_path.back ();
			}
			else
			{
				navi_path.clear ();
			}

			_post_init ();
		}
		else if ( NaviPath._version == 2 )
		{
			if ( add )
			{
				navi_path.list ( function ()
				{
					if ( replace ) navi_path.back ( _post_init );
					else _post_init ();
				} );
			}
			else
			{
				navi_path.clear ( _post_init );
			}
		}
	}
	else
		_post_init ();
};


kernel.go = function ( module, params, data )
{
	liwe.AJAX.abort ( function () { kernel._go ( module, params, data ); } );
};

kernel._go = function ( module, params, data )
{
	if ( data ) data = data.clone ();

	if ( ! params ) params = { mask: 'm:main' };

	if ( site.navi_path && NaviPath._version == 1 )
	{
		if ( ! data ) data = {};
		data [ "_navi_path_data" ] = site.navi_path.get_status ();
	}
	else if ( site.navi_path && NaviPath._version == 2 )
	{
		var npid = site.navi_path.get_last_id ();
		if ( npid ) params [ "_npid" ] = npid;
	}

	/*if ( ! params [ "__sy" ] )
	{
		var sy = utils.getScrollXY () [ 1 ];
		params [ "__sy" ] = sy;
	}*/

	if ( module == "" )
	{
		liwe.history.add ( params, data );
		module = site.default_module;
	}
	else
		liwe.history.add_module ( module, params, data );

	kernel.init_module ( module, params, data );
};


kernel.show_mask = function ( mask, div_name, cback )
{
	kernel.ajax ( '/cgi-bin/FormParser', { msk: mask }, function ( v ) { 
		var scripts = v [ 'scripts' ];
		var l = scripts.length;
		for ( t = 0; t < l; t ++ )
			liwe.utils.append_js ( scripts [ t ] );

		if ( v [ 'check_for' ] )
			utils.multi_wait ( v [ 'check_for' ], function () {
				kernel._form_done ( v, div_name, mask, cback );
			} );    
		else    
			kernel._form_done ( v, div_name, mask, cback );
	} );            
};


kernel._form_done = function ( v, div_name, mask, cback )
{
	$ ( div_name ).innerHTML = v [ 'mask' ];

	if ( v [ "codes" ] )
	{
		var i, l = v.codes.length;
		for ( i = 0; i < l; i ++ )
			eval ( v.codes [ i ] );
	}

	v [ "original_mask" ] = $ ( div_name ).innerHTML;

	if ( cback ) cback ( v, mask );
};


kernel.quit = function ()
{
	throw kernel.StopExecutionException;
};


// da chiamare quando si preme su "Cerca" per aggiornare la history
kernel.add_history_data = function ( module, params, fields, cback )
{
	liwe.AJAX.abort ( function () { kernel._add_history_data ( module, params, fields, cback ); } );
};

kernel._add_history_data = function ( module, params, fields, cback )
{
	if ( fields ) fields = fields.clone ();
	if ( site.navi_path && NaviPath._version == 1 )
	{
		if ( ! fields ) fields = {};
		fields [ "_navi_path_data" ] = site.navi_path.get_status ();
	}
	else if ( site.navi_path && NaviPath._version == 2 )
	{
		var npid = site.navi_path.get_last_id ();
		if ( npid ) params [ "_npid" ] = npid;
	}

	if ( ! params ) params = { mask: 'm:main' };

	/*if ( ! params [ "__sy" ] )
	{
		var sy = utils.getScrollXY () [ 1 ];
		params [ "__sy" ] = sy;
	}*/

	liwe.history.add_module ( module, params, fields );

	if ( params )
	{
		params = params.clone ();
		var mask = params.get ( "mask" );
		if ( mask && ( mask.startsWith ( "m:" ) || mask.startsWith ( "a:" ) || mask.startsWith ( "r:" ) ) )
		{
			mask = mask.substr ( 2 );
			params [ "mask" ] = mask;
		}
	}

	kernel.module = module;
	kernel.history_dict = params;
	kernel.history_data = fields;

	if ( cback ) cback ();
};


kernel.replace_history_data = function ( module, params, fields, cback )
{
	liwe.AJAX.abort ( function () { kernel._replace_history_data ( module, params, fields, cback ); } );
};

kernel._replace_history_data = function ( module, params, fields, cback )
{
	if ( fields ) fields = fields.clone ();

	if ( site.navi_path && NaviPath._version == 1 )
	{
		if ( ! fields ) fields = {};
		fields [ "_navi_path_data" ] = site.navi_path.get_status ();
	}

	if ( ! params ) params = { mask: 'm:main' };

	/*if ( ! params [ "__sy" ] )
	{
		var sy = utils.getScrollXY () [ 1 ];
		params [ "__sy" ] = sy;
	}*/

	liwe.history.replace ( module, params, fields );

	if ( params )
	{
		params = params.clone ();
		var mask = params.get ( "mask" );
		if ( mask && ( mask.startsWith ( "m:" ) || mask.startsWith ( "a:" ) || mask.startsWith ( "r:" ) ) )
		{
			mask = mask.substr ( 2 );
			params [ "mask" ] = mask;
		}
	}

	kernel.module = module;
	kernel.history_dict = params;
	kernel.history_data = fields;

	if ( cback ) cback ();
};


kernel.ajax = function ( url, vars, cback, easy )
{
	if ( typeof easy == "undefined" ) easy = true;

	liwe.AJAX.request ( url, vars, function ( v ) {
		if ( ! cback ) return;
		try
		{
			cback ( v );
		}
		catch ( e )
		{
			if ( e != kernel.StopExecutionException )
				throw e;
		}
	}, easy );
};


kernel.command = function ( command, dict, cback )
{
	if ( ! dict ) dict = {};
	dict [ "command" ] = command;
	kernel.ajax ( "/cgi-bin/AjaxCmd", dict, cback );
};


kernel.fulquery = function ( fq, cback )
{
	var fields = {};
	fq.fill ( fields );
	kernel.ajax ( "/cgi-bin/FulQuery", fields, cback );
};


kernel._ajax_error_handlers = {};

kernel.set_ajax_error_handler = function ( code, cback )
{
	if ( code.constructor !== Array )
		code = [ code ];

	var i, l = code.length;
	for ( i = 0; i < l; i ++ )
		kernel._ajax_error_handlers [ code [ i ] ] = cback;
};


kernel._error_handler = function ( v, err_descr, err_code, ajax_resp )
{
	if ( ajax_resp ) v = ajax_resp;

	var code = v [ "err_code" ];
	var descr = v [ "err_descr" ];

	var h = kernel._ajax_error_handlers [ code ];
	if ( h )
	{
		h ( v );
		return;
	}

	switch ( code )
	{
		case 1:		// LIBDEA_ERR_BAD_LOGIN
			if ( kernel.user_info [ "login" ] )
			{
				liwe.AJAX.abort ();
				alert ( "Attenzione! La sessione e' scaduta, sara' necessario effettuare nuovamente l'accesso." );
				Login.logout ();
				break;
			}
			//FALLTHROUGH!!!

		default:
			console.error ( "ERRORE: [" + code + "] " + descr );
			if ( site && site.error_handler ) site.error_handler ( v );
			else alert ( descr );
			break;
	}
};

// Registro l'evento principale nell'onload della finestra
liwe.events.add ( window, "load", kernel.load );



var LinkReplacer = {};

LinkReplacer.scroll_parent = null;


LinkReplacer._anchors = {};


LinkReplacer.lnk2span = function ( txt )
{
	if ( ! txt ) return "";
	var s = txt.replace ( /<(.?)lnk/ig, "<$1span" );
	return s;
};

LinkReplacer.replace = function ( replace_link_cback, prnt )
{
	if ( ! prnt ) prnt = document;

	var lnks = prnt.getElementsByTagName ( "span" );
	var lnk, l, t;
	var txt;
	var a, href;
	var res = [];

	l = lnks.length;

	for ( t = 0; t < l; t ++ )
	{
		lnk = lnks [ t ];

		if ( ! lnk.getAttribute ( 'opera' ) && ! lnk.getAttribute ( 'tipolink' ) ) continue;

		var cls = lnk.getAttribute ( 'class' ) || lnk.getAttribute ( 'className' );

		txt = lnk.innerHTML;
		href = replace_link_cback ( lnk );

		a = document.createElement ( 'a' );
		a.setAttribute ( 'href', href );

		if ( cls )
		{
			if ( utils.get_browser().startsWith("IE7") ) a.setAttribute ( 'className', cls );
			else a.setAttribute ( 'class', cls );
		}

		a.innerHTML = txt;

		res.push ( [ a, lnk ] );
	}

	l = res.length;
	for ( t = 0; t < l; t ++ )
	{
		lnk = res [ t ] [ 1 ];
		lnk.parentNode.replaceChild ( res [ t ] [ 0 ], lnk );
	}
};


LinkReplacer.replace_anchors = function ( el, skip_class_check )
{
	if ( ! el ) el = document;

	var as = el.getElementsByTagName ( "a" );
	var a, l, t;
	var name, href = false;

	l = as.length;

	for ( t = 0; t < l; t ++ )
	{
		a = as [ t ];

		name = a.getAttribute ( 'name' );
		if ( name )
			LinkReplacer._anchors [ name ] = a;

		try {
			href = a.getAttribute ( 'href' );
		} catch ( e ) {
			href = false;
		}

		if ( ! href ) continue;

		if ( ! skip_class_check && a.className != "cds_rif_nota" && a.className != "cds_rimando_nota" ) continue;

		href = href.split ( "#" );
		if ( href.length > 1 && ( ( ! href [ 0 ] ) || href [ 0 ] == ( location.protocol + "//" + location.hostname + location.pathname + location.search ) ) )
		{
			href = href [ 1 ];
			a.setAttribute ( 'href', "javascript:LinkReplacer.scroll('" + href + "')" );
		}
	}
};


LinkReplacer.scroll = function ( name )
{
	var a = LinkReplacer._anchors [ name ];
	if ( ! a )
	{
		var i, l = document.anchors.length;
		for ( i = 0; i < l; i ++ )
		{
			if ( document.anchors [ i ].name == name )
			{
				a = document.anchors [ i ];
				break;
			}
		}
	}
	if ( ! a )
	{
		console.warn ( "Manca l'anchor con NAME '" + name + "'" );
		return;
	}

	var pos = liwe.dom.get_offset_top ( a );

	if ( LinkReplacer.scroll_parent )
	{
		var p2 = liwe.dom.get_offset_top ( LinkReplacer.scroll_parent );
		LinkReplacer.scroll_parent.scrollTop = pos - p2;
	}
	else
		window.scrollTo ( 0, pos );
};


LinkReplacer.set_hl_navi = function ( el, first_el )
{
	if ( ! el ) el = document;

	var spans = el.getElementsByTagName ( "span" );
	var i, l = spans.length;
	var count = 0;
	var h, dest;
	var s_spans = [];
	var l_spans = [];

	for ( i = 0; i < l; i ++ )
	{
		var span = spans [ i ];
		if ( span.className != "highlight" ) continue;

		var p = span.parentNode;
		while ( p )
		{
			if ( p.tagName == "A" )
			{
				span._in_link = p;
				l_spans.push ( span );
				break;
			}

			p = p.parentNode;
		}

		LinkReplacer._anchors [ "_hl_span" + count ] = span;

		s_spans.push ( span );
		count ++;
	}

	l = l_spans.length;
	for ( i = 0; i < l; i ++ )
		LinkReplacer._fix_span_in_link ( l_spans [ i ] );

	for ( i = 0; i < count; i ++ )
	{
		span = s_spans [ i ];

		if ( span._in_link )
			span = span._in_link;

		if ( i > 0 )
		{
			// aggiungo la freccia PRIMA
			h = document.createElement ( "a" );
			h.href = "javascript:LinkReplacer.scroll('_hl_span" + ( i - 1 ) + "')";
			h.innerHTML = '<img border="0" alt="" src="/gfx/ft_prev.gif" style="margin-right: 2px" />';

			span.parentNode.insertBefore(h, span);
		}

		if ( i < count - 1 )
		{
			// aggiungo la freccia DOPO
			h = document.createElement ( "a" );
			h.href = "javascript:LinkReplacer.scroll('_hl_span" + ( i + 1 ) + "')";
			h.innerHTML = '<img border="0" alt="" src="/gfx/ft_next.gif" style="margin-left: 2px" />';

			dest = span.nextSibling;
			if (dest)
				span.parentNode.insertBefore(h, dest);
			else
				span.parentNode.appendChild(h);
		}
	}

	if ( first_el )
	{
		if ( count )
		{
			first_el.innerHTML = '<a href="javascript:LinkReplacer.scroll(\'_hl_span0\')">' +
				'<img alt="Prima occorrenza" border="0" src="/gfx/ft_first.gif" /></a>';
			first_el.style.display = "block";
		}
		else
			first_el.style.display = "none";
	}
};


LinkReplacer._fix_span_in_link = function ( s )
{
	var before = [];

	var lnk = s._in_link;
	while (lnk.childNodes.length > 0)
	{
		var el = lnk.childNodes [ 0 ];

		lnk.removeChild ( el );

		if ( el == s )
			break;
		else
			before.push ( el );
	}

	var a = lnk.cloneNode(false);

	var i, l = before.length;
	for ( i = 0; i < l; i ++ )
		a.appendChild ( before [ i ] );

	lnk.parentNode.insertBefore ( a, lnk );

	a = lnk.cloneNode(false);
	a.appendChild ( s );
	lnk.parentNode.insertBefore ( a, lnk );

	s._in_link = a;
};



//{{{ FulQuery ()
function FulQuery ()
{
	this.mode = '';
	this.db_name = '';
	this.resource = '';
	this.order_by = '';
	this.group_by = '';
	this.highlight = false;
	this.opera = '';
	this.operasez = '';
	this.tail_where = '';  // Aggiunge una stringa alla fine delle condizioni WHERE
	this.distinct = 0;
	this.skip_text_status = true; // Falg T/F. Se T, setta _X_SKIP_TEXT_STATUS

	this.key_overwrite = true;  // Flag T/F. Se T, sovrascrive i campi di fq.add()

	// <VerQuery specific>
	this.bucket = '';
	this.buckets = '';
	// </VerQuery specific>

	this.lines = 10;
	this.page  = 0;

	this.clear 	= fulquery_clear;
	this.add	= fulquery_add;
	this.query	= fulquery_query;
	this.add_date	= fulquery_add_date;
	this.del	= fulquery_del;
	this.fill 	= fulquery_fill;
	this.set_fields = fulquery_set_fields;
	this.set_fields_by_list = fulquery_set_fields_by_list;
	this.set_biblio = fulquery_set_biblio;
	this.corr_search = fulquery_corr_search;

	this.biblio = {
		ckey  : null,
		user  : null,
		field : null,
		mode  : null		
	};

	this.corr = {
		key : null,
		dbname : null,
		tipo : null
	};

	this.set_id 	= fulquery_set_id;

	this._conds = [];
	this._fields = null;
	this._doc_text = '';
	this._id1 = '';
	this._id2 = '';
	this._query_full = '';

	// Variabili di supporto per il Multi Query
	this._multi = [];
}
//}}}


function fulquery_set_biblio ( ckey, dbuser, dbfield, mode )
{
	this.biblio.ckey  = ckey;
	this.biblio.user  = dbuser;
	this.biblio.field = dbfield;
	this.biblio.mode  = mode;
}

function fulquery_corr_search ( key, tipo, dbname )
{
	this.mode = "SEARCH_CORR";
	
	this.corr.key = key;
	this.corr.tipo = tipo;
	this.corr.dbname = dbname;
}

//{{{ fulquery_clear ()
function fulquery_clear ()
{
	this.mode = '';
	this.db_name = '';
	this.order_by = '';
	this.group_by = '';
	this.distinct = 0;
	this.resource = '';
	this.highlight = false;
	this.page = 0;
	this.lines = 10;

	this._conds  = [];
	this._fields = [];
	this._doc_text = '';
	this._id1 = '';
	this._id2 = '';

	this.biblio.ckey  = null;
	this.biblio.user  = null;
	this.biblio.field = null;
	this.biblio.mode  = null;

	this.corr.key = null;
	this.corr.dbname = null;
	this.corr.tipo = null;
}
//}}}
//{{{ fulquery_add ( field, mode, value, db_field, prepend, append, base )
/*
	field		-> nome del campo (es. "NATURA")
	mode		-> modalita' di ricerca (es. "IN_STR")
	value		-> valore da ricercare ( es. 'L.|D.Lgs.|DM.' )
	db_field	-> campo del db associato al field (di default == field, es. "DATAGU")
	prepend		-> stringa da prependere al valore 
	append		-> stringa da appendere al valore
	base		-> base dei campi data [NOTA: solo per campi data] (es. "GU" per "GUGIORNO1" ... )
*/
function fulquery_add ( field, mode, value, db_field, prepend, append, base )
{
	mode = mode.toUpperCase ();

	if ( this.key_overwrite ) this.del ( field );

	this._conds.push ( [ field, mode, value, db_field, prepend, append, base ] );

	if ( field.toUpperCase () == 'DOCUMENT_TEXT' )
		this._doc_text = value;
}
//}}}

function fulquery_query ( sql )
{
	this._query_full = sql;
}

//{{{ fulquery_add_date ( anno1, mese1, giorno1, anno2, mese2, giorno2, db_field, prepend, append, base )
function fulquery_add_date ( anno1, mese1, giorno1, anno2, mese2, giorno2, db_field, prepend, append, base )
{
	if ( ! base ) base = "";
	this._conds.push ( [ base + "ANNO1", "DATA", anno1, db_field, prepend, append, base ] );
	this._conds.push ( [ base + "MESE1", "DATA", mese1, db_field, prepend, append, base ] );
	this._conds.push ( [ base + "GIORNO1", "DATA", giorno1, db_field, prepend, append, base ] );
	this._conds.push ( [ base + "ANNO2", "DATA", anno2, db_field, prepend, append, base ] );
	this._conds.push ( [ base + "MESE2", "DATA", mese2, db_field, prepend, append, base ] );
	this._conds.push ( [ base + "GIORNO2", "DATA", giorno2, db_field, prepend, append, base ] );
}
//}}}
//{{{ fulquery_del
function fulquery_del ( field )
{
	var i, l = this._conds.length;
	for ( i = 0; i < l; i ++ )
	{
		if ( this._conds [ i ] [ 0 ] == field )
		{
			this._conds.splice ( i, 1 );
			break;
		}
	}
}
//}}}
//{{{ fulquery_fill ( dst )
function fulquery_fill ( dst, prefix )
{
	var t, l;
	var cond;
	var s = '';
	var name;

	if ( ! prefix ) 
		prefix = "";
	else
		this._multi.push ( prefix );


	if ( ! this.opera )
	{
		console.error ( "[FulQuery]: manca l'opera !!!" );
		alert ( "[FulQuery]: manca l'opera !!!" );
		return;
	}

	// FIX: add prefix in already added fields
	/*
	if ( prefix )
	{
		var dst2 = dst.clone ();
		dst2.iterate ( function ( v, k ) { dst [ prefix + k ] = v; delete dst [ k ]; } );
	}
	*/
	// END FIX

	l = this._conds.length;

	// NEW: Contatore per campi duplicati
	var counters = {};	

	for ( t = 0; t < l; t ++ )
	{
		cond = this._conds [ t ];

		if ( typeof ( cond [ 2 ] ) == 'undefined' ) continue;

		// FIX: skippiamo anche i campi che hanno valore a ''
		//      forse questo ha un impatto su altri siti
		if ( cond [ 2 ] == '' ) continue;

		name = cond [ 0 ];

		count = counters.get ( name, 0 );
		counters [ name ] = count + 1;

		if ( count != 0 )
		{
			dst [ prefix + "_D_" + count + "_" + name ] = cond [ 2 ];
			dst [ prefix + "_M_" + count + "_" + name ] = cond [ 1 ];

			if ( cond [ 4 ] ) dst [ prefix + "_P_" + count + "_" + name ] = cond [ 4 ];
			if ( cond [ 5 ] ) dst [ prefix + "_A_" + count + "_" + name ] = cond [ 5 ];
		} else {
			// Condizione iniziale (count == 0), funziona come prima
			dst [ prefix + name ] = cond [ 2 ];

			dst [ prefix + "_M_" + name ] = cond [ 1 ];

			if ( cond [ 3 ] ) dst [ prefix + "_F_" + name ] = cond [ 3 ];
			if ( cond [ 4 ] ) dst [ prefix + "_P_" + name ] = cond [ 4 ];
			if ( cond [ 5 ] ) dst [ prefix + "_A_" + name ] = cond [ 5 ];
			if ( cond [ 6 ] ) dst [ prefix + "_B_" + name ] = cond [ 6 ];
		}
	}

	if ( ! this._fields ) this._fields = [];
	l = this._fields.length;
	for ( t = 0; t < l; t ++ )
	{
		if ( ! this._fields [ t ] ) continue;
		s += this._fields [ t ] + ":";
	}

	s = s.substr ( 0, s.length -1 );

	dst [ prefix + '_X_SEARCH_FIELDS' ] = s;
	dst [ prefix + '_X_MODE' ] = this.mode;
	dst [ prefix + '_X_LINES' ] = this.lines;
	dst [ prefix + '_X_PAGE' ] = this.page;
	dst [ prefix + '_X_DBNAME' ] = this.db_name;
	dst [ prefix + '_X_RESOURCE' ] = this.resource;
	dst [ prefix + '_X_FULL' ] = this._query_full;
	dst [ prefix + '_X_OPERA' ] = this.opera;

	if ( this.biblio.ckey )
	{
		dst [ prefix + '_X_BIBLIO' ] = this.biblio.ckey;
		dst [ prefix + '_X_BIBLIO_DBUSER' ] = this.biblio.user;
		dst [ prefix + '_X_BIBLIO_DBFIELD' ] = this.biblio.field;
		dst [ prefix + '_X_BIBLIO_MODE' ] = this.biblio.mode;
	}

	if ( this.mode == 'SEARCH_CORR' )
	{
		dst [ prefix + '_X_CORR_KEY' ] = this.corr.key;
		dst [ prefix + '_X_CORR_DBNAME' ] = this.corr.dbname;
		dst [ prefix + '_X_CORR_TIPO' ] = this.corr.tipo;
	}

	if ( this.skip_text_status ) dst [ prefix + '_X_SKIP_TEXT_STATUS' ] = 1;

	if ( this.operasez ) dst [ prefix + '_X_OPERASEZ' ] = this.operasez;

	if ( this.bucket ) dst [ prefix + '_X_BUCKET' ] = this.bucket;
	if ( this.buckets ) dst [ prefix + '_X_BUCKETS' ] = this.buckets;

	if ( this._id1 )
	{
		dst [ prefix + '_X_ID1' ] = this._id1;
		dst [ prefix + '_X_ID2' ] = this._id2;
	}

	if ( this.tail_where ) dst [ prefix + '_X_TAIL_WHERE' ] = this.tail_where;
	if ( this.group_by ) dst [ prefix + '_X_GROUP_BY' ] = this.group_by;
	if ( this.order_by ) dst [ prefix + '_X_ORDER_BY' ] = this.order_by;
	if ( this.highlight && this._doc_text ) dst [ prefix + '_X_HIGHLIGHT' ] = this._doc_text;
	if ( this.distinct ) dst [ prefix + '_X_DISTINCT' ] = "1";

	// Se multi e' settato, aggiungo _X_MULTI
	if ( this._multi.length ) dst [ '_X_MULTI' ] = ':'.join ( this._multi );

	// Cancello i dati in memoria
	if ( prefix ) this.clear ();
}
//}}}
//{{{ fulquery_set_fields ()
function fulquery_set_fields ()
{
	this._fields = arguments;
}
//}}}
// {{{ fulquery_set_fields_by_list ( lst )
function fulquery_set_fields_by_list ( lst )
{
	this._fields = lst; //.clone ();
}
// }}}

function fulquery_set_id ()
{
	var d = new Date ();
	
	this._id1 = d.getTime ().toString ();
	this._id2 = MD5.hex_md5 ( this._id1 );
}


var Login = {};

Login.templates = {};
Login._dest_div = '';
Login._dest_logged = '';
Login.login_command = "login";

//FORM FIELDS
Login._form_id = '';
Login._login_id = '';
Login._pwd_id = '';
Login._btn_id = '';

Login.events = {
		"login" : null,
		"logout" : null
		};

Login.init = function ( div_logged, form_id, login_id, pwd_id, btn_id )
{
	Login.set_ids ( div_logged, form_id, login_id, pwd_id, btn_id );

	Login._set_events ();
};

Login.set_ids = function ( div_logged, form_id, login_id, pwd_id, btn_id )
{
	Login._dest_logged = div_logged,
	Login._form_id  = form_id;
	Login._login_id = login_id;
	Login._pwd_id   = pwd_id;
	Login._btn_id   = btn_id;
};

Login._set_events = function ()
{
	if ( Login._form_id && $ ( Login._form_id ) ) $ ( Login._form_id ).setAttribute ( "action", "javascript:Login.login()" );
	else
	{
		var l = $( Login._btn_id );
		var p = $( Login._pwd_id );

		if ( l ) liwe.events.add ( l, 'click', Login.do_login );
		if ( p ) liwe.events.add ( p, 'keydown', Login._keydown );
		
		/*
		if ( $ ( Login._btn_id ) ) liwe.events.add_by_id ( Login._btn_id, 'click', Login.do_login );
		if ( $ ( Login._pwd_id ) ) liwe.events.add_by_id ( Login._pwd_id , 'keydown', Login._keydown );
		*/
	}
};

Login._keydown = function ( e )
{
	var keycode;
	
	if ( window.event ) keycode = window.event.keyCode;
	else if ( e ) keycode = e.which;
	else return false;
	
	if ( keycode != 13 ) return false;
	return Login.do_login ();
};

Login.do_login = function ()
{
	if ( $ ( Login._form_id ) ) $ ( Login._form_id ).submit ();
};

Login.login = function ()
{
	var login = ( $ ( Login._login_id ) ? $ ( Login._login_id ).value : '' );
	var pwd = ( $ ( Login._pwd_id ) ? $ ( Login._pwd_id ).value : '' );

	if ( ! login.length || ! pwd.length )
		alert ( "Inserire login e password" );
	else {
		var err_handler = liwe.AJAX.cbacks [ "req-error" ] || liwe.AJAX.error_handler;
		liwe.AJAX.cbacks [ "req-error" ] = function ( v ) { alert ( v.err_descr ); };

		kernel.ajax ( '/cgi-bin/AjaxCmd', { command: Login.login_command, login: login, passwd: pwd }, 
			function ( v )
			{
				liwe.AJAX.cbacks [ "req-error" ] = err_handler;
				Login.render_logged ( v );
			}
		);
	}
};

Login.render_logged = function ( data, dest )
{
	var s = '';
	var ctr_panel = '';

	if ( ! dest ) dest = Login._dest_logged;

	if ( Login._dest_logged && document.getElementById ( Login._dest_logged ) )
	{
		if ( data [ 'usr_kind' ] > 405 ) ctr_panel = '<div class="cp_link"><a href="/control_panel">Pannello di controllo<\/a><\/div>';

		data [ 'ctr_panel' ] = ctr_panel;

		s = String.formatDict ( Login.templates [ 'logged' ], data );


		document.getElementById ( Login._dest_logged ).innerHTML = s;
	}

	if ( Login.events [ 'login' ] ) Login.events [ 'login' ] ( data );
};

Login.logout = function ()
{
	//elimina cookie e ricarica la pagina
	kernel.ajax ( "/cgi-bin/AjaxCmd", { command: "logout" }, 
		function ( v )
		{
			if ( site && site.on_logout )
				site.on_logout ();
			else
				window.location.reload();
		}
	);
};

var logout = Login.logout;



var utils = {};

utils.MESI = [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" ];
utils.GIORNI = [ "Domenica", "Luned&igrave;", "Marted&igrave;", "Mercoled&igrave;", "Gioved&igrave;", "Venerd&igrave;", "Sabato" ];

utils.strip_html_body = function ( s )
{
	var p, p2;

	p = s.indexOf ( "<body" );
	if ( p < 0 ) p = s.indexOf ( "<BODY" );
	if ( p >= 0 )
	{
		p2 = s.indexOf ( ">", p + 5 );
		if ( p2 >= 0 )
			s = s.substr ( p2 + 1 );
	}

	p = s.indexOf ( "</body>" );
	if ( p < 0 ) p = s.indexOf ( "</BODY>" );
	if ( p >= 0 )
		s = s.substr ( 0, p );

	return s;
};


utils.get_browser = function ()
{	
	var s = navigator.userAgent;
	var res = '';

	if ( document.all && s.toLowerCase().indexOf ( 'msie' ) != -1 )
	{
		s = navigator.userAgent.substr ( s.toLowerCase().indexOf ( 'msie' ), 8 );
		res = 'IE';

		if ( s.indexOf ( '6.0' ) != -1 ) res += '6';
		else if ( s.indexOf ( '7.0' ) != -1 ) res += '7';
	}
	else if ( s.toLowerCase().indexOf ( 'mozilla' ) != -1 )
	{
		s = navigator.userAgent.substr ( navigator.userAgent.toLowerCase().indexOf ( 'firefox' ), 15);

		if ( s.toLowerCase().indexOf ( 'firefox' ) != -1 )
		{
			s = s.split ( "/" );

			res = 'FF';

			if ( s.length >= 1 )
				res += s [ 1 ]; 
		}
	}
	else
		res = navigator.appName + navigator.appVersion;

	return res;
};


utils.order_date = function ( date, sep, order, new_sep )
{
	var s = '';

	if ( date )
	{
		if ( order == "IT" && sep )
		{
			s = date.split ( sep );

			if ( s.length < 2 ) return s;

			if ( new_sep ) sep = new_sep;

			s = s [ 2 ] + sep + s [ 1 ] + sep + s [ 0 ];
		}
	}

	return s;
};


utils.get_file = function ( url, cback )
{
	kernel.ajax ( url, {}, function ( v )
	{
		if ( v.readyState != 4 ) return;
		if ( cback ) cback ( v.responseText, v.status );
	}, false );
};

utils.multi_wait = function ( lst, cback, vars, elem, n )
{
	var t, l = lst.length;
	if ( ! n ) n = 0;

	if ( n > 30 )
	{
		console.error ( "Non sono riuscito a caricare: " + elem );
		return;
	}

	for ( t = 0; t < l; t ++ )
	{
		if ( ! liwe.utils.is_def ( lst [ t ] ) )
		{
			console.debug ( "Attendo " + lst [ t ] );
			setTimeout ( function () { utils.multi_wait ( lst, cback, vars, lst [ t ], ++n );  }, 500 );
			return;
		}
	}

	if ( cback ) cback ( vars );
};

utils.fill_mask = function ( mask, div_name, cback, ds )
{
	kernel.show_mask ( mask, div_name, function ( v )
	{
		var requery = false;
		var data = kernel.history_data;

		if ( data )
		{
			var fields = v [ "fields" ];
			var ds_fields = ds ? ds.get_fields () : {};
			if ( ! ds_fields ) ds_fields = {};

			var t, l = fields.length;
			for ( t = 0; t < l; t ++ )
			{
				var f = fields [ t ] [ 0 ];
				var ftype = fields [ t ] [ 1 ];
				var val = data.get ( f, "" );  // dalla history

				if ( ftype == "radio" )
				{
					var el = $ ( f + "_" + val );
					if ( el ) el.checked = true;
				}
				else
				{
					var el = document.getElementById ( f );
					if ( ! el ) continue;

					if ( ftype == "checkbox" )
						el.checked = ( val.length > 0 );
					else if ( ftype == "select" && el.multiple )
					{
						var sval = val.split ( "|" );
						var opts = el.getElementsByTagName ( "option" );
						var oi, ol = opts.length;
						for ( oi = 0; oi < ol; oi ++ )
						{
							var opt = opts [ oi ];
							opt.selected = sval.indexOf ( opt.value ) >= 0;
						}
					}
					else
						el.value = val;
				}

				if ( val != ds_fields.get ( f, "" ) )
					requery = true;
			}
		}

		if ( cback ) cback ( v, requery );
	} );
};


utils.auto_focus = function ( field1, length, field2 )
{
	if ( field1.value.length < length ) return;
	if ( ! field2 )
	{
		field2 = field1.nextSibling;
		while ( field2 && ! field2 [ "focus" ] )
			field2 = field2.nextSibling;
	}
	else if ( typeof field2 == "string" )
		field2 = document.getElementById ( field2 );
	
	if ( field2 ) setTimeout ( function () { field2.focus(); }, 100 );
};


utils.get_sommarietto = function ( key, cback )
{
	var km = new KeyMan ();
	km.set ( key );
	var order_list = [ 18, 9, 15, 16, 19, 17 ];

	var dtm = DocTypeManager.get ( km.kind );
	if ( ! dtm [ "sommarietto" ] )
	{
		cback ( [] );
		return;
	}

	var fq = new FulQuery ();
	fq.opera = km.opera;
	fq.db_name = km.get_dbname ();
	fq.mode = "QUERY";
	fq.add ( "ID", "LIKE", km.main_key );
	fq.set_fields ( "ID", "FULTIPO" );
	fq.lines = 1000;

	var res = [];

	kernel.fulquery ( fq, function ( v )
	{
		var i, rows = v [ "rows" ];
		for ( i = 0; i < rows; i ++ )
		{
			var r = v [ "row" + i ];
			var fultipo = r [ "FULTIPO" ];
			var id = r [ "ID" ];

			var item = dtm.get_somm_item ( fultipo );
			if ( ! item ) continue;

			if ( item.ext == km.ext ) continue;
			if ( ! km.ext && item.ext == "OGG" ) continue;

			res.push ( [ id, item.descr, parseInt ( fultipo, 10 ) ] );
		}

		res.sort ( function ( a, b ) { 
			var at = a [ 2 ];
			var bt = b [ 2 ];

			var ai = order_list.indexOf ( at );
			var bi = order_list.indexOf ( bt );

			return ai - bi;
		} );

		cback ( res );
	} );
};


utils.getScrollXY = function ()
{
	var x = 0, y = 0;

	if ( typeof ( window.pageYOffset ) == 'number' )
	{
		// Netscape
		x = window.pageXOffset;
		y = window.pageYOffset;
	} else if ( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		// DOM
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	} else if ( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		// IE6 standards compliant mode
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}

	return [ x, y ];
};


utils.tree = {};

utils.tree.show_tree = function ( tree_id, expand_limit, show_checkbox, w, h, lst_file, cback )
{
	var tree = new OS3Tree.instance ( tree_id );

	//tree.check_explorer = true;
	tree.expand_limit = expand_limit;
	tree.show_checkbox = show_checkbox;
	tree.width = w;
	//tree.height = h;
	tree.expand_request = utils.tree.expand_request;
	tree.lst_file = lst_file;

	if ( tree [ "set_preselection" ] )
	{
		var fname = tree_id.substr ( 5 );
		if ( kernel.history_data && kernel.history_data [ fname ] )
			tree.set_preselection ( kernel.history_data [ fname ].split ( "|" ) );
	}

	kernel.command ( "tree_get", { FILE_NAME: tree.lst_file },
		function ( v ) 
		{
			var t, l = v [ "nodes" ].length;

			for ( t = 0; t < l; t ++ )
			{
				var node = v [ "nodes" ] [ t ];
				if ( node.folder )
					tree.add_folder ( null, node.text, node.val, node.val );
				else
					tree.add_node ( null, node.text, node.val, node.val );
			}
			
			tree.render ( tree_id + "_DIV" );

			cback && cback ();
		}
	);

	return tree;
};


utils.tree.expand_request = function ( node )
{
	kernel.command ( "tree_get", { FILE_NAME: node.tree.lst_file, NODE_ID: node.val, LEVEL: node.level },
		function ( vars ) { node.expand_done ( vars [ 'nodes' ] ); } );
};


utils.hide_windowed = function ( cnt )
{
	if ( ! cnt ) cnt = document;

	utils._windowed_status = [];

	var windowed = [ "select", "object", "iframe", "applet", "plugin", "embed" ];
	var k, len = windowed.length;
	for ( k = 0; k < len; k++ )
	{
		var els = cnt.getElementsByTagName ( windowed [ k ] );

		var t, l = els.length;
		for ( t = 0; t < l; t++ )
		{
			var el = els [ t ];
			var vis = el.style.visibility;
			utils._windowed_status.push ( [ el, vis ] );
			el.style.visibility = "hidden";
		}
	}
};


utils.restore_windowed = function ()
{
	var t, l = utils._windowed_status.length;
	for ( t = 0; t < l; t ++ )
	{
		var item = utils._windowed_status [ t ];
		var el = item [ 0 ];
		var vis = item [ 1 ];
		el.style.visibility = vis;
	}
};


utils.scrollTo = function ( el )
{
        if ( typeof el == "string" ) el = $ ( el );
        if ( ! el ) return;

        var ypos = liwe.dom.get_offset_top ( el );
        window.scrollTo ( 0, ypos );
};


utils.magic_button = function ( key )
{
	var OMEN_URL = "omen.leggiditalia.it";

	if ( kernel.user_info && kernel.user_info.attive.indexOf ( "PQ" ) >= 0 )
	{
		var km = new KeyMan ();
		km.set ( key );

		return String.format ( "http://%s/deaplugins/pm/pm_info.php?DOC_KEY=%s&ART=%s&SSCKEY=%s&LOGINDB=%s", 
			OMEN_URL, key, km.art_num, kernel.user_info.ssckey, kernel.user_info.db_name );
	}
	else
		return null;
};

utils.replace_anchors = function ( src )
{
	var as = src.getElementsByTagName ( "a" );
	var a, l, t;
	var name, href;
	var _anchors = {};

	l = as.length;

	for ( t = 0; t < l; t ++ )
	{
		a = as [ t ];

		name = a.getAttribute ( 'name' );
		if ( name )
		{
			a.setAttribute ( "id", name );
		}
		else
		{
			href = a.getAttribute ( 'href' );

			if ( ! href || ( href.indexOf ( "#" ) == -1 ) ) continue;

			var spl = href.split ( "#" );
			href = spl [ 1 ];

			a.setAttribute ( "name", href ); 

			_anchors [ href ] = a;

			a.setAttribute ( 'href', "javascript:utils.scrollTo('" + href + "')" );
		}
	}
};



function IndexManager()
{
	var self = this;

	self.db_name = "CLASS33";
	self.opera = "33";

	self._tree_labels = {};
	self._model = null;
	self._tree = null;

	self.render_tree = function ( div_name, ds )
	{
		if ( self._model && self._tree )
		{
			$ ( div_name ).className = '';
			self._create_tree ( ds, div_name );
			/*
			self._tree.render ( div_name );

			if ( self._model.root.length == 1 )
				self._tree.list [ 0 ].expand ( true );
			*/
		}
		else
		{
			var form = ds._form_fields.clone ();

			form [ "_X_SEARCH_FIELDS" ] = "CLASSIFICAZIONE:COUNT(*)";
			form [ "_X_GROUP_BY" ] = "CLASSIFICAZIONE";
			form [ "_X_ORDER_BY" ] = "CLASSIFICAZIONE";
			form [ "_X_START_POINT" ] = 0;
			form [ "_X_PAGE" ] = 0;
			form [ "_X_LINES" ] = "1000000";

			if ( form.get ( "_M_FULTIPO" ) )
			{
				delete form [ "FULTIPO" ];
				delete form [ "_M_FULTIPO" ];
			}

			kernel.ajax ( "/cgi-bin/FulQuery", form, function ( v ) {
				self._create_tree_model ( ds, div_name, v );
			} );
		}
	};


	self._create_tree_model = function ( ds, div_name, v )
	{
		var tm = {
			root: [],
			keys: {}
		};

		var keys = {};

		var t, l = parseInt ( v [ "rows" ] );
		var i, rl, count;
		var r, rv, node_list, node;
		var found = false;

		for ( t = 0; t < l; t++ )
		{
			r = v [ "row" + t ] [ "CLASSIFICAZIONE" ];
			if ( ! r ) continue;

			found = true;

			count = parseInt ( v [ "row" + t ] [ "COUNT(*)" ] );

			if ( r.charAt ( 0 ) == ':' ) r = r.substr ( 1 );
			if ( r.charAt ( r.length - 1 ) == ':' ) r = r.substr ( 0, r.length - 1 );
			
			rv = r.split ( '.' );
			rl = rv.length;

			var key = '';
			node_list = tm.root;
			for ( i = 0; i < rl; i++ )
			{
				if ( key ) key += ".";
				key += rv [ i ];

				if ( ( node_list == tm.root ) && ! self._tree_labels [ key ] )
					keys [ key ] = key;

				if ( tm.keys.get ( key, null ) )
				{
					tm.keys [ key ].count += count;
					node_list = tm.keys [ key ].children;
					continue;
				}

				node = {
					id: key,
					label: '',
					count: count,
					children: []
				};

				node_list.push ( node );
				tm.keys [ key ] = node;

				node_list = node.children;
			}
		}

		if ( ! found )
		{
			if ( $ ( div_name ) )
			{
				$ ( div_name ).className = '';
				$ ( div_name ).innerHTML = "Nessun indice";
			}
			return;
		}

		if ( tm.root.length == 1 )
			tm.root [ 0 ].no_filter = true;

		self._model = tm;

		var in_sql = "";

		keys.iterate ( function ( item ) {
			in_sql += "|" + item;
		} );

		if ( in_sql.length > 0 )
		{
			in_sql = in_sql.substr ( 1 );

			var fq = new FulQuery ();

			fq.db_name = self.db_name;
			fq.opera = self.opera;
			fq.set_fields ( 'valore', 'descr' );
			fq.add ( 'OPERA', 'EQUAL', self.opera );
			fq.add ( 'VALORE', 'IN_STR', in_sql );
			fq.lines = 1000000;

			if ( self.set_id ) fq.set_id ();

			var fields = {};
			fq.fill ( fields );

			kernel.ajax ( "/cgi-bin/FulQuery", fields, function ( v ) {
				var from = v [ "from_row" ];
				var to = v [ "to_row" ];
				var i;
				
				for ( i = from; i <= to; i++ )
				{
					var row = v [ "row" + i ];
					self._tree_labels [ row [ "valore" ] ] = row [ "descr" ];
				}

				self._create_tree ( ds, div_name );
			} );
		}
		else
			self._create_tree ( ds, div_name );
	};


	self._create_tree = function ( ds, div_name )
	{
		var t = new OS3Tree.instance ( "indici_tree_" + div_name );
		t._ds = ds;

		self._tree = t;

		function _tree_rendered ()
		{
			if ( self._model.root.length == 1 && self._model.root [ 0 ].children.length > 0 )
				t.list [ 0 ].expand ( true );
		}

		// if ( t.cbacks ) t.cbacks [ "onrendered" ] = _tree_rendered;

		t.expand_request = self._expand_request;
		t.width = "100%";
		
		t.set_event ( 'click', self._tree_click );

		self._add_tree_nodes ( t, null, self._model.root );

		$ ( div_name ).className = '';
		t.render ( div_name );

		// if ( ! t.cbacks ) _tree_rendered ();
		_tree_rendered ();
	};


	self._add_tree_nodes = function ( tree, parent, nodes )
	{
		var t, l = nodes.length;
		var node;

		for ( t = 0; t < l; t++ )
		{
			var n = nodes [ t ];

			var label = self._tree_labels.get ( n.id, n.id );

			if ( n.children.length )
				node = tree.add_folder ( parent, label + " (" + n.count + ")" );
			else
				node = tree.add_node ( parent, label + " (" + n.count + ")" );

			node.val = n;

			node.no_filter = n.get ( "no_filter" );
		}
	};


	self._tree_click = function ( tree, event_name, div, node )
	{
		var ds = tree._ds;

		if ( node.no_filter )
		{
			if ( ds._form_fields.get ( "_M_CLASSIFICAZIONE" ) )
			{
				delete ds._form_fields [ "_M_CLASSIFICAZIONE" ];
				delete ds._form_fields [ "CLASSIFICAZIONE" ];
			}
		}
		else
		{
			ds._form_fields [ 'CLASSIFICAZIONE' ] = ':' + node.val.id.replace ( /'/g, "''" );
			ds._form_fields [ '_M_CLASSIFICAZIONE' ] = 'PSEUDO';
		}

		if ( ds._form_fields.get ( '_M_FULTIPO' ) )
		{
			delete ds._form_fields [ '_M_FULTIPO' ];
			delete ds._form_fields [ 'FULTIPO' ];
		}

		ds.clear ();
		ds.fill ();
	};


	self._expand_request = function ( node )
	{
		// 0. recuperare lista di ID per la query
		var mnode = node.val;
		var t, l = mnode.children.length;
		var s = [], n;
		var ids;

		for ( t = 0; t < l; t ++ )
		{
			n = mnode.children [ t ];
			if ( ! self._tree_labels [ n.id ] )
				s.push ( n.id );
		}

		ids = '|'.join ( s );

		// 1. query AJAX per recuperare le label
		self._get_tree_labels ( ids, function () {

			// 2. creare le strutture da passare alla node.expand_done ()
			var t, n, label;
			var l = mnode.children.length;
			var res = [];
			for ( t = 0; t < l; t ++ )
			{
				n = mnode.children [ t ];
				label = self._tree_labels [ n.id ];

				res.push ( { folder: ( n.children.length ? true : false ), text: label + " (" + n.count + ")",
					val: n, id: n.id, onclick: null } );
			}
			
			node.expand_done ( res );
		} );
	};


	self._get_tree_labels = function ( ids, cback )
	{
		if ( ! ids )
		{
			cback ();
			return;
		}

		var fq = new FulQuery ();

		fq.db_name = self.db_name;
		fq.opera = self.opera;
		fq.set_fields ( 'valore', 'descr' );
		fq.add ( 'OPERA', 'EQUAL', self.opera );
		fq.add ( 'VALORE', 'IN_STR', ids );
		fq.lines = 1000000;

		if ( self.set_id ) fq.set_id ();

		var fields = {};
		fq.fill ( fields );

		kernel.ajax ( "/cgi-bin/FulQuery", fields, function ( v ) {
			var from = v [ "from_row" ];
			var to = v [ "to_row" ];
			var i;
			
			for ( i = from; i <= to; i++ )
			{
				var row = v [ "row" + i ];
				self._tree_labels [ row [ "valore" ] ] = row [ "descr" ];
			}

			cback ();
		} );
	};
}



var Note = {};

Note.docprint_cgi = {
	'save': "/cgi-bin/DocPrint",
	'open': "/cgi-bin/DocPrint",
	'print': "/cgi-bin/DocPrint"
};

Note.limit2saveprint = 30;
Note._notes = {};

// operazioni:
// 	- show_docs: mostra documenti annotati
// 	- edit: setta/rimuovi nota per il documento
// 	- get: preleva nota del documento
//
//eventi:
//	- click: click su un documento della lista
//	- change: nota modificata

Note.templates = {
	'nota_header': '<div class="title">Documenti annotati</div>',
	"annotazione":	'<div class="annotazione"><div><textarea name="nota" id="nota" rows="10" style="width: 100%"></textarea></div>' +
			'<div><button id="Note_del_btn" style="display: none; float: left;" onclick="Note._evt_nota_del()">Elimina</button>' +
			'<button style="float: right;" onclick="Note._evt_nota_ok()">OK</button></div>' +
			'</div>',

	/*
	"doc_row":	'<tr><td>%(lastmod)s</td><td>' +
			'	<a href="javascript:Note._onclick(\'%(opera)s\',\'%(id_doc)s\',\'%(tipo)s\')">%(estrcomp)s</a>' +
			'</td></tr>',
	*/

	"doc_row": 	'<tr><td><input type="checkbox" value="%(id_nota)s"/></td><td>%(lastmod)s</td><td>' +
			'	<a href="javascript:Note._onclick(\'%(opera)s\',\'%(id_doc)s\',\'%(tipo)s\')">%(estrcomp)s</a>' +
			'</td></tr>',

	/*
	"doc_result":	'<table id="ricerca_head">' +
			'  <tr>' +
			'    <th>Data</th>' +
			'    <th>Documento</th>' +
			'  </tr>' +
			'  %(rows)s' +
			'</table>',
	*/

	"doc_result":	'<div class="actions">' +
			'	<input style="margin-left: -3px;" type="checkbox" onclick="Note.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
			//'	<a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
			//'	&nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
			'</div>' +
			'<table id="ricerca_head">' +
			'  <tr class="th_header">' +
			'    <th>&nbsp;</th>' +
			'    <th>Data</th>' +
			'    <th>Documento</th>' +
			'  </tr>' +
			'  %(rows)s' +
			'</table>' +
			'<div class="note_buttons bottom">' +
			/*'	<table border="0" cellpadding="0" cellspacing="0" width="100%">' +
			'	<tr>' +
			'		<td>' +
			'			<button class="btn_archivio" type="button" onclick="Note.del_notes()">Elimina</button>' +
			'			&nbsp;&nbsp;<button class="btn_archivio" type="button" onclick="Note.save_print(\'open\')">Salva</button>' +
			'			&nbsp;&nbsp;<button class="btn_archivio" type="button" onclick="Note.save_print(\'print\')">Stampa</button>' + 
			'		</td>' +
			'	</tr>' +
			'	</table>' +*/
			'       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
			'               <div class="button">Elimina</div>' +
			'       </div>' +
			'     <div onclick="Note.save_print(\'open\',1)" class="btn_cnt">' +
			'               <div class="button">Salva</div>' +
			'       </div>' +
			'       <div onclick="Note.save_print(\'print\',1)" class="btn_cnt">' +
			'               <div class="button">Stampa</div>' +
			'       </div>' +
			'       <div class="clear_div"></div>' +
			'</div>',

	"doc_no_result":	'<div class="actions">' +
			'	<input style="margin-left: -3px;" type="checkbox" onclick="Note.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
			//'	<a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
			//'	&nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
			'</div>' +
			'%(empty)s' +
			'<div class="note_buttons bottom">' +
			'       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
			'               <div class="button">Elimina</div>' +
			'       </div>' +
			'     <div onclick="Note.save_print(\'open\',1)" class="btn_cnt">' +
			'               <div class="button">Salva</div>' +
			'       </div>' +
			'       <div onclick="Note.save_print(\'print\',1)" class="btn_cnt">' +
			'               <div class="button">Stampa</div>' +
			'       </div>' +
			'       <div class="clear_div"></div>' +
			'</div>',


	"null": null
};


Note.cbacks = {
	"del_notes": null,
	"show_docs_done": null,
	"change": null,
	"deleted": null,
	"manip": null,
	"click": function ( opera, id_doc, tipo ) {
		kernel.go ( 'doc', { id: id_doc, mask: 'show_doc', opera: opera, maschera: tipo } );
	}
};


Note.get = function ( opera, id_doc, cback )
{
	kernel.command ( "note", { action: "get", opera: opera, id_doc: id_doc }, function ( v )
	{
		if ( v && v [ "text" ] )
			Note._cur = v;
		else
			Note._cur = null;

		if ( Note.cbacks.change )
			Note.cbacks.change ( Note._cur );

		
		cback && cback ( v );
	} );
};

Note.edit = function ( opera, tipo, id_doc, descr )
{
	Note.get ( opera, id_doc, function ( v )
	{
		Note._edit_data = {
			opera: opera,
			tipo: tipo,
			id_doc: id_doc,
			descr: descr
		};

		liwe.lightbox.fade = false;
		liwe.lightbox.easy ( "lb_nota", "Annotazione", 500, 300 );

		$ ( "lb_nota" ).innerHTML = Note.templates [ "annotazione" ];


		if ( v )
		{
			var txt = v.get ( "text", "" );
			$ ( "nota" ).value = txt;

			if ( txt ) $ ( 'Note_del_btn' ).style.display = '';
		}
	} );
};

Note._evt_nota_ok = function ()
{
        var nota = $ ( "nota" ).value;
        if ( nota )
        {
		var dict = {
			action: "set",
			opera: Note._edit_data.opera,
			tipo: Note._edit_data.tipo,
			id_doc: Note._edit_data.id_doc,
			estrcomp: Note._edit_data.descr,
			text: $ ( "nota" ).value
		};

		kernel.command ( "note", dict, function ( v )
		{
			Note.get ( Note._edit_data.opera, Note._edit_data.id_doc, Note._nota_got );
		} );
        }
};

Note._nota_got = function ( v )
{
	if ( $ ( "lb_nota" ) )
		liwe.lightbox.close ();
};


Note._evt_nota_del = function ()
{
	if ( ! Note._cur ) return;

	if ( ! confirm ( "Eliminare realmente l'annotazione?" ) ) return;

	kernel.command ( "note", { action: "del", id_nota: Note._cur [ "id_nota" ] }, function ( v )
	{
		if ( Note.cbacks [ "deleted" ] )
			Note.cbacks [ "deleted" ] ( Note._cur );

		Note.get ( Note._edit_data.opera, Note._edit_data.id_doc, Note._nota_got );
	} );
};


Note.show_docs = function ( dest_div )
{
	Note._notes = {};

	kernel.command ( "note", { action: "list" }, function ( v )
	{
		var notes = v [ "notes" ];
		var t, l = notes.length;
		var row = {};
		var s = '';                                                                                                                                           
		for ( t = 0; t < l; t ++ )
		{
			row = notes [ t ];

			Note._notes [ row [ 'id_nota' ] ] = row;

			row [ "created" ] = row [ "created" ].replace ( / /, "&nbsp;" );
			row [ "lastmod" ] = row [ "lastmod" ].replace ( / /, "&nbsp;" );

			if ( Note.cbacks [ "manip" ] )
				Note.cbacks [ "manip" ] ( row );

			s += String.formatDict ( Note.templates [ 'doc_row' ], row );
		}

		if ( l <= 0 ) 
		{
			s += '<div class="no_res" style="min-height: 200px;"></div>';
			$ ( dest_div ).innerHTML = Note.templates [ 'nota_header' ] + 
				String.formatDict ( Note.templates [ 'doc_no_result' ], { empty: s } );
		}
		else
			$ ( dest_div ).innerHTML = Note.templates [ 'nota_header' ] + 
				String.formatDict ( Note.templates [ 'doc_result' ], { rows: s } );

		if ( Note.cbacks [ "show_docs_done" ] )
			Note.cbacks.show_docs_done ( notes );
	} );
};

Note._onclick = function ( opera, id_doc, tipo )
{
	if ( Note.cbacks.click ) Note.cbacks.click ( opera, id_doc, tipo );
};

/*====  NEW =====*/
Note.check_all = function ( checked, cnt_name )
{
	if (!$ ( cnt_name )) return;

	var chks = $ ( cnt_name ).getElementsByTagName ( "input" );
	var t, l = chks.length;

	for ( t = 0; t < l; t ++ )
	{
		chks [ t ].checked = checked;
	}
};

Note._get_checked = function ()
{
	var chks = $ ( "ricerca_head" ).getElementsByTagName ( "input" );
	var t, l = chks.length;
	var selected = [];

	for ( t = 0; t < l; t ++ )
	{
		if ( chks [ t ].value && chks [ t ].checked ) selected.push ( chks [ t ].value );
	}

	return selected;
};

Note.del_notes = function ()
{
	var selected = Note._get_checked ();

	if ( selected.length > 0 )
	{
		//Note.cbacks [ "del_notes" ] = modules.home.documenti_annotati;
		Note._del_notes ( selected )
	}
};

Note._del_notes = function ( ids )
{
	if ( ! confirm ( "Eliminare realmente le annotazioni?" ) ) return;
	var t, l = ids.length;
	var c = l;

	function _note_del ()
	{
		if ( --c ) return;

		if ( Note.cbacks [ "del_notes" ] ) Note.cbacks [ "del_notes" ] ( ids );
	}

	for ( t = 0; t < l; t ++ )
	{
		kernel.command ( "note", { action: "del", id_nota: ids [ t ] }, function ( v )
		{
			_note_del ();
		} );
	}
};

Note.save_print = function ( mode, from_desk )
{
	var selected = Note._get_checked ();
        var i, l = selected.length;
	var s = "";
	var dtm = null;
	var km = new KeyMan ();
	var templ = "";

	if ( l > Note.limit2saveprint )
	{
		if ( confirm ( "Si possono stampare/salvare un numero massimo di " + Note.limit2saveprint + " documenti. Se si scegliera' di proseguire verranno stampati solamente i primi " + Note.limit2saveprint + " documenti. Proseguire con l'operazione?" ) )
			l = Note.limit2saveprint;
		else return;
	}

        for ( i = 0; i < l; i ++ )
        {
		var id = selected [ i ];

		if ( ! Note._notes.get ( id ) ) continue;

		if ( i > 0 && s.length ) s += "@";

		km.set ( Note._notes [ id ][ 'id_doc' ] );

		s += km.real_opera;

		dtm = DocTypeManager.get ( km.kind );

		s += ":" + dtm.dbname;

		s += ":"; //TODO: FULTIPO

		templ = dtm.templates [ 'save' ];
		if ( ! templ ) templ = "default";

		s += ":" + templ;

		s += ":'" + Note._notes [ id ][ 'id_doc' ] + "'";
        }

        Note._mk_save_print_form ( mode, s, from_desk );
};

Note._mk_save_print_form = function ( mode, keys, from_desk )
{
        if ( ! keys ) return;

	var docprint = Note.docprint_cgi.get ( mode, "/cgi-bin/DocPrint" );

        var f = '<form id="note_save_print_form" method="POST" action="' + docprint + '" target="_blank">' +
                '<input type="hidden" name="MODE" value="' + mode + '" />' +
                '<input type="hidden" name="KEY0" value="' + keys + '" />';
		if ( from_desk ) f += '<input type="hidden" name="PRINT_NOTE" value="1" />';
                f += '</form>';

        if ( ! Note._cur_form_cnt )
        {
                Note._cur_form_cnt = document.createElement ( "DIV" );
                Note._cur_form_cnt.style.display = "none";
                document.body.appendChild ( Note._cur_form_cnt );
        }

        Note._cur_form_cnt.innerHTML = f;
        $ ( "note_save_print_form" ).submit ();
};



var Toolbar =  {};

Toolbar._instances = {};

Toolbar.instance = function ( name )
{
	this.buttons = [];
	this.name = name;
	
	this.add = function ( txt, cback )
	{
		this.buttons.push ( [ txt, cback ] );
	};

	this.render = function ( dest_div )
	{
		var t, l = this.buttons.length;
		var s = '';
		var btn;

		for ( t = 0; t < l; t ++ )
		{
			btn = this.buttons [ t ];
			s += '<button id="' + this.name + '_btn_' + t + '" class="toolbar_button" onclick="Toolbar.evt(\'' + this.name + '\',' + t + ')">' + btn [ 0 ] + '<\/button>';
		}

		document.getElementById ( dest_div ).innerHTML = s;
	};

	this.clear = function ()
	{
		this.buttons = [];
	};

	this.clone = function ( new_name )
	{
		var tb = new Toolbar.instance ( new_name );

		tb.buttons = this.buttons.concat ( [] );

		return tb;
	};

	Toolbar._instances [ name ] = this;
};

Toolbar.evt = function ( instance_name, pos )
{
	var tb = Toolbar._instances [ instance_name ];
	var cback;
	if ( ! tb ) return;

	cback  = tb.buttons [ pos ] [ 1 ];

	if ( ! cback )
		console.debug ( 'Manca cback per: %s :: %s', instance_name, tb.buttons [ pos ] [ 0 ] );
	else
		cback ();
};


var Bookmarks = {};

Bookmarks.docprint_cgi = {
	'save': "/cgi-bin/DocPrint",
	'open': "/cgi-bin/DocPrint",
	'print': "/cgi-bin/DocPrint"
};

Bookmarks.gfx_dir = "/js/wki/gfx/";

Bookmarks.limit2saveprint = 30;

Bookmarks.item_dblclick_event = null;		// Evento di gestione click su un nodo "documento"

Bookmarks.cbacks = {
	"deleted": null,
	"added": null,
	"save_print": null
};

Bookmarks._tree = null;
Bookmarks._data = {};
Bookmarks.checkall = false;
Bookmarks.print_note = false;

Bookmarks.init = function ( folders_only, data, cback )
{
	var is_mobile;
	// FABIO: modifica per device mobile
	if ( kernel.user_info [ 'device_family' ] == 'ipad' ) 
		is_mobile = true;
	
	// console.debug ( "DEVICE: " + kernel.user_info [ 'device_family' ] + " - is_mobile: " + is_mobile );
	// FABIO: se e' mobile, cambio inizializzazione
	if ( is_mobile ) Bookmarks.set_mobile ();


	Bookmarks._folders_only = folders_only;
	Bookmarks.print_note = data.get ( 'print_note' );

	Bookmarks._tree = new OS3Tree.instance ( 'bookmarks' );
	Bookmarks._tree.expand_request = Bookmarks._tree_expand;
	if ( ! folders_only )
	{
		Bookmarks._tree.show_checkbox = true;
		Bookmarks._tree.parent_autosel = false;
	}

	Bookmarks._tree.folder_collapsed = false;

	Bookmarks._tree.set_event ( "dblclick", Bookmarks._tree_dblclick );


	Bookmarks.get_subtree ( data, function ( v ) { Bookmarks._init_tree ( v, cback ); } );
};

Bookmarks.check_all = function ( chk )
{
	if ( chk ) Bookmarks.tree_seldesel_all ( 2 );
	else Bookmarks.tree_seldesel_all ( 0 );
};

Bookmarks.tree_seldesel_all = function ( mode )
{
	var tree = Bookmarks._tree;
	var nodes = tree [ 'list' ];
	var i, l = nodes.length;

	if ( mode == 0 ) tree.clear ( 0 );
	else
	{
		for ( i = 0; i < l; i ++ )
		{
			var n = nodes [ i ];

			Bookmarks._seldesel_node ( n, mode );
		}
	}
};

Bookmarks._seldesel_node = function ( node, mode )
{
	var nodes = node [ 'list' ];
	var i, l = nodes.length;

	node.change_status ( mode );
};

Bookmarks.insert = function ( data, cback )
{
	Bookmarks._do_req ( 'insert', data, function ( v ) {

		var parent_node = Bookmarks._tree.get_node_by_id ( data [ "id_parent" ] );		

		Bookmarks._tree.add_node ( parent_node, Bookmarks._decorate_text ( data [ "name" ], false ), v [ "id_node" ], data [ 'doc_key' ] );

		parent_node.refresh ();
		
		if ( cback ) cback ( v );
	} );
};

Bookmarks.create_folder = function ( data, cback ) { Bookmarks._do_req ( 'create_folder', data, cback ); };
Bookmarks.get_subtree 	= function ( data, cback ) { Bookmarks._do_req ( 'get_subtree', data, cback ); };
Bookmarks.multi_insert 	= function ( data, cback ) { Bookmarks._do_req ( 'multi_insert', data, cback ); };

Bookmarks.render 	= function ( obj_id, append )
{ 
	//APPEND: karma 20100309: problema degli id=bookmarks_tree ecc che ci sono gia' nel dom da scrivania

	if ( append ) append = ':' + append;
	else append = '';

	var s = '<div class="bookmarks_shell" id="bookmarks_shell' + append + '">';

	s += '<div class="bookmarks_top" id="bookmarks_top' + append + '"></div>';

	if ( Bookmarks.checkall && ! Bookmarks._folders_only )
	{
		s += '<div class="bookmarks_top checkall" id="bookmarks_check_all' + append + '">';
		s += '	<input type="checkbox" onclick="Bookmarks.check_all(this.checked)"/> Seleziona/Deseleziona tutti';
		s += '</div>';
	}

	s += '<div class="bookmarks_tree" id="bookmarks_tree' + append + '" onselectstart="return false;"></div>';
	s += '<div class="bookmarks_bottom" id="bookmarks_bottom' + append + '"></div>';
	s += '</div>';

	$( obj_id ).innerHTML = s;

	Bookmarks._tree.render ( "bookmarks_tree" + append ); 
	Bookmarks._create_buttons ( append );
};


Bookmarks._init_tree = function ( v, cback )
{
	var rows = v [ 'rows' ];
	var l = rows.length;
	var row, t;
	var text, is_folder;
	var data;
	
	for ( t = 0; t < l; t ++ )
	{
		row = rows [ t ];

		is_folder = parseInt ( row [ 'is_folder' ] );
		text = Bookmarks._decorate_text ( row [ "name" ], is_folder );

		if ( Bookmarks._folders_only && ! is_folder ) continue;

		if ( is_folder )
			Bookmarks._tree.add_folder ( null, text, row [ 'id' ] );
		else
		{
			data = {
				opera: row [ "opera" ],
				doc_key: row [ "doc_key" ],
				node_type: row [ "node_type" ],
				params: row [ "params" ]
			};

			Bookmarks._tree.add_node ( null, text, row [ 'id' ], data );
		}
	}

	if ( cback ) cback ();
};

Bookmarks._tree_expand = function ( node )
{
	var d = {
		'id_parent': node [ 'id' ]
	};

	Bookmarks.get_subtree ( d, function ( v ) { Bookmarks._fill_tree_node ( v, node ); } );
};

Bookmarks._fill_tree_node = function ( v, node )
{
	var elems = [];
	var rows = v [ 'rows' ];
	var l = rows.length;
	var t, row;
	var text;
	var is_folder;
	var data;

	for ( t = 0; t < l; t ++ )
	{
		row = rows [ t ];

		is_folder = parseInt ( row [ 'is_folder' ] );

		if ( Bookmarks._folders_only && ! is_folder ) continue;

		data = {
			opera: row [ "opera" ],
			doc_key: row [ "doc_key" ],
			node_type: row [ "node_type" ],
			params: row [ "params" ]
		};

		text = Bookmarks._decorate_text ( row [ "name" ], is_folder );
		elems.push ( { val: data, id: row [ 'id' ], text: text, folder: is_folder } );
	}

	node.expand_done ( elems );
};

Bookmarks._do_req = function ( mode, data, cback )
{
	data [ 'command' ] = 'bookmark';
	data [ 'mode' ] = mode;

	kernel.ajax ( '/cgi-bin/AjaxCmd', data, function ( v ) { if ( cback ) cback ( v ); } );
}

Bookmarks._create_buttons = function ( append )
{
	var s = Bookmarks.templates [ 'default_action_buttons' ];

	if ( ! Bookmarks._folders_only && Bookmarks.cbacks [ "save_print" ] )
		s += Bookmarks.templates [ 'extra_action_buttons' ];

	$( "bookmarks_top" + append ).innerHTML = s;
	$( "bookmarks_bottom" + append ).innerHTML = s;
};

Bookmarks.new_folder = function ()
{
	var current_node = Bookmarks._tree.current_get ();

	if ( current_node && ! current_node._is_folder ) return;

	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "bookmark_lb", "Nome cartella", 500, 66 );

	$ ( "bookmark_lb" ).innerHTML = Bookmarks._build_lb_html ( "_new_folder_done", "Crea" );

	$ ( "bookmark_name" ).focus ();
};


Bookmarks._new_folder_done = function ()
{
	var name = $ ( "bookmark_name" ).value.Strip();
	var current_node = Bookmarks._tree.current_get ();
	if ( name == "" ) return;

	var id_parent = null;
	if ( current_node ) id_parent = current_node.id;

	var data = {
		name: name,
		id_parent: id_parent
	};

	Bookmarks.create_folder ( data, function ( v ) {
		Bookmarks._tree.add_folder ( current_node, Bookmarks._decorate_text ( name, true ), v [ 'parent_node' ] );

		liwe.lightbox.close();
		
		if ( current_node ) current_node.refresh ();
		else Bookmarks._tree.render ();
	} );
};

Bookmarks.rename = function ()
{
	var current_node = Bookmarks._tree.current_get ();

	if ( ! current_node ) return;

	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "bookmark_lb", "Nuovo nome", 550, 66 );

	var text = current_node.text;
	$ ( "bookmark_lb" ).innerHTML = text;
	text = $ ( "bookmark_lb" ).textContent || $ ( "bookmark_lb" ).innerText;

	$ ( "bookmark_lb" ).innerHTML = Bookmarks._build_lb_html ( "_rename_done", "Rinomina" );
	$ ( "bookmark_name" ).value = text;

	$ ( "bookmark_name" ).focus ();
};

Bookmarks._rename_done = function ()
{
	var name = $ ( "bookmark_name" ).value.Strip();
	var current_node = Bookmarks._tree.current_get ();

        if ( name == "" ) return;

	var id = current_node.id;

	Bookmarks._do_req ( "rename", { name: name, id_node: id }, function ( v ) {
		current_node.text = Bookmarks._decorate_text ( name, current_node._is_folder );
		liwe.lightbox.close();

		var p = current_node.parent;

		Bookmarks._tree.current_clear ();

		if ( p ) p.refresh ();
		else Bookmarks._tree.render ();
	} );
};

Bookmarks._build_lb_html = function ( cback_name, button_label )
{
	return '<div class="bookmarks_lb"><input name="bookmark_name" id="bookmark_name" style="width: 422px" />' +
		'<button style="min-width: 65px; margin-left: 3px;" onclick="Bookmarks.' + cback_name + '()">' + button_label + '</button>' +
		'</div>';
};

Bookmarks.del_item = function ()
{
	var checked = Bookmarks._tree.get_selection ();
	if ( checked.count () )
	{
		Bookmarks.del_items ();
		return;
	}

	var current_node = Bookmarks._tree.current_get ();

	if ( ! current_node ) return;

	var msg;
	if ( current_node._is_folder )
		msg = "Cancellare l'elemento selezionato e TUTTI i suoi sotto-elementi?";
	else
		msg = "Cancellare l'elemento selezionato?";

	if ( ! confirm ( msg ) ) return;

	Bookmarks._do_req ( "delete", { id_node: current_node.id }, function ( v ) {
		if ( Bookmarks.cbacks [ "deleted" ] )
			Bookmarks.cbacks [ "deleted" ] ( current_node );

		Bookmarks._tree.del_node ( current_node );
	} );
};

Bookmarks.del_items = function ()
{
	var items = [];
	Bookmarks.get_tree_selection ( Bookmarks._tree.list, items );

	var msg = "Cancellare TUTTI gli elementi selezionati?";
	if ( ! confirm ( msg ) ) return;

	var ids = [];
	var i, l = items.length;
	for ( i = 0; i < l; i ++ )
		ids.push ( items [ i ].id );

	Bookmarks._do_req ( "delete", { id_node: "|".join ( ids ) }, function ( v )
	{
		if ( Bookmarks.cbacks [ "deleted" ] )
		{
			items.iterate ( function ( v, k )
			{
				var node = Bookmarks._tree.get_node_by_id ( k );
				Bookmarks.cbacks [ "deleted" ] ( node );
			} );
		}

		l = items.length;
		for ( i = 0; i < l; i ++ )
			Bookmarks._tree.del_node ( items [ i ] );
	} );
};

Bookmarks._decorate_text = function ( text, is_folder )
{
	var el = is_folder ? "folder" : "item";
	return '<div class="bookmark_' + el + '"><img src="' + Bookmarks.gfx_dir + el + '.gif" alt="" border="0"/>' + text + '</div>';
	return '<div class="bookmark_' + el + '">' + text + '</div>';
};

Bookmarks._tree_dblclick = function ( tree, event_name, div, node )
{
	if ( node._is_folder ) return;

	if ( Bookmarks.item_dblclick_event )
		Bookmarks.item_dblclick_event ( node.val );
};

Bookmarks.get_selected = function ()
{
	var node = Bookmarks._tree.current_get ();
	if ( ! node ) return null;
	return node.id;
};


Bookmarks.save = function ()
{
	Bookmarks._saveprint ( "open" );
};

Bookmarks.print = function ()
{
	Bookmarks._saveprint ( "print" );
};

Bookmarks.get_tree_selection = function ( lst, res )
{
	var l = lst.length;
	var t;

	for ( t = 0; t < l; t ++ ) 
	{
		var item = lst [ t ];
		if ( item._is_folder ) Bookmarks.get_tree_selection ( item.list, res );

		if ( item.status == 2 )
			res.push ( item );
	}
};

Bookmarks._saveprint = function ( mode )
{
	var items = Bookmarks._tree.get_selection ();
	var keys = {};
	var folders = [];


	function _do_saveprint ()
	{
		if ( ! keys.count () ) return;

		Bookmarks.cbacks [ "save_print" ] ( mode, keys.values () );
	}

	items.iterate ( function ( v, k )
	{
		if ( v == true ) folders.push ( k );
		else keys [ v.doc_key ] = v;
	} );

	if ( folders.length > 0 )
	{
		Bookmarks._do_req ( "get_all_docs", { folders: "|".join ( folders ) }, function ( v )
		{
			var docs = v [ "rows" ];
			var i, l = docs.length;
			for ( i = 0; i < l; i ++ )
			{
				var doc = docs [ i ];
				keys [ doc.doc_key ] = doc;
			}

			_do_saveprint ();
		} );
	}
	else
		_do_saveprint ();
};

Bookmarks._save_print = function ( mode, docs )
{
        var ks = [];
        var i, l = docs.length;
	var s = "";
	var dtm = null;
	var km = new KeyMan ();
	var templ = "";

	if ( l > Bookmarks.limit2saveprint )
	{
		if ( confirm ( "Si possono stampare/salvare un numero massimo di " + Bookmarks.limit2saveprint + " documenti. Se si scegliera' di proseguire verranno stampati solamente i primi " + Bookmarks.limit2saveprint + " documenti. Proseguire con l'operazione?" ) )
			l = Bookmarks.limit2saveprint;
		else return;
	}

        for ( i = 0; i < l; i ++ )
        {
                var d = docs [ i ];
		if ( ! d.doc_key ) continue;

		if ( i > 0 ) s += "@";

		km.set ( d.doc_key );

		s += km.real_opera;

		dtm = DocTypeManager.get ( km.kind );

		s += ":" + dtm.dbname;

		s += ":"; //TODO: FULTIPO

		templ = dtm.templates [ 'save' ];
		if ( ! templ ) templ = "default";

		s += ":" + templ;

		s += ":'" + d.doc_key + "'";
        }

        Bookmarks._mk_save_print_form ( mode, s );
};

Bookmarks._mk_save_print_form = function ( mode, keys )
{
        if ( ! keys ) return;
	
	var docprint = Bookmarks.docprint_cgi.get ( mode, "/cgi-bin/DocPrint" );

        var f = '<form id="save_print_form" method="POST" action="' + docprint + '" target="_blank">' +
                '<input type="hidden" name="MODE" value="' + mode + '" />' + 
                '<input type="hidden" name="KEY0" value="' + keys + '" />';

		if ( Bookmarks.print_note ) f += '<input type="hidden" name="PRINT_NOTE" value="1" />';

                f += '</form>';

        var cnt = $ ( "save_print_form_cnt" );
        if ( ! cnt )
        {
                cnt = document.createElement ( "DIV" );
                cnt.id = "save_print_form_cnt";
                cnt.style.display = "none";
                document.body.appendChild ( cnt );
        }

        cnt.innerHTML = f;
        $ ( "save_print_form" ).submit ();
};

// FABIO: aggiunto per evento "Mostra documento" per iPad
Bookmarks.show_doc = function ()
{
	var node = Bookmarks._tree.current_get ();
	if ( ! node ) return;

	if ( node._is_folder ) return;

	if ( Bookmarks.item_dblclick_event )
		Bookmarks.item_dblclick_event ( node.val );
};

// FABIO: nuova funzione per gestire i device mobile
Bookmarks.set_mobile = function ()
{
	Bookmarks.templates [ 'extra_action_buttons' ] = 
		'<div class="btn_cnt" style="padding-right: 5px; padding-left: 3px; min-width: 75px;" onclick="Bookmarks.show_doc()"><div class="button">Mostra documento</div></div>';
		
};

Bookmarks.templates = {};

Bookmarks.templates [ 'default_action_buttons' ] =
	'<div class="btn_cnt" onclick="Bookmarks.new_folder()"><div class="button">Nuova cartella</div></div>' +
	'<div class="btn_cnt" onclick="Bookmarks.rename()"><div class="button">Rinomina</div></div>' +
	'<div class="btn_cnt" onclick="Bookmarks.del_item()"><div class="button">Elimina</div></div>';

Bookmarks.templates [ 'extra_action_buttons' ] = 
	'<div class="btn_cnt" onclick="Bookmarks.save()"><div class="button">Salva</div></div>' +
	'<div class="btn_cnt" onclick="Bookmarks.print()"><div class="button">Stampa</div></div>';


var Ricerca = {};

// operazioni:
// 	- list: mostra le ricerca effettuate/salvato
// 	- add: aggiunge una nuova ricerca (in sessione)
// 	- save: salva (permanentemente) una nuova ricerca
// 	- get: preleva una ricerca
// 	- del: elimina una ricerca
//
//eventi:
//	- click: click su una ricerca della lista

Ricerca.templates = {
	'ric_header': '<div class="title">Ricerche %(tipo)s</div>',

	"ric_row":	'<tr>' +
                        '       <td width="1"><input type="checkbox" id="ric_%(id_ricerca)s" /></td>' +
                        '       <td width="200" valign="top"><b>%(created)s</b></td>' +
			'	<td valign="top"><a href="javascript:Ricerca._onclick(%(id_ricerca)s)">%(name)s</a></td>' +
                        '</tr>' +
			'<tr>' +
			'	<td colspan="3">' +
			'	<div class="cnt_descr_notes">' +
			'		<span class="descr1">%(_descr)s</span>' +
			'		<span id="%(id_ricerca)s_ricerca_descr2" class="descr2" style="display: none; margin-left: 0;">%(_descr2)s</span>' +
			'	</div>' +
			'	</td>' +
			'</tr>',
			//OLD TEMPLATE '<tr>' +
			//'	<td><input type="checkbox" id="ric_%(id_ricerca)s" /></td>' +
			//'	<td><a href="javascript:Ricerca._onclick(%(id_ricerca)s)">%(created)s</a></td><td>%(name)s%(_num_rows)s</td>' +
			//'</tr>',

	"ric_no_result":	'<div class="actions">' +
			'	<input style="margin-left: -3px;" type="checkbox" onclick="Ricerca.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
			//'	<a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
			//'	&nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
			'</div>%(empty)s',

	"ric_result":	'<div class="actions">' +
			'	<input style="margin-left: -3px;" type="checkbox" onclick="Ricerca.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
			//'	<a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
			//'	&nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
			'</div>' +
			'<table id="ricerca_head">' +
			'	<tr>' +
			'	<th>&nbsp;</th>' +
			'	<th>Data</th>' +
			'	<th>Maschera di ricerca</th>' +
			'</tr>' +
			'	%(rows)s' +
			'</table>',

	"ric_footer":	'<div class="ricerca_link"><a href="javascript:Ricerca.select_all(true)">Seleziona tutti</a> - ' +
			'<a href="javascript:Ricerca.select_all(false)">Deseleziona tutti</a></div>' +
			'<div class="ricerca_buttons"><button onclick="Ricerca._delete()">Elimina</button></div>',

	"null": null
};


Ricerca.cbacks = {
	"click": function ( page, params ) {
		kernel.go ( 'search', { mask: page }, params );
	},
	"list_row_manip": null,
	"render_done": null,
	"add_before": null
};


Ricerca.get = function ( id_ricerca, cback )
{
	kernel.command ( "ricerca", { action: "get", id_ricerca: id_ricerca }, function ( v )
	{
		cback && cback ( v );
	} );
};

Ricerca.get_last_by_app = function ( app, cback )
{
	kernel.command ( "ricerca", { action: "get", "APP": app }, function ( v )
	{
		cback && cback ( v );
	});
};

Ricerca.add = function ( name, page, params, query_id, cback )
{
	Ricerca._last_page = page;
	Ricerca._last_params = params;

	if ( kernel.user_info [ 'login' ] )
	{
		var dct = { 
			action: "add", 
			name: name, 
			page: page, 
			params: params, 
			query_id: query_id 
		};

		//KARMA: se si arriva da IPAD APP aggiungere il flag
		var dev = kernel.user_info.get ( 'device_family', '' );
		if ( dev == "ipad" )
			dct [ 'APP' ] = "ipad";

		if ( Ricerca.cbacks [ "add_before" ] ) 
			Ricerca.cbacks [ "add_before" ] ( dct ); //necessaria per ridefinire il nome o il contenuto di dct
		
		kernel.command ( "ricerca", dct, function ( v )
		{
			cback && cback ( v );
		} );
	}
	else cback && cback ( {} );
};

Ricerca.save = function ( name, page, params, cback )
{
	if ( kernel.user_info [ 'login' ] )
	{
		kernel.command ( "ricerca", { action: "save", name: name, page: page, params: params }, function ( v )
		{
			cback && cback ( v );
		} );
	}
	else cback && cback ( {} );
};

Ricerca.save_last = function ( name, cback )
{
	Ricerca.save ( name, Ricerca._last_page, Ricerca._last_params, cback );
};

Ricerca.del = function ( id_ricerca, cback )
{
	kernel.command ( "ricerca", { action: "del", id_ricerca: id_ricerca }, function ( v )
	{
		cback && cback ( v );
	} );
};


Ricerca._list_row_manip = function ( row )
{
	row [ '_descr2' ] = '';
	row [ '_descr' ] = row [ 'descr' ];

	/*
	var i = 0;
	for ( i = 0; i < 20; i ++ )
	{
		row [ '_descr' ] += ' BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA BLA';
	}
	*/

	var t, l = row [ '_descr' ].length;
	var cur_pos = 199;
	if ( l > 200 )
	{
		for ( t = 199; t < l; t++ )
		{
			if ( row [ '_descr' ][ t ] == " " )
			{
				cur_pos = t;
				break;
			}
		}

		var s = row [ '_descr' ].substr ( 0, cur_pos ) + '<a id="top_lnk_exp_' + row [ 'id_ricerca' ] + '" title="Espandi" href="javascript:Ricerca.toggle_ricerca(\'' + row [ 'id_ricerca' ] + '_ricerca_descr2\')">... &gt;&gt;</a>';
		row [ '_descr2' ] = row [ '_descr' ].substr ( cur_pos ) + '<a title="Chiudi" href="javascript:Ricerca.toggle_ricerca(\'' + row [ 'id_ricerca' ] + '_ricerca_descr2\')"> &lt;&lt;</a>';
		row [ '_descr' ] = s;
	}
};

Ricerca._render_done = function ()
{
	var dct = kernel.history_data || {};
	dct.iterate ( function ( v, k ) {
		Ricerca.toggle_ricerca ( k );
	});
};

Ricerca.toggle_ricerca = function ( el_id )
{
	var el = $ ( el_id );
	if ( ! el ) return;

	var dct = kernel.history_data || {};

	var disp = el.style.display;
	var a = $ ( 'top_lnk_exp_' + el_id.split ( '_' )[ 0 ]);

	if ( disp == 'none' )
	{
		el.style.display = '';
		//a.innerHTML = '&lt;&lt;';
		//a.setAttribute('title', 'Chiudi');
		a.style.display = 'none';
		dct [ el_id ] = el_id;
	}
	else 
	{
		el.style.display = 'none';
		//a.innerHTML = '... &gt;&gt;';
		//a.setAttribute('title', 'Espandi');
		a.style.display = '';

		if ( dct.get ( el_id ) ) delete dct [ el_id ];
	}

	kernel.replace_history_data ( kernel.module, kernel.history_dict.clone(), dct );
};

Ricerca.list = function ( dest_div, saved )
{
	Ricerca._cur_dest = dest_div;
	Ricerca._cur_saved = saved;

	kernel.command ( "ricerca", { action: "list", saved: saved }, function ( v )
	{
		var rics = v [ "ricerche" ];
		var t, l = rics.length;
		var row = {};
		var s = '';                                                                                                                                       
		for ( t = 0; t < l; t ++ )
		{
			row = rics [ t ];

			try
			{
				var params;
				eval ( "params = " + row [ "params" ] );

				var num_rows = params.get ( "_num_rows", null );

				if ( num_rows != null ) row [ "_num_rows" ] = " (" + num_rows + ")";
				else row [ "_num_rows" ] = "";

				if ( ! row [ 'descr' ] || row [ 'descr' ] == '(null)' )
					row [ 'descr' ] = '';

				if ( Ricerca.cbacks [ 'list_row_manip' ] )
					Ricerca.cbacks [ 'list_row_manip' ] ( row );
				else
					Ricerca._list_row_manip ( row );

				s += String.formatDict ( Ricerca.templates [ 'ric_row' ], row );
			}
			catch ( e )
			{
			}
		}

		if ( l <= 0 )
		{ 
			s += '<div class="no_res" style="min-height: 200px;"></div>';
			
			$ ( dest_div ).innerHTML = String.formatDict ( Ricerca.templates [ "ric_header" ], { tipo: ( saved ? "archiviate" : "effettuate" ) } ) + String.formatDict ( Ricerca.templates [ "ric_no_result" ], { empty: s } ) + Ricerca.templates [ "ric_footer" ];
		}
		else
		{
			$ ( dest_div ).innerHTML = String.formatDict ( Ricerca.templates [ "ric_header" ], { tipo: ( saved ? "archiviate" : "effettuate" ) } ) + String.formatDict ( Ricerca.templates [ "ric_result" ], { rows: s } ) + Ricerca.templates [ "ric_footer" ];

			if ( Ricerca.cbacks [ 'render_done' ] )
				Ricerca.cbacks [ 'render_done' ] ();
			else
				Ricerca._render_done();
		}
	} );
};

Ricerca._onclick = function ( id_ricerca )
{
	Ricerca.get ( id_ricerca, function ( v )
	{
		if ( Ricerca.cbacks.click )
			Ricerca.cbacks.click ( v [ "page" ], v [ "params" ] );
	} );
};


Ricerca.select_all = function ( select )
{
	var table = $ ( "ricerca_head" );
	var checks = table.getElementsByTagName ( "input" );
	var i, l = checks.length;

	for ( i = 0; i < l; i ++ )
	{
		var chk = checks [ i ];
		chk.checked = select;
	}
};


Ricerca._delete = function ()
{
	var table = $ ( "ricerca_head" );
	var checks = table.getElementsByTagName ( "input" );
	var i, l = checks.length;
	var ids = [];

	for ( i = 0; i < l; i ++ )
	{
		var chk = checks [ i ];
		if ( chk.checked ) ids.push ( chk.id.substr ( 4 ) );
	}

	if ( ids.length == 0 ) return;

	kernel.command ( "ricerca", { action: "del", id_ricerca: "|".join ( ids ) }, function ( v )
	{
		Ricerca.list ( Ricerca._cur_dest, Ricerca._cur_saved );
	} );
};

Ricerca.check_all = function ( checked, cnt_name )
{
	if ( ! $ ( cnt_name ) ) return;
	var chks = $ ( cnt_name ).getElementsByTagName ( "input" );
	var t, l = chks.length;

	for ( t = 0; t < l; t ++ )
	{
		chks [ t ].checked = checked;
	}
};


/*

uuid.js - Version 0.3
JavaScript Class to create a UUID like identifier

Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved.

This program is free software; you can redistribute it and/or modify it under 
the terms of the GNU General Public License as published by the Free Software 
Foundation; either version 2 of the License, or (at your option) any later 
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY 
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with 
this program; if not, write to the Free Software Foundation, Inc., 59 Temple 
Place, Suite 330, Boston, MA 02111-1307 USA

The latest version of this file can be downloaded from
http://www.af-design.com/resources/javascript_uuid.php

HISTORY:
6/5/06 	- Initial Release
5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of
          a simpler rand(max) function. Reduced overhead by using getTime() 
          method of date class (suggestion by James Hall).
9/5/08	- Fixed a bug with rand(max) and additional efficiencies pointed out 
	  by Robert Kieffer http://broofa.com/

KNOWN ISSUES:
- Still no way to get MAC address in JavaScript
- Research into other versions of UUID show promising possibilities 
  (more research needed)
- Documentation needs improvement

*/

// On creation of a UUID object, set it's initial value
function UUID(){
	this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function(){ return this.id; }
UUID.prototype.toString = function(){ return this.id; }

//
// INSTANCE SPECIFIC METHODS
//

UUID.prototype.createUUID = function(){
	//
	// Loose interpretation of the specification DCE 1.1: Remote Procedure Call
	// described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
	// since JavaScript doesn't allow access to internal systems, the last 48 bits 
	// of the node section is made up using a series of random numbers (6 octets long).
	//  
	var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
	var dc = new Date();
	var t = dc.getTime() - dg.getTime();
	var h = '-';
	var tl = UUID.getIntegerBits(t,0,31);
	var tm = UUID.getIntegerBits(t,32,47);
	var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
	var csar = UUID.getIntegerBits(UUID.rand(4095),0,7);
	var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);

	// since detection of anything about the machine/browser is far to buggy, 
	// include some more random numbers here
	// if NIC or an IP can be obtained reliably, that should be put in
	// here instead.
	var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,7) + 
			UUID.getIntegerBits(UUID.rand(8191),8,15) + 
			UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long
	return tl + h + tm + h + thv + h + csar + csl + h + n; 
}


//
// GENERAL METHODS (Not instance specific)
//


// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there 
// aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function(val,start,end){
	var base16 = UUID.returnBase(val,16);
	var quadArray = new Array();
	var quadString = '';
	var i = 0;
	for(i=0;i<base16.length;i++){
		quadArray.push(base16.substring(i,i+1));	
	}
	for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
		if(!quadArray[i] || quadArray[i] == '') quadString += '0';
		else quadString += quadArray[i];
	}
	return quadString;
}

// Replaced from the original function to leverage the built in methods in
// JavaScript. Thanks to Robert Kieffer for pointing this one out
UUID.returnBase = function(number, base){
	return (number).toString(base).toUpperCase();
}

// pick a random number within a range of numbers
// int b rand(int a); where 0 <= b <= a
UUID.rand = function(max){
	return Math.floor(Math.random() * (max + 1));
}

// end of UUID class file



function KeyMan ()
{
	this.key = null;

	this.opera 	= null;			// codice opera
	this.real_opera = null;			// codice opera originale (es.: 20 per le regionali)
	this.kind  	= null;			// tipo (LX, MA, ...)
	this.base_num  	= null;			// 01LX00001234ART5 -> 00001234
	this.ext       	= null;			// estensione -> ART
	this.main_key   = null;			// chiave senza estensione
	this.art_num	= null;			// numero articolo

	this._mode = null;
	this._regexp = null;
	
	this.set = function ( k )
	{
		var types = DocTypeManager.get_types ();
		//if ( ! this._regexp )
		//{
			var re = "^([0-9A-Z]{2,4})(" + '|'.join ( types ) + ")([0-9])([0-9]+)([A-Z0-9]*)\\+*.*$";
			if ( this._mode === 'mod') re = "^([0-9A-Z]{2,4})(" + '|'.join ( types ) + ")([0-9A-Z]{2,4})([0-9]+)([A-Z0-9]*)\\+*.*$";
			this._regexp = new RegExp ( re );

			// console.debug ( "REGEXP: %s", re );
		//}

		var r = k.match ( this._regexp );

		if ( ! r || ! r.length ) 
		{
			console.error ( "KeyMan: error parsing key '" + k + "' (missing dtm/doctypes ?)" );
			return;
		}

		this.key = k;

		this.opera = r [ 1 ];
		this.real_opera = KeyMan.resolve_opera ( r [ 1 ] );
		this.kind  = r [ 2 ];
		this.storico  = r [ 3 ];
		this.modulo  = r [ 3 ];
		this.base_num = r [ 4 ];
		this.ext      = r [ 5 ];

		this.main_key = this.opera + this.kind + this.storico + this.base_num;

		r = this.ext.match ( /ART([0-9]+)/ );
		if ( ! r )
			this.art_num = 0;
		else
			this.art_num = r [ 1 ];

		//console.debug ( this );
	};

	this.get_storico = function () { return this.opera + this.kind + '9' + this.base_num; };
	this.get_vigente = function () { return this.opera + this.kind + '0' + this.base_num; };
	this.get_opposite = function () 
	{ 
		if ( this.storico == '9' ) return  this.get_vigente ();
		return this.get_storico ();
	};

	this.get_dbname   = function ( skip_opera )
	{
		var doc_type = DocTypeManager.get ( this.kind );
		var op = KeyMan.resolve_opera ( this.opera );

		if ( ! doc_type )
		{
			console.error ( "Non c'e' doc_type per: " + this.kind );
			return "LEGGI" + op;
		}

		if ( skip_opera )
			return doc_type.dbname;

		return doc_type.dbname + op;
	};

	// FIXME: secondo me, questa funzione e' bacata
	// 	  deve utilizzare 
	this.is_kind 	  = function ( k )
	{
		var real_k = this.key.charAt ( 2 ) + this.key.charAt ( 3 );

		return ( real_k == k );
	};


	this.set_mode = function ( mode )
	{
		this._mode = mode;
	};
}



// STATIC
KeyMan.resolve_opera = function ( cod_opera )
{
	if ( " 11 22 23 16 17 24 25 18 26 03 21 12 13 27 28 04 19 02 29 30 31 32 ".match ( cod_opera ) ) return "20";

	return cod_opera;
};



var OS3TreeExtension = {};

OS3TreeExtension._new_instance = OS3Tree.instance;
OS3Tree.instance = function ( id )
{
	var self = new OS3TreeExtension._new_instance ( id );

	self._preselection = null;
	self._disabled = false;

	self.parent_autosel = true;


	self.__add_node = self.add_node;
	self.add_node = function ( parent_node, text, id, val, onclick )
	{
		var n = self.__add_node ( parent_node, text, id, val, onclick );

		if ( self._preselection )
		{
			var sel = self._preselection;

			var i, l = sel.length;
			for ( i = 0; i < l; i ++ )
			{
				var s = sel [ i ];
				if ( s == val )
				{
					sel.splice ( i, 1 );
					n.status = 2;
					break;
				}
				else if ( s.startsWith ( val ) )
				{
					n.status = 1;
					n.expand_request ( n );
					break;
				}
			}
		}

		return n;
	};


	self.__get_selection = self.get_selection;
	self.get_selection = function ( folders_only )
	{
		var arr = self.__get_selection ( folders_only );

		if ( self._preselection )
		{
			var i, c = self._preselection.length;
			for ( i = 0; i < c; i ++ )
				arr [ "_noid" + i ] = self._preselection [ i ];
		}

		return arr;
	};


	self.set_preselection = function ( sel )
	{
		self._preselection = sel;
	};


	self.disable = function ( disable )
	{
		self._disabled = disable;
	};

	return self;
};


OS3TreeExtension._dispatch_evt = OS3Tree.evt;
OS3Tree.evt = function ( div, event_name )
{
	var values = div.id.split ( ":" );
	var tree_name = values [ 0 ];	// Tree name
	var tree = OS3Tree.instances [ tree_name ];

	if ( tree._disabled ) return;

	return OS3TreeExtension._dispatch_evt ( div, event_name );
};


OS3TreeExtension._node_select = OS3Tree.node_select;
OS3Tree.node_select = function ( tree_id, node_id, status, img )
{
	var new_status = 0;
	var tree = OS3Tree.instances [ tree_id ];

	if ( tree._disabled ) return;

	return OS3TreeExtension._node_select ( tree_id, node_id, status, img );
};


OS3TreeExtension._node_expand = OS3Tree.expand;
OS3Tree.expand = function ( img, force_mode )
{
	var values = img.id.split ( ":" );
	var tree_name = values [ 1 ];	// Tree name
	var tree = OS3Tree.instances [ tree_name ];

	if ( tree._disabled ) return;

	var folder = img.parentNode; 
	var node = OS3Tree.get_node_by_id ( folder.id ); 
	if ( force_mode == "none" && node._is_folder && ( node._nodes == 0 ) ) return;


	return OS3TreeExtension._node_expand ( img, force_mode );
};


OS3TreeExtension._new_node_instance = OS3Tree.Node.instance;
OS3Tree.Node.instance = function ( parent_node, text, id, val, onclick, _tree )
{
	var self = new OS3TreeExtension._new_node_instance ( parent_node, text, id, val, onclick, _tree );
	

	self.expand_done = function ( elems )
        {
                var img = document.getElementById ( 'handle:' + self.full_id );
                var l, t, n, node, s, folder;

                if ( ! elems )
                {
                        // TODO: uscire senza togliendo il piu'
                        return;
                }

                l = elems.length;
                for ( t = 0; t < l; t ++ )
                {
                        n = elems [ t ];

                        node = self.tree.add_node ( self, ( n.text ? n.text : 'NO TEXT' ), n.id, n.val, n.onclick );
                        node._is_folder = n.folder ? true : false;
                        if ( node.status == 0 ) node.status = self.status == 2 ? 2 : 0;
                }

                self.refresh ();

                folder = document.getElementById ( 'folder:' + self.full_id ).lastChild;
                folder.style.display = 'block';
                img.className = 'minus';
        };


	self._add_node = function ( parent, child_status )
	{
		if ( ! parent ) return;

		var parent_autosel = self.tree.parent_autosel;

		var img = document.getElementById ( self._mk_img_id ( parent ) );

		if ( child_status == 2 ) parent._selected ++;
		if ( parent_autosel && parent._selected >= parent._nodes )
		{
			parent._selected = parent._nodes;

			if ( parent.status != 2 )
			{
				parent.status = 2;
				this._add_node ( parent.parent, parent.status );
			}
		} else {
			parent.status = 1;
			this._add_node ( parent.parent, parent.status );
		}

		if ( img ) img.className = parent.tree.status_img [ parent.status ];
	};


	self.change_status = function ( new_status )
	{
		if ( self.status == new_status ) return;		// Do nothing if status has not changed

		var l = self.list.length;
		var n;
		var img = document.getElementById ( self._mk_img_id ( self ) );

		if ( l > 0 )
		{
			for ( n = 0; n < l; n ++ )
				self.list [ n ].change_status ( new_status );
		}
		else
		{
			if ( new_status == 2 ) self._add_node ( self.parent, new_status );
			else if ( new_status == 0 ) self._del_node ( self.parent, new_status );
		}

		self.status = new_status;
		if ( img ) img.className = self.tree.status_img [ self.status ];
	};


	return self;
};



var BoxWarning = {};

BoxWarning.show = function ( txt, prnt, cback )
{
	var box = document.createElement ( "div" );
	var msg, close;
	
	box.id = "box_warning";
	
	close = document.createElement ( "div" );
	close.className = "close";
	close._prnt = prnt;
	close.onclick = function () { 
		if ( this._prnt ) this._prnt.removeChild ( $( "box_warning" ) );
		else document.body.removeChild ( $( "box_warning" ) ); 
	};
	close.innerHTML = '<div class="x_close">X</div>';

	msg = document.createElement ( "div" );
	msg.className = "msg";
	msg.innerHTML = txt;

	if ( cback ) cback ( box, msg, close );

	box.appendChild ( close );
	box.appendChild ( msg );

	if ( prnt ) prnt.appendChild ( box );
	else document.body.appendChild ( box );
};


Note.save_print = function ( mode, from_desk )
{
	var selected = Note._get_checked ();
        var i, l = selected.length;
	var s = "";
	var dtm = null;
	var km = new KeyMan ();
	var templ = "";

	if ( l > Note.limit2saveprint )
	{
		if ( confirm ( "Si possono stampare/salvare un numero massimo di " + Note.limit2saveprint + " documenti. Se si scegliera' di proseguire verranno stampati solamente i primi " + Note.limit2saveprint + " documenti. Proseguire con l'operazione?" ) )
			l = Note.limit2saveprint;
		else return;
	}

        for ( i = 0; i < l; i ++ )
        {
		var id = selected [ i ];

		if ( ! Note._notes.get ( id ) ) continue;

		if ( i > 0 && s.length ) s += "@";

		km.set ( Note._notes [ id ][ 'id_doc' ] );

		s += "I0QU";

		dtm = DocTypeManager.get ( km.kind );

		s += ":" + dtm.dbname;

		s += ":"; //TODO: FULTIPO

		templ = dtm.templates [ 'save' ];
		if ( ! templ ) templ = "default";

		s += ":" + templ;

		s += ":'" + Note._notes [ id ][ 'id_doc' ] + "'";
        }

        Note._mk_save_print_form ( mode, s, from_desk );
};


var DocTypeManager = {};

DocTypeManager.doc_types = {};

DocTypeManager.register = function ( doc_type )
{
	var t, l = doc_type.types.length;

	doc_type.get_somm_item = function ( fultipo ) { return DocTypeManager._get_somm_item ( doc_type, fultipo ); };

	for ( t = 0; t < l; t ++ )
		DocTypeManager.doc_types [ doc_type.types [ t ] ] = doc_type;
};

DocTypeManager.get_types = function () { return DocTypeManager.doc_types.keys (); };

DocTypeManager.get = function ( type )
{
	return DocTypeManager.doc_types [ type ];
};

DocTypeManager.set_attr = function ( type, attr_name, value )
{
	var dt = DocTypeManager.doc_types [ type ];
	if ( ! dt )
	{
		console.error ( "DocTypeManager::set_attr non trovo: %s", type ); 
		return;
	}

	dt [ attr_name ] = value;
};


DocTypeManager._get_somm_item = function ( doc_type, fultipo )
{
	if ( ! doc_type [ "sommarietto" ] ) return null;

	var i, l = doc_type.sommarietto.length;
	for ( i = 0; i < l; i++ )
	{
		var item = doc_type.sommarietto [ i ];
		if ( String ( item.fultipo ) == String ( fultipo ) ) return item;
	}

	return null;
};


DocTypeManager.get_by_dbname = function ( dbname )
{
	var res = null;

	DocTypeManager.doc_types.iterate ( function ( v, k )
	{
		if ( v.dbname == dbname ) res = v;
	} );

	return res;
};



DocTypeManager.register ( {
	name: 	"Quotidiano",
	types: 	[ "QT" ],
	dbname: "QUOTY",
	has_navi: true,
	has_somm: true,
	fields: {
			"search" : "ID:TITOLO:DESCR_TIPO:AUTORE:DATA:COD_OPERA:COGNOME_AUTORE:TIPO:ESTREMI:ABSTRACT",
			"show" : "ID:TIPO:TITOLO:OCCHIELLO:DATA:DESCR_TIPO:AUTORE:DOCUMENT_TEXT:COD_OPERA:DATA_FORM:ESTREMI:ABSTRACT",
			"save" : "ID:DATA_FORM:DOCUMENT_TEXT"
		},

	templates: {
			"save" : false 		// DocPrint usa "default"

		   }
} );



var site = {};

site.adv_ipad = false;

site._masks = [ "search", "adv_search", "show_doc" ];

site._months = [ "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" ];
site._day_name = [ "Domenica", "Luned&igrave", "Marted&igrave;", "Mercoled&igrave;", "Gioved&igrave;", "Venerd&igrave;", "Sabato" ];

site._home_divs = [ 'block_main_body_news', 'block_main_body_last_news', 'block_main_body_today_comm', 'block_main_body_rass_stampa', 'block_main_body_adnk', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ];

site._cache_mask = {};
site.form_data = {};

site.attive = null;
site.scadute = null;
site.non_poss = null;
site.keyman = null;

site.query_dict = {};


site.serv_centr = false;
site.use_login = false;


//{{{ STRUCT: _areas
site._areas = {
	"prpag": { 
			lbl: '<b>p</b>rima <b>p</b>agina', 
			lbl_tab: 'Prima Pagina', 
			show_divs: [ 'block_main_body_news', 'block_main_body_last_news', 'block_main_body_today_comm', 'block_main_body_rass_stampa' ],//PATCH: GAETANO 'block_main_body_adnk' ], 
			//cback: function () { modules.home._init_prpag () },
			items_rightbox: []
	},
	"I0Q1": { 
			lbl: 'area <b>Fisco</b>', 
			lbl_tab: 'Fisco', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'sel_item' }
				//{ lbl: 'Commercialista in vista', func: 'modules.home.list_commr_vista(\'%(area)s\')', itemclass: 'item' }
				//{ lbl: 'TG TAX', func: 'void(0)', itemclass: 'item' }
			]
		
	},
	"I0Q2": { 
			lbl:'area <b>Bilancio &amp; Societ&agrave;</b>', 
			lbl_tab: 'Bilancio &amp; Societ&agrave;', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'sel_item' }
			]
	},
	"I0Q3": { 
			lbl:'area <b>Lavoro &amp; Previdenza</b>', 
			lbl_tab: 'Lavoro &amp; Previdenza', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'sel_item' },
				{ lbl: 'Dati tabellari', func: 'modules.home.list_dat_tabel(\'%(area)s\')', itemclass: 'item' },
				{ lbl: 'Rinnovi CCNL', func: 'modules.home.list_rinn_ccnl(\'%(area)s\')', itemclass: 'item' }
			]
	},
	"I0Q4": { 
			lbl:'area <b>Diritto</b>', 
			lbl_tab: 'Diritto', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'sel_item' },
				{ lbl: 'Osservatorio di giurisprudenza', func: 'modules.home.list_oss_giurisp(\'%(area)s\')', itemclass: 'item' }
			]
	},
	"I0Q5": { 
			lbl:'area <b>Economia, Finanziamenti e Mercati</b>', 
			lbl_tab: 'Economia, Finanziamenti e Mercati', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'sel_item' }
			]
	}
	/*,
	"I0Q6": { 
			lbl:'area <b>Pubblica Amministrazione</b>', 
			lbl_tab: 'Pubblica Amministrazione', 
			show_divs: [ 'block_main_body_news', 'block_main_body_area_news_sx', 'block_main_body_area_news_dx' ],
			items_rightbox: [ 
				{ lbl: 'Commenti', func: 'modules.home.list_commenti(\'%(area)s\')', itemclass: 'item' },
				{ lbl: 'Osservatorio di giurisprudenza', func: 'modules.home.list_oss_giurisp(\'%(area)s\')', itemclass: 'item' }
			]
	}
	*/
};
//}}}

// INFO e CAMPI della form Login
site.login_form_data = {
	div_logged: 'main_top_login',
	form_id: 'login_form',
	login_id: 'login',
	pwd_id: 'password',
	btn_id: 'btn_login',
	btn_info: 'btn_info'
};

Login.login_command = "loginwkiticket";

//Override della login base
Login.login = function ()
{
	var login = ( $ ( Login._login_id ) ? $ ( Login._login_id ).value : '' );
	var pwd = ( $ ( Login._pwd_id ) ? $ ( Login._pwd_id ).value : '' );

	Login.events [ 'login' ] = null;

	if ( ! login.length || ! pwd.length )
		alert ( "Inserire login e password" );
	else {
		var err_handler = liwe.AJAX.cbacks [ "req-error" ] || liwe.AJAX.error_handler;
		liwe.AJAX.cbacks [ "req-error" ] = function ( v ) { 
				alert ( "Utente non riconosciuto" ); 
				$ ( "login_wait" ).style.display = 'none';
			};

		$ ( "login_wait" ).style.display = 'block';

		kernel.ajax ( '/cgi-bin/AjaxCmd', { command: Login.login_command, login: login, passwd: pwd }, 
			function ( v )
			{
				liwe.cookie.del ( "DEASSC" );
				liwe.cookie.set ( "DEASSC", v [ 'ssckey' ] );
				kernel.ajax ( '/cgi-bin/AjaxCmd', { command: "get_opere"}, 
					function ( v1 )
					{
						kernel.on_login ( v1 );
						liwe.AJAX.cbacks [ "req-error" ] = err_handler;
						Login.render_logged ( v );
					}
				);
				/*
				kernel.ajax ( '/cgi-bin/AjaxCmd', { command: "login", login: login, passwd: pwd }, 
					function ( v1 )
					{
						liwe.AJAX.cbacks [ "req-error" ] = err_handler;
						Login.render_logged ( v1 );
					}
				);
				*/
			}
		);
	}
};

// nome del modulo di default (chiamato se non viene specificato nella history)
site.default_module = 'home';

site._cur_area = 'prpag';
// funzione di inizializzazione del sito (dopo essersi loggati)
site.on_login = function ( v )
{
	$ ( "login_wait" ).style.display = 'none';

	if ( v [ 'login' ] )
	{
		$ ( 'center_cnt' ).style.display = 'block';
		$ ( 'copy' ).style.display = 'block';

		if ( location.host.indexOf ( 'lan' ) >= 0 ) $ ( 'scrivania_site' ).style.display = 'block';

		site._set_links ();
	}
	else 
	{
		$ ( 'scrivania_site' ).style.display = 'none';
		$ ( 'center_cnt' ).style.display = 'block';
		$ ( 'copy' ).style.display = 'block';

		if ( site.use_login ) site.on_logout ();
		else $ ( "login_table1" ).style.display = "";
	}

	site.set_rightbox ();

	//site.create_home ( { area: 'area_' + ( site._cur_area ? site._cur_area : 'prpag' ) } );
};

site.set_rightbox = function ()
{
	site.set_rbar_sect ( 'rbar_func_body', "rbar_functions", "rbar_functions_nologged" );
	site.set_rbar_sect ( 'rbar_servizi_body', "rbar_servizi", "rbar_servizi_nologged" );

	if ( ! kernel [ 'user_info' ].get ( 'login' ) ) $ ( "rbar_abbonati" ).style.display = "block";
	else $ ( "rbar_abbonati" ).style.display = "none";
};

site.set_rbar_sect = function ( cnt, templ, templ_nologged )
{
	if ( ! kernel [ 'user_info' ].get ( 'login' ) ) templ = templ_nologged;

	$ ( cnt, site.templates [ templ ] );
};

site.set_rbar_servizi = function ()
{
	var templ = site.templates [ "rbar_servizi" ];

	if ( ! kernel [ 'user_info' ].get ( 'login' ) ) templ = site.templates [ "rbar__nologged" ];

	$ ( "rbar_servizi_body" ).innerHTML = templ;
};

site._set_links = function ()
{
	var ckey = '';
	var ssckey = '';
	var templ = "http://asp.teleskill.it/fadcom/asp/qu_auth.asp?c=fadcom&SSCKEY=%(ssckey)s&OPERA=I0QU&AUTH=%(auth)s";
	//var templ = "http://www.ipsoa.it/shared/elearning.aspx?coupon=9PA23HA8b893|A7Q377J8C6A4|ADC377J8C6A5|APs377J8C6A6|b8A77i6C895C|bE377i6C895D|bQC77i6C895E";

	var lnk = $ ( 'lnk_telsk' );

	if ( ! lnk ) return;

	if ( kernel [ 'user_info' ].get ( 'login' ) )
	{
		//eliminare quando online 11/06/2009
		//=============
		//var login = kernel [ 'user_info' ].get ( 'login' );
		//var users = [ 'teleskill', 'wkiredaz1', 'wkiredaz2','wkiredaz3','wkiredaz4','wkiredaz5','wkiredaz6','wkiredaz7','wkiredaz8','wkiredaz9' ];
		//if ( users.indexOf ( login ) < 0 ) return;
		//=============

		var disp = 'block';

		if ( kernel [ 'user_info' ][ 'attive' ].indexOf ( 'I0QU' ) >= 0 )
		{
			//disp = 'none';
			ckey = kernel [ 'user_info' ][ 'ckey' ];
			ssckey = kernel [ 'user_info' ][ 'ssckey' ];

			var auth = MD5.hex_md5 ( ssckey + "I0QUerrepici" );

			lnk.setAttribute ( 'href', String.formatDict ( templ, { 'ssckey': ssckey, 'auth': auth } ) );
			lnk.setAttribute ( 'target', '_blank' );
		}
		else
		{
			lnk.setAttribute ( 'href', 'javascript:site.nologged(\'30min\')' );
		}

		if ( kernel [ 'user_info' ][ 'attive' ].indexOf ( 'I0SB' ) >= 0 )
			$ ( 'teleskill' ).style.display = 'none';
		else $ ( 'teleskill' ).style.display = 'block';
	}
	else lnk.setAttribute ( 'href', 'javascript:site.nologged(\'30min\')' );
};

site.error_handler = function ( v )
{
	var code = v [ "err_code" ];
	var descr = v [ "err_descr" ];
	var s = '';

	if ( $ ( 'block_main_body_doc' ) )
	{
		$ ( 'block_main_body_doc' ).innerHTML = v.get ( 'err_msg', v [ 'err_descr' ] );

		$ ( 'block_main_body_doc' ).innerHTML += '<br /><a href="http://quotidiano.ipsoa.it/">Quotidiano Ipsoa</a>';

		if (  $ ( 'block_main_top_pag' ) )
		{
			if ( site._cur_area ) s = site._areas.get ( site._cur_area ).lbl;

			$ ( 'block_main_top_pag' ).innerHTML = s;
		}
	}
	//setTimeout ( function () { Login.logout ();}, 5000 );
};

site.on_logout = function ()
{
	if ( site.use_login )
	{
		document.body.innerHTML = site.templates [ 'msg_nologin' ];
		kernel.quit ();
	}
	else
		location = "/";

	//location = "http://quotidiano.ipsoa.it";
};

site.opere = null;
// funzione di inizializzazione globale (chiamata dalla init di ogni modulo
//    prima di ogni cosa)
site.init = function ( module, dict, data )
{
	site.serv_centr = false;
	if ( location.host.indexOf ( 'lan' ) >= 0 ) site.serv_centr = true;

	if ( kernel.user_info [ "device_family" ] == 'ipad' && ! site.adv_ipad )
	{
		//BoxWarning.show ( "&Egrave; necessario utilizzare due dita per scorrere i risultati di ricerca, i documenti e gli indici.", $("center_cnt") );
		site.adv_ipad = true;
	}

	site._init_notes ();
	site._init_ricerche ();

	Ricerca.cbacks [ 'click' ] = site.ricerca_click;

	//if ( site.keyman == null ) site.keyman = new KeyMan ();

	if ( ! site.tbar ) 
		site.tbar = new Toolbar.instance ( 'tbar' );

	if ( ! site.tbar_rass_stampa ) site.tbar_rass_stampa = new Toolbar.instance ( 'tbar_rass_stampa' );

	site.smooth_roll = new SmoothRoll ( 'last_news_smooth_roll_render' );

	site._set_links ();
};

site.ricerca_click = function ( page, params )
{
	var arr = page.split ( ":" );
	if ( params ) params = eval ( '(' + params + ')' );

	kernel.go ( 'home', { mask: 'search', area: arr [ 0 ], search_form: arr [ 1 ] }, params ); 
};

site.nologged = function ( cod_opera )
{
	if ( site.use_login && ! kernel.user_info.get ( 'login' ) )
	{
		site.on_login ();
		return;
	}

	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "user_nologged", "Il Quotidiano Ipsoa", 600, 500 );

	var div = $ ( "user_nologged" );
	//div.innerHTML = site.templates [ 'msg_noopera' ];

	var page;
	var url_page;
	if ( cod_opera == "30min" )
	{
		url_page = "static/30min_nologged.html";
		if ( site._page_30min_nologged ) page = site._page_30min_nologged;
	}
	else
	{
		url_page = "static/msg_nologged.html";
		if ( site._page_nologged ) page = site._page_nologged;
	}

	if ( page ) div.innerHTML = page;
	else
	{
		utils.get_file ( url_page, function(html)
		{
			if ( ! html ) html = site.templates [ 'msg_noopera' ];

			html = utils.strip_html_body(html);

			if ( cod_opera == "30min" ) site._page_30min_nologged = html;
			else site._page_nologged = html;

			div.innerHTML = html;
		});
	}
	
	//var lbl = site._areas.get ( cod_opera ).lbl_tab;
	//alert (site.templates [ 'msg_noopera' ] );
};

site.user_check_opera = function ( cod_opera )
{
	if ( kernel.user_info.attive.indexOf ( "I0QU" ) < 0 ) return false;

	if ( kernel.user_info.attive.indexOf ( cod_opera ) < 0 ) return false;

	return true;
};

site.get_areaname = function ( codop )
{
	var name = site._areas.get ( codop );

	if ( name ) return name.lbl_tab;

	return '';
};

site.get_short_areaname = function ( codop )
{
	var s = site.get_areaname ( codop );

	if ( ! s ) return '';

	s = s.replace ( ",", "" );

	return s.split ( " " )[ 0 ];
};

//{{{ show_mask ( cur_mask, dict, data, cback )
site.show_mask = function ( cur_mask, dict, data, cback, ds )
{
	if ( ! dict ) dict = {};
	dict [ 'mask' ] = cur_mask; 

	/*
	if ( site._cache_mask [ cur_mask ] )
	{
		if ( cback ) cback ( { 'mask': site._cache_mask [ cur_mask ] }, dict, data );
		return;
	}
	*/

	$ ( 'main_top_mask' ).innerHTML = site.templates [ 'progress' ];

	utils.fill_mask ( cur_mask, 'main_top_mask', function ( v, requery ) { 
		site._cache_mask [ cur_mask ] = v [ 'mask' ]; 
		if ( cback ) cback ( v, dict, data, requery ); 
	}, ds ); 
};
//}}}
//{{{ create_home ( dict, data )
site.create_home = function ( dict, data )
{
	//if ( site.use_login && ! kernel.user_info.get ( 'login' ) ) return;

	if ( ! dict ) dict = {};

	var area = dict.get ( 'area', '' );

	area = site._cur_area = site.create_home_top ( area );	
	site._create_home ( area, dict, data );
};
//}}}
//{{{ create_home_details ( dict, data )
site.create_home_details = function ( dict, data )
{
	if ( ! dict ) dict = {};

	var area = dict.get ( 'area', '' );

	area = site._cur_area = site.create_home_top ( area );	

	site._create_rightbox ( area );
};
//}}}
//{{{ _create_home ( area, dict, data )
site._create_home = function ( area, dict, data )
{
	if ( ! area ) area = 'prpag';

	if ( site._masks.indexOf ( dict.get ( 'mask' ) ) != -1 )
		site._create_rightbox ( area );
	else
	{
		modules.home._fill_primo_piano ( function ( ids ) {
			site._create_home_cback ( area, ids );
		} );
	}
};

site._create_home_cback = function ( area, ids )
{
	if ( ! ids ) ids = [];

	if ( area == "prpag" )
	{
		modules.home._fill_rassegna_stampa ();

		modules.home._fill_last_news ( ids );

		modules.home._fill_2lists ( 'commenti', modules.home._format_today_comment, true, 2 );

		//PATCH GAETANO
		//modules.home._fill_adnk ();
	}
	else modules.home._fill_home_area_news ( area, ids );
	
	site._create_rightbox ( area );
	site._show_divs ( area );
};
//}}}
//{{{ _create_rightbox ( area )
site._create_rightbox = function ( area )
{
	var dct = {};

	dct [ 'items' ] = site._areas.get ( area, 'prpag' ).items_rightbox;

	if ( area == "prpag" )
	{
		$ ( 'right_area_sects_site' ).innerHTML = '';
		$ ( 'right_area_sects_site' ).style.display = 'none';
	}
	else site._build_rightbox ( area, dct );

	site.set_rightbox ();
};
//}}}
//{{{ _build_rightbox ( area, dct )
site._build_rightbox = function ( area, dct )
{
	var items = dct.get ( 'items', [] );
	var t, l = items.length;
	var item;
	var templ_row = site.templates [ 'right_bar_box_item' ];
	var s = '';

	for ( t = 0; t < l; t ++ )
	{
		item = items [ t ];

		item [ 'func' ] = String.formatDict ( item [ 'func' ], { 'area': area } );
		s += String.formatDict ( templ_row, item );
	}

	if ( l > 0 )
	{
		$ ( 'right_area_sects_site' ).innerHTML = String.formatDict ( site.templates [ 'right_bar_box' ], { _type: '_site' } );
		$ ( 'rightbar_box_body_site' ).innerHTML = s;
		$ ( 'right_area_sects_site' ).style.display = 'block';
	}

	var archivio = [ 
		{ lbl: 'Quotidiano', func: 'kernel.go(\'home\',{mask:\'quoty_arch_main\',area:\'area_%(area)s\'})', itemclass: 'item' },
		{ lbl: 'Rassegna Stampa', func: 'kernel.go(\'home\',{mask:\'rass_arch\',area:\'area_%(area)s\'})', itemclass: 'item' }
	];

	s = '';
	l = archivio.length;

	for ( t = 0; t < l; t ++ )
	{
		item = archivio [ t ];
		item [ 'func' ] = String.formatDict ( item [ 'func' ], { 'area': area } );

		s +=  String.formatDict ( templ_row, item );
	}

	if ( $ ( 'rightbar_lnk_archivio' ) ) $ ( 'rightbar_lnk_archivio' ).innerHTML = s;
};
//}}}
//{{{ create_home_top ( area )
site.create_home_top = function ( area )
{
	site._set_selected_area ( area );

	area = site._cur_area = site._cod_op_by_idarea ( area );
	site.create_main_top ( area );

	return area;
};
//}}}
//{{{ _cod_op_by_idarea ( area )
site._cod_op_by_idarea = function ( area )
{
	return area.split ( "_" )[ 1 ];
};
//}}}
//{{{ create_main_top ( op )
site.create_main_top = function ( op )
{
	site._print_top_sect ( op );
	site._print_top_data ();

	var d = new Date ();
	var cod_opera = 'I0QU';

	if ( site._cur_area && site._cur_area != 'prpag' ) cod_opera = site._cur_area;

	var dct = {
		txt: 'Stampa il quotidiano',//site._cur_area != 'prpag' ? 'Preleva il giornale' : 'Stampa la prima pagina',
		cod_opera: cod_opera,
		year: d.getFullYear (),
		month: d.getMonth () + 1,
		day: d.getDate ()
	};

	if ( kernel [ 'user_info' ].get ( 'login' ) ) $ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( site.templates [ 'lnk_print_prima_pag' ], dct );
	else $ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( site.templates [ 'lnk_print_prima_pag_nologged' ], dct );
	//$ ( 'block_main_top_downl' ).innerHTML = '';
};
//}}}
//{{{ _set_selected_area ( el_id )
site._set_selected_area = function ( el_id )
{
	if ( ! el_id ) el_id = "area_prpag";

	if ( ! $ ( el_id ) ) return;

	var elems = $ ( el_id ).parentNode.childNodes;
	

	var t, l = elems.length;
	var el;

	for ( t = 0; t < l; t ++ )
	{
		el = elems [ t ];

		if ( ! el.id ) continue;

		if ( el.id == el_id ) el.className = 'td_sel';
		else el.className = 'td_unsel';
	}
};
//}}}
//{{{ _print_top_sect ( op, lbl )
site._print_top_sect = function ( op, lbl )
{
	console.debug ( op );
	if ( ! op || op == 'I0QU' ) op = 'prpag';

	if ( ! lbl )
	{
		lbl = '';

		if ( op != 'prpag' ) lbl = 'News ';
	}

	var sez = site._areas.get ( op );

	$ ( 'block_main_top_pag' ).innerHTML = lbl + site._areas.get ( op ).lbl;
};
//}}}
//{{{ _print_top_data ()
site._print_top_data = function ()
{
	var d = new Date ();
	var dct = {};

	dct [ 'day' ] = d.getDate();
	dct [ 'month' ] = site._months [ d.getMonth () ];
	dct [ 'year' ] = d.getFullYear ();

	$ ( 'block_main_top_data' ).innerHTML = String.formatDict ( site.templates [ 'top_data' ], dct );
};
//}}}
//{{{ show_global_divs ( mode )
site.show_global_divs = function ( mode )
{
	switch ( mode )
	{
		case "list":
			$ ( 'block_main_body_doc' ).style.display = 'none';
			$ ( 'block_main_body_results' ).style.display = 'none';
			$ ( 'block_main_body' ).style.display = 'none';
			$ ( 'block_main_body_adnk' ).style.display = 'none';
			$ ( 'block_main_top_downl' ).style.display = 'none';
			$ ( 'static_cnt' ).style.display = 'none';

			$ ( 'block_main_body_list' ).style.display = 'block';
			$ ( 'right_bar_site' ).style.display = 'block';
			$ ( 'block_main_top_data' ).style.display = 'block';
			break;
		case "doc":
			$ ( 'block_main_body' ).style.display = 'none';
			$ ( 'block_main_body_adnk' ).style.display = 'none';
			$ ( 'block_main_body_results' ).style.display = 'none';
			$ ( 'block_main_body_list' ).style.display = 'none';
			$ ( 'block_main_top_downl' ).style.display = 'none';
			$ ( 'static_cnt' ).style.display = 'none';

			$ ( 'block_main_body_doc' ).style.display = 'block';
			$ ( 'right_bar_site' ).style.display = 'block';
			$ ( 'block_main_top_data' ).style.display = 'block';
			break;
		case "search":
			$ ( 'block_main_body' ).style.display = 'none';
			$ ( 'block_main_body_adnk' ).style.display = 'none';
			$ ( 'block_main_body_doc' ).style.display = 'none';
			$ ( 'block_main_body_list' ).style.display = 'none';
			$ ( 'block_main_top_downl' ).style.display = 'none';
			$ ( 'static_cnt' ).style.display = 'none';
			$ ( 'block_main_top_data' ).style.display = 'none';

			$ ( 'block_main_body_results' ).style.display = 'block';
			$ ( 'right_bar_site' ).style.display = 'block';
			break;

		case "static":
			$ ( 'block_main_body_doc' ).style.display = 'none';
			$ ( 'block_main_body_results' ).style.display = 'none';
			$ ( 'block_main_body' ).style.display = 'none';
			$ ( 'block_main_body_adnk' ).style.display = 'none';
			$ ( 'block_main_top_downl' ).style.display = 'none';
			$ ( 'block_main_body_list' ).style.display = 'none';

			$ ( 'static_cnt' ).style.display = 'block';
			$ ( 'right_bar_site' ).style.display = 'block';
			$ ( 'block_main_top_data' ).style.display = 'block';
			break;

		default:
			$ ( 'block_main_body_doc' ).style.display = 'none';
			$ ( 'block_main_body_list' ).style.display = 'none';
			$ ( 'block_main_body_results' ).style.display = 'none';
			$ ( 'static_cnt' ).style.display = 'none';

			$ ( 'block_main_top_downl' ).style.display = 'block';
			$ ( 'block_main_top_data' ).style.display = 'block';
			$ ( 'block_main_body' ).style.display = 'block';
			//PATCH GAETANO: display none
			$ ( 'block_main_body_adnk' ).style.display = 'none';
			break;
	}
};
//}}}
//{{{ _show_divs ( area )
site._show_divs = function ( area )
{
	var t, l = site._home_divs.length;
	var d;

	for ( t = 0; t < l; t ++ )
	{
		d = site._home_divs [ t ];

		if ( $ ( d ) ) $ ( d ).style.display = 'none';
	}

	var area_divs = site._areas.get ( area, 'prpag' ).show_divs;
	l = area_divs.length;

	for ( t = 0; t < l; t ++ )
	{
		d = area_divs [ t ];

		if ( $ ( d ) ) $ ( d ).style.display = 'block';
	}
};
//}}}

//{{{ site.set_area_tabs ( mode, clear )
site.set_area_tabs = function ( mode, clear )
{
	var tab_id = '';
	var lbl_tab = '';
	var func = '';

	site._areas.iterate ( function ( v, k ) {
		tab_id = 'area_' + k;
		lbl_tab = site._areas [ k ].lbl_tab;

		if ( mode == 'search' )
		{
			if ( k == 'prpag' ) return;

			$ ( 'block_main_top_pag' ).innerHTML = 'Ricerca ' + site._areas.get ( k ).lbl;
			if ( k == 'prpag' ) lbl_tab = 'Tutti i risultati';

			if ( ! clear )
				func = 'site.create_home_top(\'' + tab_id + '\');modules.home.show_tab_res(\'' + k + '\');site._create_rightbox ( \'' + k + '\' )';
			/*
			$ ( tab_id ).innerHTML = String.formatDict ( site.templates [ 'top_tab' ], {
				'func': 'site.create_home_top(\'' + tab_id + '\');modules.home.show_tab_res(\'' + k + '\');site._create_rightbox ( \'' + k + '\' )',
				'lbl_tab': lbl_tab,
				'area': k,
				'tot': ''
			} );
			*/
		}
		else if ( mode == 'pdf_arch' )
		{
			if ( k == 'prpag' ) return;

			$ ( 'block_main_top_pag' ).innerHTML = 'Archivio PDF - ' + site._areas.get ( k ).lbl;

			if ( ! clear )
				func = 'kernel.go(\'home\',{area:\'' + tab_id + '\',mask:\'quoty_arch\'})';
				//func = 'site.create_home_top(\'' + tab_id + '\');modules.home.show_tab_res(\'' + k + '\');site._create_rightbox ( \'' + k + '\' )';
		}
		else
		{
			if ( k == 'prpag' ) lbl_tab = 'Prima Pagina';

			if ( ! clear )
				func = 'kernel.go(\'home\',{area:\'' + tab_id + '\'})';
			/*
			$ ( tab_id ).innerHTML = String.formatDict ( site.templates [ 'top_tab' ], {
				'func': 'kernel.go(\'home\',{area:\'' + tab_id + '\'})',
				'lbl_tab': lbl_tab,
				'area': k,
				'tot': ''
			} );
			*/
		}
		
		site.set_tabs_data ( k, func, lbl_tab, '' );
	} );
};
//}}}
//{{{ set_tabs_data ( area, lbl_tab, tot )
site.set_tabs_data = function ( area, func, lbl_tab, tot )
{
	if ( ! tot ) tot = '';

        $ ( 'area_' + area ).innerHTML = String.formatDict ( site.templates [ 'top_tab' ], {
                'func': func,
                'area': area,
                'lbl_tab': lbl_tab,
                'tot': tot
        } );
};
//}}}

site.save_ric = function ( module, mask, area, search_form, fields )
{ 
	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "lb_save_ric", "Salva la ricerca", 500, 100 );

	var div = $ ( "lb_save_ric" );
	div._ric = { module: module, mask: mask, area: area, search_form: search_form, fields: fields };
	div.innerHTML = site.templates [ "save_ric" ];

	$ ( "ric_descr" ).focus ();
};                                              
                
site._save_ric_done = function ()
{
	var div = $ ( "lb_save_ric" );
	var descr = $ ( "ric_descr" ).value.Strip();
		
	if ( descr == "" ) return;
			
	var module = div._ric.module;
	var mask = div._ric.mask; 
	var fields = div._ric.fields;
	var search_form = div._ric.search_form;
	var area = div._ric.area;
			
	Ricerca.save ( descr, area + ':' + search_form, fields.toJSONString (), function ( v )
	{
		liwe.lightbox.close ();
	} );
};

site.get_corrs = function ( ids, tipo, cback )
{
	if ( ! ids || ids.length <= 0 ) return;

	ids = ids.join ( "|" );

	var fq = new FulQuery ();
	var dct = {};

	fq.set_fields ( 'DESCR_DOC', 'KEY_DOC', 'TIPO_DOC', 'DESCR_RIF', 'KEY_RIF', 'TIPO_RIF', 'TEXT_RIF', 'ORD_RIF' );

	fq.set_id ();
	fq.add ( 'KEY_DOC', 'IN_STR', ids );

	if ( tipo )
	{
		tipo = tipo.join ( "|" );
		fq.add ( 'TIPO_RIF', 'IN_NUM', tipo );
	}

	fq.lines = 99999;
	fq.db_name = 'CORRI0QU';
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	kernel.fulquery ( fq, cback );
};

site.tipo2name = function ( tipo )
{
	return {
		"92": 'news',
		"86": 'news',
		"87": 'comm',
		"34": 'rass'
		}.get ( tipo, '' );
};

site._init_notes = function ()
{
        Note.templates [ 'nota_header' ] =
                '<div class="note_buttons top">' +
                '       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
                '               <div class="button">Elimina</div>' +
                '       </div>' +
                '     <div onclick="Note.save_print(\'open\',1)" class="btn_cnt">' +
                '               <div class="button">Salva</div>' +
                '       </div>' +
                '       <div onclick="Note.save_print(\'print\',1)" class="btn_cnt">' +
                '               <div class="button">Stampa</div>' +
                '       </div>' +
                '       <div class="clear_div"></div>' +
                '</div>';

        Note.templates [ 'nota_footer' ] =
                '<div class="note_buttons bottom">' +
                '       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
                '               <div class="button">Elimina</div>' +
                '       </div>' +
                '     <div onclick="Note.save_print(\'open\',1)" class="btn_cnt">' +
                '               <div class="button">Salva</div>' +
                '       </div>' +
                '       <div onclick="Note.save_print(\'print\',1)" class="btn_cnt">' +
                '               <div class="button">Stampa</div>' +
                '       </div>' +
                '       <div class="clear_div"></div>' +
                '</div>';

	if ( kernel.user_info [ 'device_family' ] != 'browser' )
        {
                Note.templates [ 'nota_header' ] =
                        '<div class="note_buttons top">' +
                        '       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
                        '               <div class="button">Elimina</div>' +
                        '       </div>' +
                        '       <div class="clear_div"></div>' +
                        '</div>';

                Note.templates [ 'nota_footer' ] =
                        '<div class="note_buttons bottom">' +
                        '       <div style="border-left: 0;" onclick="Note.del_notes()" class="btn_cnt">' +
                        '               <div class="button">Elimina</div>' +
                        '       </div>' +
                        '       <div class="clear_div"></div>' +
                        '</div>';

		Note.templates [ "doc_no_result" ] =
			'<div class="actions">' +
			'       <input style="margin-left: -3px;" type="checkbox" onclick="Note.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
			//'     <a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
			//'     &nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
			'</div>' +
			'<div style="min-height: 200px;" class="no_res"></div>' +
			Note.templates [ 'nota_header' ];
        }

        Note.templates [ "doc_result" ] =
                '<div class="actions">' +
                '       <input style="margin-left: -3px;" type="checkbox" onclick="Note.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
                //'     <a href="javascript:Note.check_all(true,\'ricerca_head\')">Seleziona tutti</a>&nbsp;&nbsp;&nbsp;' +
                //'     &nbsp;&nbsp;&nbsp;<a href="javascript:Note.check_all(false,\'ricerca_head\')">Pulisci</a>' +
                '</div>' +
                '<table id="ricerca_head">' +
                '  <tr class="th_header">' +
                '    <th>&nbsp;</th>' +
                '    <th>Data</th>' +
                '    <th>Documento</th>' +
                '    <th>Annotazione</th>' +
                '  </tr>' +
                '  %(rows)s' +
                '</table>' +
                Note.templates [ 'nota_footer' ];
};

site._init_ricerche = function ()
{
        Ricerca.templates [ 'ric_header' ] =
                '<div class="ricerca_buttons top">' +
                '       <div style="border-left: 0;" onclick="Ricerca._delete()" class="btn_cnt">' +
                '               <div class="button">Elimina</div>' +
                '       </div>' +
                '       <div class="clear_div"></div>' +
                '</div>';

        Ricerca.templates [ 'ric_footer' ] =
                '<div class="ricerca_buttons bottom">' +
                '       <div style="border-left: 0;" onclick="Ricerca._delete()" class="btn_cnt">' +
                '               <div class="button">Elimina</div>' +
                '       </div>' +
                '       <div class="clear_div"></div>' +
                '</div>';

	Ricerca.templates [ "ric_result" ] =
                        '<div class="actions">' +
                        '       <input style="margin-left: -3px;" type="checkbox" onclick="Ricerca.check_all(this.checked,\'ricerca_head\')"/> Seleziona/Deseleziona tutti' +
                        '</div>' +
                        '<table id="ricerca_head">' +
                        '       <tr>' +
                        '       <th>&nbsp;</th>' +
                        '       <th>Data</th>' +
                        '       <th>Ricerca</th>' +
                        '</tr>' +
                        '       %(rows)s' +
                        '</table>';

        Ricerca.templates [ "ric_row" ] =
                        '<tr>' +
                        '       <td><input type="checkbox" id="ric_%(id_ricerca)s" /></td>' +
                        '       <td><a href="javascript:Ricerca._onclick(%(id_ricerca)s)">%(created)s</a></td><td>%(name)s</td>' +
                        '</tr>';
};


site.utils = {};

site.utils.go = function ( dest, new_w )
{
	if ( ! dest ) dest = '/';

	if ( new_w ) window.open ( dest );
	else window.location = dest;
};

site.utils.check_logged = function ()
{
	liwe.AJAX.request ( "/cgi-bin/AjaxCmd", { "command": "get_opere" }, 
			function ( v )
			{
				if ( v [ 'login' ] )
					Login.render_logged ( v, 'cnt_login' );
				else
					kernel.on_login ( v );
			},
			true );
};


site.utils.strip_html_body = function ( s )
{
	var p, p2;
	p = s.indexOf ( "<body" );
	if ( p >= 0 )
	{
		p2 = s.indexOf ( ">", p + 5 );
		if ( p2 >= 0 )
			s = s.substr ( p2 + 1 );
	}

	p = s.indexOf ( "</body>" );
	if ( p >= 0 )
		s = s.substr(0, p);

	return s;
};

site.utils.create_iframe = function ( url )
{
	$ ( "static_cnt" ).style.padding = "0";
	$ ( "static_cnt" ).innerHTML = '<iframe id="static_frame" frameBorder="no" width="98%" height="850px" style="padding: 5px;" src="' + url + '"><\/iframe>';
};

site.utils.parseInt = function ( s )
{
	s = '' + s;
	while ( s && ( s.charAt ( 0 ) == '0' ) ) s = s.substr ( 1 );
	return parseInt ( s );
};


site.utils.order_date = function ( date, sep, order, new_sep )
{
	var s = '';

	if ( date )
	{
		if ( order == "IT" && sep )
		{
			s = date.split ( sep );

			if ( s.length < 2 ) return s;

			if ( new_sep ) sep = new_sep;

			s = s [ 2 ] + sep + s [ 1 ] + sep + s [ 0 ];
		}
	}

	return s;
};


site.utils.show_static = function ( page )
{
	liwe.AJAX.request ( "/cgi-bin/AjaxCmd", { command: "dump_html", fname: page }, function ( v ) {
		$ ( "static_cnt" ).style.padding = "1em 2em";
		$ ( "static_cnt" ).innerHTML = LinkReplacer.lnk2span ( site.utils.strip_html_body ( v [ "content" ] ) );
		LinkReplacer.replace ();
	}, true );
};

site.utils.make_doc_link = function ( row, ds, skip_history, highlight )
{
	var today = new Date ();
	/*var data = row [ "data" ];
	data = data.split ( "-" );
	var d = new Date ( data [ 0 ], ( site.utils.parseInt ( data [ 1 ] ) - 1 ), data [ 2 ] );
	*/

	if ( skip_history ) skip_history = 1;
	else skip_history = 0;

	if ( ! highlight ) highlight = "";

	if (
		( ( site.user_info.attive.indexOf ( "AP" ) >= 0 ) && ( site.user_info [ "login" ] != "" ) )
		/*||
		(
			d.getFullYear() == today.getFullYear() &&
			d.getMonth() == today.getMonth() &&
			d.getDate() == today.getDate()
		)*/
	   )
	{
		// sono loggato
		if ( ds )
		{
			row [ "link" ] = String.formatDict ( "javascript:kernel.go({mask:\'doc\',ds_name:\'%(ds_name)s\'," + 
							     "pos:%(_pos)d,opera:\'PA\',id:\'%(id)s\',highlight:\'%(highlight)s\'})", 
					{
						ds_name: ds.name,
						_pos: row._pos,
						id: row.get ( 'id' ),
						highlight: highlight
					} );
		}
		else
		{
			row [ "link" ] = String.formatDict ( "javascript:kernel.go({'__nh': %(skip_history)s, mask:\'doc\',id:\'%(id)s\'})",
				{ id: row.get ( "ID" ), skip_history: skip_history } );
		}
	}
	else
	{
		// NON sono loggato
		row [ "link" ] = "javascript:kernel.go({mask:'frame',page:'http://el.leggiditalia.it/studiolegale/coupon/'})";
	}
};

site.utils.show_hide = function ( id_name )
{
	var h = $( id_name );

	if ( h.style.display == 'none' )
		h.style.display = 'block';
	else
		h.style.display = 'none';
};

site.utils.getElementsByClass = function ( searchClass, tag, node )
{
        var classElements = new Array();
        if ( node == null )
                node = document;
        if ( tag == null )
                tag = '*';
        var els;

        els = node.getElementsByTagName ( tag );
        return site.utils._find_class_elem ( els, RegExp( searchClass ) );
};

site.utils._find_class_elem = function ( elems, pattern )
{
        var classElements = new Array();
        var i, l = elems.length;
        for ( i = 0; i < l; i++ )
                if ( pattern.test ( elems[i].className ) ) classElements.push( elems [ i ] );

        return classElements;
};


site.templates = {};

var self = site.templates;

self [ 'top_tab' ] = 	'<div onclick="%(func)s">%(lbl_tab)s</div>' +
			'<div id="tot_%(area)s_td" onclick="%(func)s">%(tot)s</div>';

self [ 'progress' ] = '<div class="progress_div">&nbsp;</div>';

self [ 'progress_small' ] = '<div class="progress_div_small">&nbsp;</div>';

self [ 'logged' ] =  	'Benvenuto <b>%(user_name)s</b>. <br />Per ulteriori informazioni contatti la Sua Agenzia di zona.' +
				'<br />%(ctr_panel)s';

self [ 'results_navi' ] =  '<div class="result_right">%(prev_page)s %(dash)s %(next_page)s</div>';

self [ 'results_top' ] = '';//'Lista dei risultati: <span class="num_rows">%(num_rows)d</span>';

//self [ 'top_data' ] = '<b>%(day)s</b> %(month)s <b>%(year)s</b>';
self [ 'top_data' ] = '%(day)s %(month)s %(year)s';

self [ 'cnt_navi' ] =   '<div id="navi_tot"></div>' +
			'<div id="navi_page"></div>' +
			'<div id="results_navi_body"></div>';

self [ 'cnt_results_tree' ] = 	'<div class="title">Filtra il risultato</div>' +
				'<div id="tree_body_results"></div>';

self [ 'cnts_results' ] = 	'<div id="results_top"></div>' +
				'<div id="results_tree">' + site.templates [ 'cnt_results_tree' ] + '</div>' +
				'<div id="results_body"></div>' +
				'<div id="results_navi">' + site.templates [ 'cnt_navi' ] + '</div>';

self [ 'right_bar_box_item' ] = '<div class="%(itemclass)s" onclick="%(func)s">:: %(lbl)s</div>';

self [ 'right_bar_box' ] =      '<div class="title">:: Sezioni di Area</div>' +
				'<div id="rightbar_box_body%(_type)s" class="body"></div>';

self [ 'row_nologged' ] = '';

self [ "save_ric" ] =   '<div class="save_ric"><div>Immettere un nome per la ricerca:' +
			'<input type="text" name="ric_descr" id="ric_descr" style="width: 80%" /></div>' +
			'<div style="margin: 12px auto; text-align: center">' +
			'<button style="width: 50px; height: 21px" onclick="site._save_ric_done()">OK</button></div>' +
			'</div>';

self [ 'lnk_print_prima_pag' ] = '<a href="/cgi-bin/downloader.cgi?OPERA=I0QU&FILE=home_file/I0QU.pdf&MIME=application/pdf">%(txt)s</a>';
self [ 'lnk_print_prima_pag_nologged' ] = '<a href="javascript:site.nologged()">%(txt)s</a>';
//self [ 'lnk_print_prima_pag' ] = '<a href="/archivio/home_file/I0QU.pdf">%(txt)s</a>';

self [ 'msg_nologin' ] = 	'<div class="cnt_nologin" >' +
				'	<div id="main_top">' +
				'		<div id="main_top_header">' +
				'			<div id="main_top_logo" ></div>' +
				'			<div id="main_top_logo_dx" onclick="location=\'http://www.ipsoa.it\'" style="cursor: pointer;"></div>' +
				'		</div>' +
				'	</div>' +
				'	<div class="msg_nologin">' +
				'	Per accedere al prodotto &egrave; necessario essere abbonati a "Il Quotidiano Ipsoa" o effettuare l\'autenticazione' +
				'	 inserendo username e password ' +
				'	<a href="http://quotidiano.ipsoa.it">cliccando qui</a>.' +
				'	</div>' +
				'</div>';

self [ 'msg_noopera' ] =	'Per accedere a questo documento &egrave; necessario essere abbonati e autenticarsi inserendo Username e Password nella barra di registrazione.'

//self [ 'msg_noopera' ] =	'Per accedere a questo documento &egrave; necessario essere abbonati a Il Quotidiano Ipsoa.<br/>' +
				'Per maggiori informazioni' +
				' <a href="http://shop.wki.it/Ipsoa/Quotidiani/il_quotidiano_ipsoa_s20471.aspx" target="_blank">clicchi qui</a> ' +
				'oppure contatti il suo Agente di zona';

self [ "rbar_functions" ] = 
	'<div class="item" id="rightbar_lnk_archivio_header" onclick="modules.home.rightbox_toogle(this)">:: Archivio PDF</div><div class="subitem" style="display: none;">' +
	'	<div id="rightbar_lnk_archivio">' +
	'		<div class="item" onclick="kernel.go(\'home\',{mask:\'quoty_arch_main\',area:\'area_prpag\'})">:: Quotidiano</div>' +
	'		<div class="item" onclick="kernel.go(\'home\',{mask:\'rass_arch\',area:\'area_prpag\'})">:: Rassegna Stampa</div>' +
	'	</div>' +
	'</div>' +
	'<!--div class="item" onclick="modules.home.create_page(\'help\')">:: Help</div-->' +
	'<!--div class="item">:: MyDesk</div-->';
	//'<div class="item" onclick="modules.home.create_page(\'newsletter\')">:: Newsletter</div>';

self [ "rbar_functions_nologged" ] =
	'<div class="item" id="rightbar_lnk_archivio_header" onclick="modules.home.rightbox_toogle(this)">:: Archivio PDF</div><div class="subitem" style="display: none;">' +
	'	<div id="rightbar_lnk_archivio">' +
	'		<div class="item" onclick="site.nologged()">:: Quotidiano</div>' +
	'		<div class="item" onclick="site.nologged()">:: Rassegna Stampa</div>' +
	'	</div>' +
	'</div>';
	//'<div class="item" onclick="site.nologged()">:: Newsletter</div>';

self [ "rbar_servizi" ] =
	'<div class="item" onclick="modules.home.create_frame(\'http://www.ipsoa.it/gazzetta/arretrati.asp\',\'GU\')">:: Gazzetta Ufficiale</div>' +
	'<div class="item" onclick="modules.home.create_frame(\'http://www.ipsoa.it/IpsoDaily/Scadenzario/default_default.asp\',\'SCAD\')">:: Scadenze legali</div>' +
	'<div class="item" onclick="modules.home.create_frame(\'http://www.ipsoa.it/portalelavoro/scadenzariocontrattuale/2935_default.asp\',\'SCAD\')">:: Scadenze contrattuali</div>';
	//'<div class="item" onclick="modules.home.create_page(\'eventi\')">:: Box eventi</div>';

self [ "rbar_servizi_nologged" ] =
	'<div class="item" onclick="site.nologged()">:: Gazzetta Ufficiale</div>' +
	'<div class="item" onclick="site.nologged()">:: Scadenze legali</div>' +
	'<div class="item" onclick="site.nologged()">:: Scadenze contrattuali</div>';
	//'<div class="item" onclick="modules.home.create_page(\'eventi\')">:: Box eventi</div>';


modules.home = {};

modules.home._last_year = null;
modules.home._last_month = null;

modules.home._today = new Date ();
modules.home._query_id = null;

modules.home._ds = null;
modules.home._index_man = {};

modules.home._cur_search_mask = null;

modules.home._static_page = {};

modules.home._mask_fields_chks = [ "CHK_TIPO_92", "CHK_TIPO_87", "CHK_TIPO_88", "CHK_TIPO_34", "CHK_TIPO_36" ];
modules.home._mask_fields = [ "DOCUMENT_TEXT", "ANNO1", "MESE1", "GIORNO1", "ANNO2", "MESE2", "GIORNO2", "AUTORE" ].concat ( modules.home._mask_fields_chks );

modules.home._cur_tab_shown = '';

//{{{ init ( dict, data )
modules.home.init = function ( dict, data )
{
	modules.home._today = new Date ();

	modules.home._cur_search_mask =  dict.get ( 'search_form', "search" );
	modules.home._cur_area = dict.get ( 'area', 'area_prpag' );

	modules.home._cur_opera = site._cod_op_by_idarea ( modules.home._cur_area );

	modules.home._highlight = '';

	var ds = null;
	if ( modules.home._ds )
		ds = modules.home._ds.values () [ 0 ];

	var mask = modules.home._cur_mask = dict.get ( "mask", "" );
	switch ( mask )
	{
		/*
		case "arch_quot_month":
		case "rass_quot_month":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'static' );
			//modules.home.list_arch_by_month ( dict, data );
			break;
		*/

		case "quoty_arch_main":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'static' );
			modules.home.quoty_arch_page ();
			break;

		case "quoty_arch":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'static' );
			modules.home.quoty_arch_list ();
			break;

		case "rass_arch":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'static' );
			modules.home.quoty_rass_arch_list ();
			break;

		case "adnk":
			site.set_area_tabs ();
			console.debug ( "ADNK" );
			break;

		case "search":
		case "adv_search":
			//site.create_home_top ( dict.get ( 'area', '' ) );
			site.set_area_tabs ( 'search' );
			//site.create_home ( dict, data );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'search' );
			break;

		case "commenti":
		case "list_oss_giurisp":
		case "list_rinn_ccnl":
		case "list_rass_stampa":
		case "list_dat_tabel":
		case "list_commr_vista":
		case "last7comm":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			site.create_home_top ( modules.home._cur_area );
			modules.home._init_list ( dict, data );
			break;

		case "show_page":
			site.set_area_tabs ();
			site._create_rightbox ( modules.home._cur_opera );
			//site.create_home ( dict, data );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			site.show_global_divs ( 'static' );
			modules.home._create_page ( dict );
			break;

		default:
			site.set_area_tabs ();
			site.show_global_divs ();
			site.create_home ( dict, data );
			site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done, ds );
			break;
	}
};
//}}}
//{{{ show_mask_done ( v, dict, data )
modules.home.show_mask_done = function ( v, dict, data, requery )
{
	var dct = {};
	var area = dict.get ( "area", "area_prpag" );
	
	modules.home._requery = requery;

	if ( modules.home._cur_search_mask == 'search' )
	{
		site.form_data.cerca = function () {
			modules.home.search_click ( {
				area: area,
				mask: dict.get ( "mask", "" ),
				search_form: 'search'
			} );
		};

		site.form_data.adv_cerca = function () {
			modules.home.create_search_form ( {
				area: area,
				mask: dict.get ( "mask", "" ),
				search_form: 'adv_search'
			} );
		};

		site.form_data.new_cerca = function () {
			modules.home.ds_back2home ( area, 'search' );
			/*modules.home.new_search ( {
				mask: dict.get ( "mask", "" ),
				search_form: 'search'
			} );*/
		};


		$ ( 'adv_cerca' ).innerHTML = 'Aggiungi criteri di ricerca';
	}
	else 
	{
		site.form_data.cerca = function () {
			modules.home.search_click ( {
				area: area,
				mask: dict.get ( "mask", "" ),
				search_form: 'adv_search'
			} );
		};

		site.form_data.adv_cerca = function () {
			modules.home.create_search_form ( {
				area: area,
				mask: dict.get ( "mask", "" ),
				search_form: 'search'
			} );
		};

		site.form_data.new_cerca = function () {
			modules.home.ds_back2home ( area, 'adv_search' );
			/*modules.home.new_search ( {
				mask: dict.get ( "mask", "" ),
				search_form: 'adv_search'
			} );*/
		};


		$ ( 'adv_cerca' ).innerHTML = 'Ricerca Semplice';
	}

	if ( data )
		modules.home._fill_mask ( data );

	modules.home._set_form_events ();
};
//}}}
//{{{ new_search ( dct )
modules.home.new_search = function ( dct )
{
	liwe.AJAX.abort ( function ()
	{ 
		modules.home._ds.iterate ( function ( v, k ) {
			var ds = modules.home._ds [ k ];
			var tot_td = $ ( 'tot_' + ds.name + '_td' );
			tot_td.innerHTML = '';
		} );

		$ ( 'block_main_body_results' ).innerHTML = String.formatDict ( modules.home.templates [ 'cnts_results' ], { name: 'tmp' } );
		modules.home.create_search_form ( dct );
	} );
};
//}}}
//{{{ search_click ( dct, skip_history )
modules.home.search_click = function ( dct, skip_history )
{
	site.show_global_divs ( 'search' );
	
	modules.home._highlight = '';

	var fields = Array.toObject ( Array.fromForm ( 'main_top_mask' ) );

	modules.home._requery = true;

	if ( ! modules.home._cur_area ) modules.home._cur_area = dct.get ( 'area', 'area_prpag' );

	/*
	$ ( "results_body" ).innerHTML = modules.home.templates [ 'progress' ];
	$ ( 'results_tree' ).innerHTML = modules.home.templates [ 'cnt_results_tree' ];
	$ ( 'tree_body_results' ).innerHTML = modules.home.templates [ 'progress' ];
	*/


	modules.home._query_id = String ( new UUID () );

	if ( skip_history )
		modules.home._start_search ( fields );
	else
	{
		if ( modules.home._cur_search_mask == 'search' )
		{
			fields [ 'CHK_TIPO_92' ] = '92|86';
			fields [ 'CHK_TIPO_34' ] = '34';
			fields [ 'CHK_TIPO_36' ] = '36';
			fields [ 'CHK_TIPO_87' ] = '87';
			fields [ 'CHK_TIPO_88' ] = '88';
		}

		kernel.add_history_data ( 'home', { mask: dct.get ( 'mask' ), area: modules.home._cur_area, search_form: dct.get ( 'search_form', 'search' ) }, fields, function () {
			Ricerca.add ( "Ricerca", modules.home._cur_area +':'+ dct.get ( 'search_form' ) , fields.toJSONString (), modules.home._query_id );

			modules.home._start_search ( fields );
		} );
	}


	/*
	Ricerca.add ( "Ricerca", modules.home._cur_area +':'+ dct.get ( 'search_form' ) , fields.toJSONString (), function ( v ) {

		if ( skip_history )
			modules.home._start_search ( fields );
		else
		{
			if ( modules.home._cur_search_mask == 'search' )
			{
				fields [ 'CHK_TIPO_92' ] = '92|86';
				fields [ 'CHK_TIPO_34' ] = '34';
				fields [ 'CHK_TIPO_36' ] = '36';
				fields [ 'CHK_TIPO_87' ] = '87';
				fields [ 'CHK_TIPO_88' ] = '88';
			}

			kernel.add_history_data ( 'home', { mask: dct.get ( 'mask' ), area: modules.home._cur_area, search_form: dct.get ( 'search_form', 'search' ) }, fields, function () {
				modules.home._start_search ( fields );
			} );
		}
	} );
	*/

};
//}}}
//{{{ create_search_form ( dct )
modules.home.create_search_form = function ( dct )
{
	modules.home._cur_search_mask = dct.search_form;
	modules.home._cur_mask = dct.mask;
	dct [ "area" ] = modules.home._cur_area;
	site.show_mask ( modules.home._cur_search_mask, dct, null, modules.home.show_mask_done );
};
//}}}
//{{{ list_commenti ( area )
modules.home.list_commenti = function ( area )
{
	kernel.go ( 'home', { mask: 'commenti', 'area': modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{
modules.home.list_rass_stampa = function ()
{
	kernel.go ( 'home', { mask: 'list_rass_stampa', area: modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{ list_commr_vista ( area )
modules.home.list_commr_vista = function ( area )
{
	kernel.go ( 'home', { mask: 'list_commr_vista', 'area': modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{ list_oss_giurisp ( area )
modules.home.list_oss_giurisp = function ( area )
{
	kernel.go ( 'home', { mask: 'list_oss_giurisp', 'area': modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{ list_dat_tabel ( area )
modules.home.list_dat_tabel = function ( area )
{
	kernel.go ( 'home', { mask: 'list_dat_tabel', 'area': modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{ list_rinn_ccnl ( area )
modules.home.list_rinn_ccnl = function ( area )
{
	kernel.go ( 'home', { mask: 'list_rinn_ccnl', 'area': modules.home._cur_area, 'search_form': modules.home._cur_search_mask } );
};
//}}}
//{{{ explode_data ( elem )
modules.home.explode_data = function ( elem )
{
	var el = $ ( elem );

	el.href = 'javascript:modules.home.close_data ( "'  + elem + '");';
	el.parentNode.nextSibling.style.display = "block";
};
//}}}
//{{{ close_data ( elem )
modules.home.close_data = function ( elem )
{
	var el = $ ( elem );

	el.href = 'javascript:modules.home.explode_data ( "' + elem + '" )';
	el.parentNode.nextSibling.style.display = "none";
};
//}}}
//{{{ rightbox_toogle ( elem )
modules.home.rightbox_toogle = function ( elem )
{
	var d = elem.nextSibling;
	d.style.display = d.style.display == 'none' ? 'block' : 'none';
};
//}}}
//{{{ create_page ( page_name )
modules.home.create_page = function ( page_name )
{
	kernel.go ( 'home', { mask: 'show_page', page: page_name, search_mask: modules.home._cur_search_mask, area: modules.home._cur_area } );
};
//}}}
//{{{ create_frame ( url, name )
modules.home.create_frame = function ( url, name )
{
	kernel.go ( 'home', { mask: 'show_page', frame: url, page: name, search_mask: modules.home._cur_search_mask, area: modules.home._cur_area } );
};
//}}}
//{{{ quoty_rass_arch_list ()
modules.home.quoty_rass_arch_list = function ()
{
	if ( ! $ ( 'rightbar_lnk_archivio' ).style.display || $ ( 'rightbar_lnk_archivio' ).style.display == 'none' )
	{
		$ ( 'rightbar_lnk_archivio' ).parentNode.style.display = 'block';
		$ ( 'rightbar_lnk_archivio' ).style.display = 'block';
	}

	$ ( 'static_cnt' ).innerHTML = '';

	var s = '';
	site._areas.iterate ( function ( v, k ) {
		if ( k == 'prpag' ) return;

		site.set_tabs_data ( k, 'kernel.go(\'home\',{mask:\'rass_arch\',area:\'area_' + k + '\'})', v.lbl_tab, '' );
	} );

	modules.home._get_quoty_arch_list ( 'I0QU', 'archivio_rassegne/', function ( v ) {
		//$ ( 'static_cnt' ).innerHTML = modules.home.templates [ 'quoty_arch_cnt_cols' ];
		$ ( 'static_cnt' ).innerHTML = modules.home.templates [ 'quoty_arch_container' ];
		//$ ( 'col_years' ).innerHTML = modules.home._format_quoty_arch_year_list ( v [ 'files' ], modules.home.templates [ 'rass_arch_year_row' ] );
		$ ( 'cnt_years' ).innerHTML = modules.home._format_quoty_arch_year_list ( v [ 'files' ], modules.home.templates [ 'rass_arch_year_cnt' ] );
	} );

	//if ( modules.home._cur_opera == 'prpag' ) modules.home._cur_opera = op;

	modules.home._cur_tab_shown = modules.home._cur_opera;
	//modules.home._print_quoty_arch_list ();
	site.create_home_top ( 'area_' + modules.home._cur_opera );
	$ ( 'block_main_top_pag' ).innerHTML = 'Archivio delle Rassegne stampa';

	var area = 'area_';
	if ( modules.home._cur_tab_shown ==  'I0QU' ) area += 'prpag';
	else area += modules.home._cur_tab_shown

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';
};
//}}}
//{{{ quoty_arch_page ()
modules.home.quoty_arch_page = function ()
{
	if ( ! $ ( 'rightbar_lnk_archivio' ).style.display || $ ( 'rightbar_lnk_archivio' ).style.display == 'none' )
	{
		$ ( 'rightbar_lnk_archivio' ).parentNode.style.display = 'block';
		$ ( 'rightbar_lnk_archivio' ).style.display = 'block';
	}

	var s = '';
	var op = '';

	site._areas.iterate ( function ( v, k ) {
		if ( k == 'prpag' ) return;

		site.set_tabs_data ( k, 'kernel.go(\'home\',{mask:\'quoty_arch_main\',area:\'area_' + k + '\'})', v.lbl_tab, '' );
	} );

	$ ( 'static_cnt' ).innerHTML = '';

	//if ( modules.home._cur_opera == 'prpag' ) modules.home._cur_opera = op;

	modules.home._cur_tab_shown = modules.home._cur_opera;

	modules.home._print_quoty_arch_page_list ();

	site.create_home_top ( 'area_' + modules.home._cur_opera );
	$ ( 'block_main_top_pag' ).innerHTML = 'Archivio de "il Quotidiano Ipsoa" ';// + site._areas.get ( modules.home._cur_opera ).lbl;

	var area = 'area_';
	if ( modules.home._cur_tab_shown ==  'I0QU' ) area += 'prpag';
	else area += modules.home._cur_tab_shown

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';
};
//}}}
//{{{ quoty_arch_list ()
modules.home.quoty_arch_list = function ()
{
	if ( ! $ ( 'rightbar_lnk_archivio' ).style.display || $ ( 'rightbar_lnk_archivio' ).style.display == 'none' )
	{
		$ ( 'rightbar_lnk_archivio' ).parentNode.style.display = 'block';
		$ ( 'rightbar_lnk_archivio' ).style.display = 'block';
	}

	$ ( 'static_cnt' ).innerHTML = '';

	var s = '';
	site._areas.iterate ( function ( v, k ) {
		if ( k == 'prpag' ) return;

		site.set_tabs_data ( k, 'kernel.go(\'home\',{mask:\'quoty_arch\',area:\'area_' + k + '\'})', v.lbl_tab, '' );
	} );

	modules.home._get_quoty_arch_list ( 'I0QU', 'archivio_quoty/' + modules.home._cur_opera, function ( v ) {
		//$ ( 'static_cnt' ).innerHTML = modules.home.templates [ 'quoty_arch_cnt_cols' ];
		$ ( 'static_cnt' ).innerHTML = modules.home.templates [ 'quoty_arch_container' ];
		//$ ( 'col_years' ).innerHTML = modules.home._format_quoty_arch_year_list ( v [ 'files' ], modules.home.templates [ 'quoty_arch_year_row' ] );
		$ ( 'cnt_years' ).innerHTML = modules.home._format_quoty_arch_year_list ( v [ 'files' ], modules.home.templates [ 'quoty_arch_year_cnt' ] );
	} );

	//if ( modules.home._cur_opera == 'prpag' ) modules.home._cur_opera = op;

	modules.home._cur_tab_shown = modules.home._cur_opera;
	//modules.home._print_quoty_arch_list ();
	site.create_home_top ( 'area_' + modules.home._cur_opera );
	$ ( 'block_main_top_pag' ).innerHTML = 'Archivio de "il Quotidiano Ipsoa" ' + site._areas.get ( modules.home._cur_opera == 'I0QU' ? 'prpag' : modules.home._cur_opera ).lbl;

	var area = 'area_';
	if ( modules.home._cur_tab_shown ==  'I0QU' ) area += 'prpag';
	else area += modules.home._cur_tab_shown

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';
};
//}}}
//{{{ get_quoty_arch_month_list ( year, opera )
modules.home.get_quoty_arch_month_list = function ( year, opera )
{
	//$ ( 'col_months' ).innerHTML = site.templates [ 'progress' ];
	//$ ( 'col_files' ).innerHTML = '';
	
	var cnt = $ ( 'cnt_' + year + '_months' );

	if ( cnt._click )
	{
		if ( cnt._show ) cnt.style.display = 'none';
		else cnt.style.display = 'block';

		cnt._show = ! cnt._show;
	}
	else
	{
		cnt.innerHTML = site.templates [ 'progress' ];

		modules.home._get_quoty_arch_list ( 'I0QU', 'archivio_quoty/' + opera + "/" + year + "/", function ( v ) {
			cnt._click = true;
			cnt._show = true;
			//$ ( 'col_months' ).innerHTML = modules.home._format_quoty_arch_month_list ( year, v [ 'files' ], modules.home.templates [ 'quoty_arch_month_row' ] );
			cnt.innerHTML = modules.home._format_quoty_arch_month_list ( 'quoty', year, v [ 'files' ], modules.home.templates [ 'quoty_arch_month_cnt' ] );
		} );
	}
};
//}}}
//{{{ get_rass_arch_month_list ( year, opera )
modules.home.get_rass_arch_month_list = function ( year, opera )
{
	//$ ( 'col_months' ).innerHTML = site.templates [ 'progress' ];
	//$ ( 'col_files' ).innerHTML = '';

	var cnt = $ ( 'cnt_' + year + '_months' );

	if ( cnt._click )
	{
		if ( cnt._show ) cnt.style.display = 'none';
		else cnt.style.display = 'block';

		cnt._show = ! cnt._show;
	}
	else
	{
		cnt.innerHTML = site.templates [ 'progress' ];

		modules.home._get_quoty_arch_list ( 'I0QU', 'archivio_rassegne/' + year + "/", function ( v ) {
			//$ ( 'col_months' ).innerHTML = modules.home._format_quoty_arch_month_list ( year, v [ 'files' ], modules.home.templates [ 'rass_arch_month_row' ] );
			cnt._click = true;
			cnt._show = true;
			cnt.innerHTML = modules.home._format_quoty_arch_month_list ( 'rass', year, v [ 'files' ], modules.home.templates [ 'quoty_arch_month_cnt' ] );
		} );
	}
};
//}}}
//{{{ get_quoty_arch_file_list ( type, year, opera, month )
modules.home.get_quoty_arch_file_list = function ( type, year, opera, month )
{
	var path = '';

	if ( type == 'rass' ) path = 'archivio_rassegne/' + year + "/" + month;
	else path = 'archivio_quoty/' + opera + "/" + year + "/" + month;
	
	var cnt = $ ( 'cnt_files_' + year + '_' + month );

	//$ ( 'col_files' ).innerHTML = site.templates [ 'progress' ];

	if ( cnt._click )
	{
		if ( cnt._show ) cnt.style.display = 'none';
		else cnt.style.display = 'block';

		cnt._show = ! cnt._show;
	}
	else
	{
		cnt.innerHTML = site.templates [ 'progress' ];

		modules.home._get_quoty_arch_list ( 'I0QU', path, function ( v ) {
			cnt._click = true;
			cnt._show = true;
			//$ ( 'col_files' ).innerHTML = modules.home._format_quoty_arch_file_list ( type, year, opera, month, v [ 'files' ] );
			cnt.innerHTML = modules.home._format_quoty_arch_file_list ( type, year, opera, month, v [ 'files' ] );
		} );
	}
};
//}}}
//{{{ _format_quoty_arch_file_list ( type, year, opera, month, files )
modules.home._format_quoty_arch_file_list = function ( type, year, opera, month, files )
{
	var t, q, lf, l = files.length;
	var f;
	var s = '';
	var ord = [];
	var day;
	var templ = '';

	if ( type == 'rass' ) path = 'archivio_rassegne/' + year + "/" + month;
	else path = 'archivio_quoty/' + opera + "/" + year + "/" + month;
	

	for ( t = 0; t < l; t ++ )
	{
		f = files [ t ];
		day = parseInt ( f.split ( "." ) [ 0 ], 10 );

		ord.push ( f );
	}

	ord.reverse();
	l = ord.length;
	lf = files.length;
	var start = 0;
	if ( ( modules.home._last_year == year ) && ( modules.home._last_month == month ) ) start = 1;

	for ( t = start; t < l; t ++ )
	{
		day = ord [ t ];
		for ( q = 0; q < lf; q ++ )
		{
			f = files [ q ];

			if ( day != f ) continue;

			var name = f.split ( "." ) [ 0 ];

			if ( parseInt ( name, 10 ) < 10 ) name = ' ' + name;

			var m = month;
			if ( month > 0 ) m = month - 1;

			s += String.formatDict ( modules.home.templates [ 'list_arch_row' ], { 
				fpath: "/cgi-bin/downloader.cgi?OPERA=I0QU&MIME=application/pdf&FILE=" + path + "/" + f,
				//fpath: "/archivio/" + path + "/" + f,
				day: name, 
				year: year,
				monthname: site._months [ m ]
			} );
		}
	}

	return s;
};
//}}}
//{{{ _format_quoty_arch_month_list ( type, year, files, templ )
modules.home._format_quoty_arch_month_list = function ( type, year, files, templ )
{
	var t, q, lf, l = files.length;
	var f;
	var s = '';

	var ord = [];
	var month;

	for ( t = 0; t < l; t ++ )
	{
		f = files [ t ];
		if ( ! f.endsWith ( "/" ) ) continue;

		month = f.replace ( "/", "" );
		month = parseInt ( month, 10 );

		ord.push ( month );
	}

	ord.sort ( function ( a, b ) {
		return b - a;
	} );

	l = ord.length;
	lf = files.length;
	modules.home._last_month = null;

	for ( t = 0; t < l; t ++ )
	{
		month = ord [ t ];
		for ( q = 0; q < lf; q ++ )
		{
			f = files [ q ];
		
			if ( ! f.endsWith ( "/" ) ) continue;
		
			var name = f.replace ( "/", "" );

			if ( month != name ) continue;

			var m = name;
			if ( name > 0 ) m = name - 1;

			s += String.formatDict ( templ, { 
				//fpath: fpath + f,
				//day: f, 
				txt: site._months [ m ] + ' ' + year,
				year: year,
				opera: modules.home._cur_opera,
				month: name,
				type: type
			} );

			if ( ! modules.home._last_month )
				modules.home._last_month = name;
		}
	}

	return s;
};
//}}}
//{{{ _format_quoty_arch_year_list ( files, templ )
modules.home._format_quoty_arch_year_list = function ( files, templ )
{
	var t, l = files.length;
	var f;
	var s = '';
	var year;
	var ord = [];

	modules.home._last_year = null;

	for ( t = 0; t < l; t ++ )
	{
		f = files [ t ];
		if ( ! f.endsWith ( "/" ) ) continue;

		var name = f.replace ( "/", "" );

		if ( ! name.startsWith ( "20" ) ) continue;

		year = parseInt ( name, 10 );

		ord.push ( year );
	}

	ord.reverse();
	l = ord.length;

	for ( t = 0; t < l; t ++ )
	{
		var name = ord [ t ];

		s += String.formatDict ( templ, { 
			txt: name,
			year: name,
			opera: modules.home._cur_opera
		} );

		modules.home._last_year = name;
	}

	return s;
};
//}}}
//{{{ _get_quoty_arch_list ( opera, path )
modules.home._get_quoty_arch_list = function ( opera, path, cback )
{
	kernel.command ( 'list_dir', { opera: opera, path: path }, function ( v ) { cback ( v ) } );
};
//}}}
//{{{ show_tab_pdf_arch ( name )
modules.home.show_tab_pdf_arch = function ( name )
{
	modules.home._cur_tab_shown = name;
	modules.home._cur_opera = name;

	site.show_global_divs ( 'static' );

	var area = 'area_';
	if ( modules.home._cur_tab_shown == 'I0QU' ) area += 'prpag';
	else area += modules.home._cur_tab_shown;

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';
	
	var s = 'Archivio de "il Quotidiano Ipsoa" ';
	var op = '';

	site._areas.iterate ( function ( v, k ) {
		//if ( k == 'prpag' ) return;
		if ( k == 'prpag' ) op = 'I0QU';
		else op = k;

		if ( $ ( 'cnt_quoty_arch_' + op ) ) $ ( 'cnt_quoty_arch_' + op ).style.display = 'none';

		if ( op == modules.home._cur_tab_shown ) s += ' - ' + site._areas.get ( k ).lbl;

	} );

	if ( $ ( 'block_main_top_pag' ) ) $ ( 'block_main_top_pag' ).innerHTML = s;
	if ( $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ) ) $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ).style.display = 'block';
};
//}}}
/*
//{{{ rass_arch_list ()
modules.home.rass_arch_list = function ()
{
	if ( ! $ ( 'rightbar_lnk_archivio' ).style.display || $ ( 'rightbar_lnk_archivio' ).style.display == 'none' )
	{
		$ ( 'rightbar_lnk_archivio' ).parentNode.style.display = 'block';
		$ ( 'rightbar_lnk_archivio' ).style.display = 'block';
	}

	$ ( 'block_main_top_pag' ).innerHTML = 'Archivio PDF - Rassegna Stampa';

	modules.home._print_rass_arch_list ();

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: modules.home._cur_area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';
};
//}}}
//{{{ list_arch_by_month ( dict, data )
modules.home.list_arch_by_month = function ( dict, data )
{
	var op = '';
	site._areas.iterate ( function ( v, k ) {
		//if ( k == 'prpag' ) return;
		if ( k == 'prpag' ) op = 'I0QU';
		else op = k;

		site.set_tabs_data ( k, 'kernel.go(\'home\',{area:\'area_' + op + '\',mask:\'quoty_arch\'})', v.lbl_tab, '' );
	} );

	var year = parseInt ( dict.year, 10 );
	var month = parseInt ( dict.month, 10 ) - 1;
	var d = new Date ();

	if ( d.getMonth () == month ) d = new Date ( year, month, d.getDate () );
	else d = new Date ( year, month + 1 , 0 );

	var t, l = d.getDate ();
	var s = '';
	var start = new Date ( d.getFullYear(), d.getMonth (), 1 );
	var dset = start.getDay ();
	var templ = modules.home.templates [ 'list_arch_row' ];

	var title = 'Archivio PDF - ';
	var fpath = '';
	var op = '';

	if ( modules.home._cur_mask == 'arch_quot_month' )
	{
		if ( modules.home._cur_opera == 'prpag' ) op = 'I0QU';
		else op = modules.home._cur_opera;

		fpath = 'archivio_quoty/' + op + '/';
		title += site._months [ month ] + ' - ' + site._areas.get ( modules.home._cur_opera ).lbl;
	}
	else
	{
		fpath = 'archivio_rassegne/';
		title += ' - ' + site._months [ month ];
	}

	fpath += year + '/' + ( month + 1 ) + '/';

	$ ( 'block_main_top_pag' ).innerHTML = title; 

	kernel.command ( 'list_dir', { opera: 'I0QU', path: fpath }, function ( v ) {
		var files = v [ 'files' ];
		l = files.length;
		var f;
		for ( t = 0; t < l; t ++ )
		{
			f = files [ t ];
			s += String.formatDict ( templ, { 
				fpath: fpath + f,
				day: f, 
				dayname: site._day_name [ ( dset % 7 ) ],
				year: year,
				monthname: site._months [ month ]
			} );

			dset ++;
		}
		$ ( 'static_cnt' ).innerHTML = s;
	} );

}; 
//}}}
*/
//{{{ _print_quoty_arch_page_list ()
modules.home._print_quoty_arch_page_list = function ()
{
	var now = new Date ();
	var op = '';
	var s = '';

	site._areas.iterate ( function ( v, k ) {
		if ( k == 'prpag' ) return;

		s += String.formatDict ( modules.home.templates [ 'view_quoty_arch_lnk' ], { area: k, txt: v.lbl_tab } );
	} );

	$ ( 'static_cnt' ).innerHTML = modules.home.templates [ 'view_quoty_arch_lnk_header' ] + s;

	//if ( $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ) ) $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ).style.display = 'block';
};
//}}}
//{{{ _print_quoty_arch_list ()
modules.home._print_quoty_arch_list = function ()
{
	var now = new Date ();
	var op = '';

	site._areas.iterate ( function ( v, k ) {
		//if ( k == 'prpag' ) return;
		if ( k == 'prpag' ) op = 'I0QU';
		else op = k;

		modules.home._format_arch_list ( modules.home.templates [ 'quot_arch_view_month' ], now, 'cnt_quoty_arch_' + op, 'area_' + k );
	} );

	if ( $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ) ) $ ( 'cnt_quoty_arch_' + modules.home._cur_tab_shown ).style.display = 'block';
};
//}}}
//{{{ _print_rass_arch_list ()
modules.home._print_rass_arch_list = function ()
{
	var now = new Date ();

	modules.home._format_arch_list ( modules.home.templates [ 'rass_arch_view_month' ], now, 'static_cnt' );
};
//}}}
//{{{ _format_arch_list ( templ, now, dest, area )
modules.home._format_arch_list = function ( templ, now, dest, area )
{
	var s = '';
	var now = new Date ();
	//al max 6 mesi indietro
	var end = new Date ( now.getFullYear(), now.getMonth () - 6, now.getDate () );

	//TODO: stabilire data inizio/pubblicazione
	var limit = new Date ( 2008, 8, 1 );

	//prendo la data piu' grande tra le due
	var d_end = new Date ( Math.max ( limit, end ) );

	//if ( area && ( area == 'prpag' ) ) area = 'I0QU';

	while ( now >= d_end )
	{
		var cur_y = now.getFullYear();
		var cur_m = now.getMonth ();
		var d = new Date ( cur_y, cur_m, 1 );
		s += String.formatDict ( templ, {
			txt: site._months [ d.getMonth() ] + ' ' + d.getFullYear (), 
			month: d.getMonth() + 1,
			year: d.getFullYear (),
			area: area ? area : ''
		} ) + '<br />';

		now = new Date ( cur_y, cur_m - 1, 1 );
	}

	$ ( dest ).innerHTML = s;
};
//}}}
//=========  PRIVATE ==================
//{{{ _init_list ( dict, data )
modules.home._init_list = function ( dict, data )
{
	var lbl = '';
	var type = dict.get ( "mask" );
	//site.create_home ( dict, data );

	if ( ! $ ( "DOCUMENT_TEXT" ) )
		site.show_mask ( modules.home._cur_search_mask, dict, data, modules.home.show_mask_done );

	site.show_global_divs ( "list" );
	window.scrollTo (0,0);
	
	switch ( type )
	{
		case "commenti":
			lbl = 'Commenti ';
			modules.home._fill_2lists ( type, modules.home._format_list_today_comment );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "list_oss_giurisp":
			lbl = 'Osservatorio giurispr. ';
			modules.home._fill_2lists ( type, modules.home._format_list_oss_giurisp, null, 300 );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "list_rinn_ccnl":
			lbl = 'Rinnovi CCNL ';
			modules.home._fill_2lists ( type, modules.home._format_list_rinn_ccnl, null, 300 );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "list_dat_tabel":
			lbl = 'Dati tabellari ';
			modules.home._fill_2lists ( type, modules.home._format_list_dat_tabel, null, 300 );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "list_commr_vista":
			lbl = 'Il commercialista in vista ';
			modules.home._fill_2lists ( type, modules.home._format_list_commr_vista, null, 300 );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "last7comm":
			lbl = 'Commenti ';
			modules.home._fill_2lists ( type, modules.home._format_list_7today_comment );
			
			site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), lbl );
			break;
		case "list_rass_stampa":
			lbl = 'Rassegna stampa ';
			$ ( 'block_main_top_pag' ).innerHTML = lbl;
			modules.home._fill_2lists ( type, modules.home._format_list_rass_stampa );
			break;
	}
};
//}}}
//{{{ _fill_mask ( data )
modules.home._fill_mask = function ( data )
{
	/*
        var t, l = modules.home._mask_fields.length;
        for ( t = 0; t < l; t ++ )
        {
                var f = modules.home._mask_fields [ t ];
                var v = data.get ( f, "" );

                var el = document.getElementById ( f );
                if ( ! el ) continue;

                if ( f.startsWith ( "CHK_" ) )
                {
                        if ( el.checked != ( v.length > 0 ) )
                        {
                                modules.home._requery = true;
                                el.checked = ( v.length > 0 );
                        }
                }
                else
                {
                        if ( el.value != v )
                        {
                                modules.home._requery = true;
                                el.value = v;
                        }
                }
        }
	*/

	if ( data [ 'mode' ] != 'doc' )
		modules.home._start_search ( data );
};
//}}}
//{{{ _set_form_events ()
modules.home._set_form_events = function ()
{
	liwe.events.add ( $( 'main_top_mask' ), 'keydown', modules.home._search_keydown );
};
//}}}
//{{{ _search_keydown ( e )
modules.home._search_keydown = function ( e )
{
	var keycode;

	if ( window.event ) keycode = window.event.keyCode;
	else if ( e ) keycode = e.which;
	else return false;

	if ( keycode != 13 ) return false;
	return modules.home.search_click ( { mask: 'search', area: modules.home._cur_area, search_form: modules.home._cur_search_mask } );
};
//}}}
//{{{ _start_search ( fields )
modules.home._start_search = function ( fields )
{
	if ( ! modules.home._requery && modules.home._ds )
	{
		site.show_global_divs ( 'search' );
		modules.home._ds.iterate ( function ( v, k ) {
			var ds = modules.home._ds [ k ];
			var tot_td = $ ( 'tot_' + ds.name + '_td' );
			tot_td.innerHTML = '(' + ds.num_rows + ')';
		} );

		return;
	}

	$ ( 'block_main_body_results' ).innerHTML = '';
	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: modules.home._cur_area } );
	$ ( 'block_main_top_downl' ).style.display = 'block';

	modules.home._res_render = null;
	modules.home._index_man = {};
	
	site._print_top_sect ( site._cod_op_by_idarea ( modules.home._cur_area ), 'Ricerca ' );

	if ( fields.get ( "DOCUMENT_TEXT", null ) )
		modules.home._highlight = fields.get ( "DOCUMENT_TEXT" );

	site.set_area_tabs ( 'search', true );

	site._areas.iterate ( function ( v, k ) {
		//if ( k == 'prpag' ) return;

		$ ( 'tot_' + k + '_td' ).innerHTML = site.templates [ 'progress_small' ];
		$ ( 'block_main_body_results' ).innerHTML += String.formatDict ( modules.home.templates [ 'cnt_result_ds' ], { name: k });

		$ ( "results_body_" + k ).innerHTML = site.templates [ 'progress' ];

		if ( $ ( 'cnt_results_' + k ) ) $ ( 'cnt_results_' + k ).style.display = 'none';

		//$ ( 'results_tree_' + k ).innerHTML = modules.home.templates [ 'cnt_results_tree' ];
		//$ ( 'results_tree_' + k ).innerHTML = '';
		//$ ( "results_navi_" + k ).innerHTML = modules.home.templates [ 'cnt_navi' ];
		//$ ( "results_top_" + k ).innerHTML = "";

		var ds = modules.home._init_ds ( k );
		ds.lines_per_page = 15;

		var fq = new FulQuery ();
		fq.set_id ();
		fq.db_name = "QUOTYI0QU";
		fq.mode = 'QUERY';
		fq.opera = 'I0QU';
		fq.set_fields ( 'ID', 'TITOLO', 'DESCR_TIPO', 'AUTORE', 'DATA', "COD_OPERA", "COGNOME_AUTORE", "TIPO", "ESTREMI", "ABSTRACT" );

		var tipo = [];
		var t, l = modules.home._mask_fields_chks.length;
		for ( t = 0; t < l; t ++ )
		{
			var chk_tipo = modules.home._mask_fields_chks [ t ];
			if ( fields [ chk_tipo ] )
			{
				tipo.push ( fields [ chk_tipo ] );
			}
		}

		if ( k != "prpag" ) fq.add ( "COD_OPERA", "EQUAL", k );

		if ( tipo.length <= 0 ) fq.add ( "TIPO", "IN_NUM", "34|36|87|88|92" );
		else fq.add ( "TIPO", "IN_NUM", tipo.join ( "|" ) );

		fq.add ( "DOCUMENT_TEXT", "FULTXT", fields.get ( 'DOCUMENT_TEXT' ) );

		fq.add ( "ANNO1", "DATA", fields [ "ANNO1" ], "DATA" );
		fq.add ( "MESE1", "DATA", fields [ "MESE1" ], "DATA" );
		fq.add ( "GIORNO1", "DATA", fields [ "GIORNO1" ], "DATA" );

		fq.add ( "ANNO2", "DATA", fields [ "ANNO2" ], "DATA" );
		fq.add ( "MESE2", "DATA", fields [ "MESE2" ], "DATA" );
		fq.add ( "GIORNO2", "DATA", fields [ "GIORNO2" ], "DATA" );

		fq.add ( "AUTORE", "EQUAL", fields [ "AUTORE" ] );

		if ( modules.home._query_id && ( ! site.query_dict.get ( fields [ "_X_TRACK_ID" ] ) ) )
		{
			fields [ "_X_TRACK_ID" ] = modules.home._query_id;
			site.query_dict [ modules.home._query_id ] = true;
		}
		else
			delete fields [ "_X_TRACK_ID" ];


		fq.fill ( fields );

		ds.set_fields ( fields );

		ds.fill ( modules.home._render_ds );
		/*
		ds.fill ( function ()
		{
			modules.home._requery = false;

			$ ( 'results_tree' ).innerHTML = modules.home.templates [ 'cnt_results_tree' ];
			$ ( 'tree_body_results' ).innerHTML = modules.home.templates [ 'progress' ];
			ds.show_results_table ( "results_body" );
		} );	
		*/
	} );
};
//}}}

modules.home.show_tab_res = function ( name )
{
	modules.home._cur_tab_shown = name;

	site.show_global_divs ( 'search' );

	$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: 'area_' + modules.home._cur_tab_shown } );
	$ ( 'block_main_top_downl' ).style.display = 'block';

	site._areas.iterate ( function ( v, k ) {
		//if ( k == 'prpag' ) return;

		if ( $ ( 'cnt_results_' + k ) ) $ ( 'cnt_results_' + k ).style.display = 'none';
		if ( k != modules.home._cur_tab_shown ) return;

		var s = "";
		if ( k == 'prpag' ) s = 'Tutti i risultati';
		else s = 'Risultati ' + site._areas.get ( k ).lbl;

		if ( $ ( 'block_main_top_pag' ) ) $ ( 'block_main_top_pag' ).innerHTML = s;
	} );

	if ( $ ( 'cnt_results_' + name ) ) $ ( 'cnt_results_' + name ).style.display = 'block';
};

//{{{ _render_ds ( ds )
modules.home._render_ds = function ( ds )
{
	var fields = ds.get_fields ();
	var lbl_tab = site._areas [ ds.name ].lbl_tab;

	if ( ds.name == 'prpag' ) lbl_tab = 'Tutti i risultati';

	site.set_tabs_data ( ds.name, 'site.create_home_top(\'area_' + ds.name + '\');modules.home.show_tab_res(\'' + ds.name + '\');site._create_rightbox ( \'' + ds.name + '\' )', lbl_tab, '' );

	/*
	$ ( 'area_' + ds.name ).innerHTML = String.formatDict ( site.templates [ 'top_tab' ], {
		'func': 'site.create_home_top(\'area_' + ds.name + '\');modules.home.show_tab_res(\'' + ds.name + '\');site._create_rightbox ( \'' + ds.name + '\' )',
		'area': ds.name,
		'lbl_tab': lbl_tab,
		'tot': ''
	} );
	*/

	var tot_td = $ ( 'tot_' + ds.name + '_td' );
	tot_td.innerHTML = '(' + ds.num_rows + ')';

	if ( ds.num_rows == 0 ) $ ( 'results_body_' + ds.name ).innerHTML = modules.home.templates [ "no_res" ];
	else ds.render ( "results_body_" + ds.name );
		
	//if ( site._cod_op_by_idarea ( modules.home._cur_area ) == ds.name ) $ ( 'cnt_results_' + ds.name ).style.display = 'block';
	//else $ ( 'cnt_results_' + ds.name ).style.display = 'none';

	var im = null;
	if ( ! modules.home._index_man [ ds.name ] )
	{
		$ ( 'results_tree_' + ds.name ).innerHTML = String.formatDict ( modules.home.templates [ 'cnt_results_tree' ], { name: ds.name } );
		$ ( 'tree_body_results_' + ds.name ).innerHTML = modules.home.templates [ 'progress' ];

		im = modules.home._index_man [ ds.name ] = new IndexManager();

		im.set_id = true;
		im.db_name = "CLASSI0QU";
		im.opera = "I0QU";
		im.render_tree ( "tree_body_results_" + ds.name, ds );
	}

	if ( ! modules.home._res_render )
	{
		site._create_rightbox ( ds.name );
		$ ( 'block_main_body_results' ).innerHTML += modules.home.templates [ 'toolbar' ];
		site.tbar.clear ();
		$ ( 'toolbar' ).style.display = 'none';
		$ ( 'toolbar_body' ).innerHTML = '';

		site._set_selected_area ( 'area_' + ds.name );
		modules.home._res_render = true;
		modules.home.show_tab_res ( ds.name );

		if ( ds.num_rows > 0 )
		{
			//site.tbar.add ( 'Salva la ricerca', function () { site.save_ric ( "home", "m:search", modules.home._cur_area, modules.home._cur_search_mask, fields ); } );
			site.tbar.add ( 'Stampa risultati della ricerca', function () { modules.home.print_search_results (); } );
			site.tbar.render ( 'toolbar_body' );
			$ ( 'toolbar' ).style.display = 'block';

			actionbar.init ( ds, "results_body_" + ds.name, null, ds._print_template );
		}
		else $ ( 'toolbar' ).style.display = 'none';
	}
};
//}}}
modules.home.get_page2print = function ()
{
	modules.home._print_data.ds.rows = [];
	modules.home._print_data.ds.num_rows = 0;
	modules.home._print_data.ds.from_row = 0;
	modules.home._print_data.ds.to_row = 0;
	modules.home._print_data.ds._form_fields [ '_X_START_POINT' ] = 0;

	var from = parseInt ( $ ( "from_page" ).value, 10 );
	var to = parseInt ( $ ( "to_page" ).value, 10 );

	if ( from < 1 ) from = 1;
	else if ( from > modules.home._print_data.num_page ) from = modules.home._print_data.num_page;

	if ( to < 1 ) to = 1;
	else if ( to > modules.home._print_data.num_page ) to = modules.home._print_data.num_page;

	if ( to > ( from + modules.home._print_data.limit_page ) ) to = from + modules.home._print_data.limit_page;

	if ( from > to ) from = to;

	var from_row = 0;
	
	modules.home._print_data.ds.from_row = Math.floor ( ( from - 1 ) * modules.home._print_data.orig_lines );
	modules.home._print_data.ds._form_fields [ '_X_START_POINT' ] = modules.home._print_data.ds.from_row;
	modules.home._print_data.ds.to_row = Math.floor ( to * modules.home._print_data.orig_lines );

	liwe.lightbox.close ();

	modules.home.results2print ();
};

modules.home.print_search_results = function ()
{
	modules.home._limit = 200;
	var _ds = modules.home._ds.get ( modules.home._cur_tab_shown );
	_ds = _ds.clone ();
	_ds.to_row = _ds.num_rows;
	var orig_lines = _ds.lines_per_page;
	var num_page = Math.floor ( ( _ds.num_rows - 1 ) / _ds.lines_per_page ) + 1;
	var limit_page = Math.floor ( modules.home._limit / _ds.lines_per_page );

	modules.home._print_data = {
		'limit': 200,
		ds: _ds,
		orig_lines: _ds.lines_per_page,
		num_page: num_page,
		limit_page: limit_page
	};
	
	if ( _ds.num_rows > 200 )
	{
		//modules.home._show_page_request ( limit_page );
		alert ( 'Si possono stampare un massimo di ' + modules.home._limit + ' risultati. Si consiglia di raffinare la ricerca.' );
	}
	else modules.home.results2print ();
};

modules.home._show_page_request = function ( limit_page )
{
	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "print_page", "Stampa", 500, 150 );

	var div = $ ( "print_page" );
	div.innerHTML = String.formatDict ( modules.home.templates [ "page2print" ], modules.home._print_data );

	$ ( "from_page" ).focus ();
	$ ( "to_page" ).value = limit_page;
};

modules.home.results2print = function ()
{
	var ds = modules.home._print_data.ds;
	ds.lines_per_page = ds.to_row - ds.from_row;

	ds.fill ( function () {
		//ds.to_row = ds.num_rows;
		var wnd = window.open ();
		if ( ! wnd ) return;

		var s = ds.to_string ();
		var dct = { _title: '- Risultati ricerca', _content: s };

		s = String.formatDict ( modules.home.templates [ 'print_lists' ], dct );

		wnd.document.write ( s );
		wnd.document.close ();
		wnd.print ();
		wnd.close ();
	} );
};
//{{{ _init_ds ( area )
modules.home._init_ds = function ( area )
{
	if ( ! modules.home._ds ) modules.home._ds = {};

	var ds = modules.home._ds [ area ] = new DataSet ( area );

	ds.templates [ 'table_start' ] = modules.home.templates [ 'ds_table_start' ];
	ds.templates [ 'table_header' ] = modules.home.templates [ 'ds_table_header' ];
	ds.templates [ 'table_end' ] = modules.home.templates [ 'ds_table_end' ];
	ds.templates [ 'table_row' ] = modules.home.templates [ 'ds_table_row' ];
	ds.templates [ 'prev_page' ] = modules.home.templates [ 'ds_prev_page' ];
	ds.templates [ 'next_page' ] = modules.home.templates [ 'ds_next_page' ];
	ds.templates [ 'table_footer' ] = modules.home.templates [ 'ds_table_footer' ];

	ds._print_template = modules.home.templates [ 'print_template' ];

	ds.cbacks [ "show_results" ] = modules.home._ds_show_results;
	ds.cbacks [ "row_manip" ] = modules.home._ds_row_manip;

	return ds;
};
//}}}
//{{{ _ds_show_results ( ds )
modules.home._ds_show_results = function ( ds )
{
	//$ ( "results_top_" + ds.name ).innerHTML = String.formatDict ( modules.home.templates [ 'ds2areahome' ], { name: ds.name, home: site._areas [ ds.name ].lbl } );//ds.format_str ( site.templates [ "results_top" ] );

	var s = "";
	if ( ds.num_rows ) s = ds.format_str ( site.templates [ 'results_navi' ] );

	$ ( "results_navi_body_" + ds.name ).innerHTML = s;
	$ ( 'navi_tot_' + ds.name ).innerHTML = 'Risultati: ' + ds.num_rows;
	$( 'navi_page_' + ds.name ).innerHTML = 'Pagina ' + ( ds.page + 1 ) + '/' + ( Math.ceil( ds.num_rows / ds.lines_per_page ) );
};
//}}}
//{{{ _ds_row_manip ( ds, row )
modules.home._ds_row_manip = function ( ds, row )
{
	row [ '_ds_name' ] = ds.name;

	row [ '_cur_area' ] = 'area_' + ds.name;

	row [ '_data' ] = utils.order_date ( row [ 'DATA' ], "-", "IT", "/" );

	row [ '_descr_tipo' ] = '';
	if ( row [ 'TIPO' ] == "86" ) row [ '_descr_tipo' ] = 'News';
	else row [ '_descr_tipo' ] = row [ 'DESCR_TIPO' ];

	if ( ! row [ 'AUTORE' ] ) row [ 'AUTORE' ] = '&nbsp;';
	if ( ! row [ 'COGNOME_AUTORE' ] ) row [ 'COGNOME_AUTORE' ] = '&nbsp;';

	row [ '_highlight' ] = ',highlight:\'\'';
	if ( modules.home._highlight )
		//row [ '_highlight' ] = ',highlight:\'' + escape ( modules.home._highlight ) + '\'';
		row [ '_highlight' ] = ',highlight:\'' + escape ( modules.home._highlight.replace ( /\'/g, "\\'" ) ) + '\'';

	row [ '_search_form' ] = ',search_form:\'search\'';
	if ( modules.home._cur_search_mask ) row [ '_search_form' ] = ',search_form:\'' + modules.home._cur_search_mask + '\'';

	row [ '_area' ] = '';
	var dct_area = site._areas.get ( row [ "COD_OPERA" ] );
	if ( dct_area ) row [ '_area' ] = dct_area.lbl_tab.split ( " " ) [ 0 ].replace ( "," , "" );

	if ( ! site.user_check_opera ( row [ "COD_OPERA" ] ) )
		row [ "func" ] = String.formatDict ( modules.home.templates [ "ds_table_row_func_nologged" ], row );
	else
		row [ "func" ] = String.formatDict ( modules.home.templates [ "ds_table_row_func" ], row );

	row [ '_titolo' ] = row [ 'TITOLO' ];

	if ( ds.name == "I0Q4" && row [ 'TIPO' ] == '88' )
	{
		if ( row [ 'OCCHIELLO' ] && ( row [ 'OCCHIELLO' ].length > 5 ) ) row [ '_titolo' ] = row [ 'OCCHIELLO' ] + " " + row [ 'TITOLO' ] + " " + row [ 'ESTREMI' ];
		else if ( row [ 'ABSTRACT' ].length > 5 ) row [ '_titolo' ] = row [ 'TITOLO' ] + " " + row [ 'ABSTRACT' ];
	}
};
//}}}
//{{{ _format_list_rass_stampa ( v )
modules.home._format_list_rass_stampa = function ( v )
{
	//fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'FILE_NAME', 'COD_OPERA' );
	$ ( 'block_main_body_list' ).innerHTML = modules.home.templates [ 'cnt_rass_stampa' ];
	site.tbar_rass_stampa.clear ();

	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'lst_rass_stampa_row', function ( row ) {
			if ( row [ '_area_name' ] ) row [ '_area_name' ] = row [ '_area_name' ].replace ( "|", "" );
	} );
	var s = r.get ( 'txt', '' );
	var ids = r.get ( 'ids', [] );


	if ( l > 0 )
	{
		s = String.formatDict ( modules.home.templates [ 'rass_stampa_cnt' ], { txt: s } );
			site.tbar_rass_stampa.add ( '&nbsp;', function () { modules.home._rass_stampa_save ( ids, true ); } );
			site.tbar_rass_stampa.add ( '&nbsp;', function () { modules.home._rass_stampa_save ( ids ); } );
			site.tbar_rass_stampa.render ( 'toolbar_rass_stampa_body' );
			$ ( 'toolbar_rass_stampa' ).style.display = 'block';
	}
	else
		s = modules.home.templates [ 'no_res' ];

	$ ( 'cnt_lst_rass_stampa' ).innerHTML = s;
};
//}}}

modules.home._rass_stampa_save = function ( ids, print )
{
	var t, l = ids.length;
	var s = '';

	var mode = 'open';
	//if ( print ) mode = 'open';

	for ( t = 0; t < l; t ++ )
	s += "'" + ids [ t ] + "'@";
	if ( s.length > 0 ) window.open ( "/cgi-bin/DocPrint?MODE=" + mode + "&_X_OPERA=I0QU&_X_DBNAME=QUOTY&TEMPLATE=rass_stampa&KEY0=" + s );
};

modules.home._rass_stampa_print = function ( elem )
{
	var wnd;

	wnd = window.open ();
	wnd.document.write ( elem.innerHTML );
	wnd.document.close ();
	wnd.print ();
	wnd.close ();
};

//{{{ _format_list_dat_tabel ( v )
modules.home._format_list_dat_tabel = function ( v )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var code = null;

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;

		if ( ! code )
		{
			code = row [ 'COD_DATITAB' ];
			s += String.formatDict (  modules.home.templates [ 'datitab_start' ], { _code: code, _descr_datitab: row [ 'DESCR_DATITAB' ] } );
		}
		else if ( code != row [ 'COD_DATITAB' ] )
		{
			s += '</div>';
			code = row [ 'COD_DATITAB' ];
			s += String.formatDict (  modules.home.templates [ 'datitab_start' ], { _code: code, _descr_datitab: row [ 'DESCR_DATITAB' ] } );
		}


		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;

		if ( row [ 'ESTREMI' ] ) row [ 'ESTREMI' ] = LinkReplacer.lnk2span ( row [ 'ESTREMI' ] );
		
		row [ '_area_name' ] = '';
		var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
		if ( area_name ) row [ '_area_name' ] = area_name + ' | ';

		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) 
			s += String.formatDict (  modules.home.templates [ 'dat_tabel_row' ], row );
		else
			s += String.formatDict (  modules.home.templates [ 'dat_tabel_row_nologged' ], row );

	}

	if ( l > 0 )
	{
		s += '</div>';
		s = String.formatDict ( modules.home.templates [ 'dat_tabel_cnt' ], { txt: s } );
	}
	else s = modules.home.templates [ 'no_res' ];

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _fill_2lists ( type, cback, anteprima, lines )
modules.home._fill_2lists = function ( type, cback, anteprima, lines )
{
	var fq = new FulQuery ();
	var dct = {};
	var d = new Date ();

	function _do_query ()
	{
		fq.db_name = "QUOTYI0QU";
		fq.mode = 'QUERY';
		fq.opera = 'I0QU';

		if ( $ ( 'block_main_body_list' ) ) $ ( 'block_main_body_list' ).innerHTML = modules.home.templates [ 'progress' ];

		kernel.fulquery ( fq, cback );
	}

	if ( modules.home._cur_opera != "prpag" ) fq.add ( 'COD_OPERA', 'EQUAL', modules.home._cur_opera );

	switch ( type )
	{
		case "commenti":
			fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'AUTORE', 'OCCHIELLO', 'TIPO', 'ESTREMI', 'COD_OPERA', 'ORA', 'TIPO'  );
			fq.add ( 'TIPO', 'EQUAL', '87' );
			if ( anteprima ) fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'S' );

			//FIXME: quando online decommentare per le news del giorno
			//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

			fq.set_id ();
			fq.order_by = "DATA DESC, ORA DESC";

			fq.lines = lines ? lines : 6;
			break;
		case "list_oss_giurisp":
			fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'AUTORE', 'OCCHIELLO', 'COD_OPERA', 'ABSTRACT', 'ESTREMI', 'TIPO' );
			fq.add ( 'TIPO', 'EQUAL', '88' );
			//FIXME: quando online decommentare per le news del giorno
			//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );
			fq.set_id ();
			fq.order_by = "DATA DESC";
			fq.lines = lines ? lines : 10;
			break;
		case "list_rinn_ccnl":
			fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'OCCHIELLO', 'COD_OPERA', 'TIPO'  );
			fq.add ( 'TIPO', 'EQUAL', '36' );
			//FIXME: quando online decommentare per le news del giorno
			//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );
			fq.set_id ();
			fq.order_by = "DATA DESC";
			fq.lines = lines ? lines : 10;
			break;
		case "list_dat_tabel":
			fq.set_fields ( 'ID', 'TITOLO', 'DESCR_DATITAB', 'COD_OPERA', 'COD_DATITAB', 'TIPO'  );
			fq.add ( 'TIPO', 'EQUAL', '33' );
			fq.order_by = "DESCR_DATITAB";
			fq.set_id ();
			//fq.order_by = "DATA DESC";
			fq.lines = lines ? lines : 10;
			break;
		case "list_commr_vista":
			fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'AUTORE', 'OCCHIELLO', 'COD_OPERA', 'TIPO'  );
			fq.add ( 'TIPO', 'EQUAL', '35' );
			//FIXME: quando online decommentare per le news del giorno
			//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );
			fq.set_id ();
			fq.order_by = "DATA DESC";
			fq.lines = lines ? lines : 10;
			break;
		case "last7comm":
			var n = new Date ();
			n.setDate ( n.getDate () - 7 );

			fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'AUTORE', 'OCCHIELLO', 'TIPO', 'ESTREMI', 'COD_OPERA' );
			fq.add ( 'TIPO', 'EQUAL', '87' );

			//FIXME: quando online decommentare
			//fq.add_date ( n.getFullYear(), ( n.getMonth() + 1 ), n.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

			fq.set_id ();
			fq.order_by = "DATA DESC";

			fq.lines = lines ? lines : '99999';
			break;
		case "list_rass_stampa":
			var n = new Date ();
			//n.setDate ( n.getDate () - 7 );

			fq.set_fields ( 'ID', 'TIPO', 'TITOLO', 'OCCHIELLO', 'DATA', 'DESCR_TIPO', 'AUTORE', 'DOCUMENT_TEXT', 'COD_OPERA', 'ORD_AREA' );
			fq.add ( 'TIPO', 'EQUAL', '34' );

			//FIXME: quando online decommentare
			//fq.add_date ( n.getFullYear(), ( n.getMonth() + 1 ), n.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

			fq.set_id ();
			fq.order_by = "DATA DESC";

			fq.lines = 1;

			fq.db_name = "QUOTYI0QU";
			fq.mode = 'QUERY';
			fq.opera = 'I0QU';

			fq.fill ( dct );

			kernel.ajax ( '/cgi-bin/FulQuery', dct, function ( v ) {
				dct = {};

				if ( ! v [ 'rows' ] ) $ ( 'cnt_lst_rass_stampa' ).innerHTML = modules.home.templates [ "no_res" ];
				else
				{
					var data = v [ 'row0' ] [ 'DATA' ];

					fq.add ( 'DATA', 'EQUAL', data );
					fq.lines = 99999;
					fq.order_by = 'ORD_AREA';
				}

				_do_query ();
			});
			return;

			break;
	}

	_do_query ();
};
//}}}
//{{{ _format_list_oss_giurisp ( v )
modules.home._format_list_oss_giurisp = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'oss_giurisp_row' );
	var s = r.get ( 'txt', '' );

	if ( l > 0 ) s = String.formatDict ( modules.home.templates [ 'oss_giurisp_cnt' ], { txt: s } );

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _format_list_rinn_ccnl ( v )
modules.home._format_list_rinn_ccnl = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'rinn_ccnl_row' );
	var s = r.get ( 'txt', '' );


	if ( l > 0 ) s = String.formatDict ( modules.home.templates [ 'rinn_ccnl_cnt' ], { txt: s } );
	else s = modules.home.templates [ 'no_res' ];

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _format_list_commr_vista ( v )
modules.home._format_list_commr_vista = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'commr_vista_row' );
	var s = r.get ( 'txt', '' );


	if ( l > 0 ) s = String.formatDict ( modules.home.templates [ 'commr_vista_cnt' ], { txt: s } );

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _format_list_7today_comment ( v )
modules.home._format_list_7today_comment = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'today_last7_comm_row', function ( row ) {
			row [ '_cls_tipo' ] = '';
			var cls_name = site.tipo2name ( row [ 'TIPO' ] );
			if ( cls_name ) row [ '_cls_tipo' ] = '_' + cls_name;
	} );

	var s = r.get ( 'txt', '' );


	if ( l > 0 ) s = String.formatDict ( modules.home.templates [ 'today_comm_cnt' ], { txt: s } );

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _fetch_list_rows ( v, templ_row, cback )
modules.home._fetch_list_rows = function ( v, templ_name, cback )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var ids = [];

	for ( t = 0; t < l; t ++ )
	{
		var templ = templ_name;

		row = v [ "row" + t ];
		if ( ! row ) continue;

		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;

		if ( row [ 'ESTREMI' ] ) row [ 'ESTREMI' ] = LinkReplacer.lnk2span ( row [ 'ESTREMI' ] );
		
		row [ '_area_name' ] = '';
		var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
		if ( area_name ) row [ '_area_name' ] = area_name + ' | ';

		if ( row [ 'COD_OPERA' ] == "I0Q4" && row [ 'TIPO' ] == '88' )
		{
			templ = templ_name + "2";
			row [ '_txt' ] = "";

			if ( row [ 'ABSTRACT' ] ) row [ '_txt' ] = '<div class="txt_black abstract" style="margin-bottom: 5px;">' + row [ 'ABSTRACT' ] + '</div>';
			row [ '_txt' ] += '<div class="estremi" style="margin-bottom: 15px;">' + row [ 'ESTREMI' ] + '</div>';
		}

		if ( cback ) cback ( row );

		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) 
			s += String.formatDict (  modules.home.templates [ templ ], row );
		else
			s += String.formatDict (  modules.home.templates [ templ + '_nologged' ], row );

		ids.push ( row [ 'ID' ] );
	}

	return { txt: s, ids: ids };
};
//}}}
//{{{ _format_list_today_comment ( v )
modules.home._format_list_today_comment = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'today_list_comm_row', function ( row ) {
			row [ '_cls_tipo' ] = '';
			var cls_name = site.tipo2name ( row [ 'TIPO' ] );
			if ( cls_name ) row [ '_cls_tipo' ] = '_' + cls_name;
	} );


	var s = r.get ( 'txt', '' );

	site.get_corrs ( r.get ( 'ids', [] ), [ '79' ], modules.home._render_corrs );

	if ( l > 0 )
	{
		s = String.formatDict ( modules.home.templates [ 'today_comm_cnt' ], { txt: s } );

		s += String.formatDict ( modules.home.templates [ 'last7_comm' ], { area: modules.home._cur_area } );
	}
	else
		s = modules.home.templates [ "no_res" ];

	$ ( 'block_main_body_list' ).innerHTML = s;
};
//}}}
//{{{ _format_today_comment ( v )
modules.home._format_today_comment = function ( v )
{
	var l = v [ 'rows' ];
	var r = modules.home._fetch_list_rows ( v, 'today_comm_row', function ( row ) {
			row [ '_sep' ] = '';
			if ( row [ '_area_name' ] )
			{
				row [ '_area_name' ] = row [ '_area_name' ].replace ( "|", "" );
				row [ '_sep' ] = ' | ';
			}
	} );
	var s = r.get ( 'txt', '' );


	if ( l > 0 ) s = modules.home.templates [ 'today_comm_header' ] + String.formatDict ( modules.home.templates [ 'today_comm_cnt' ], { txt: s } );

	$ ( 'block_main_body_today_comm' ).innerHTML = s;
	modules.home._set_adnk_top ();

	LinkReplacer.replace ( modules.doc._link_replace );
};
//}}}
//{{{ _fill_last_news ( ids )
modules.home._fill_last_news = function ( ids )
{
	var fq = new FulQuery ();
	var d = new Date ();


	fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'AUTORE', 'OCCHIELLO', 'TIPO', "COD_OPERA", "ORA" );
	//fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'N' );
	fq.add ( 'TIPO', 'IN_NUM', '92|86' );
	fq.add ( 'FULTIPO', 'EQUAL', '5' );
	
	var ids = ids.join ( "|" );
	if ( ids ) fq.add ( "ID", "NOT_IN_STR", ids );

	//FIXME: quando online decommentare per le news del giorno
	// fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

	fq.set_id ();
	fq.order_by = "DATA DESC, ORA DESC";
	fq.lines = 20;

	fq.db_name = "QUOTYI0QU";
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	$ ( 'last_news_smooth_roll_render' ).innerHTML = modules.home.templates [ 'progress' ];

	kernel.fulquery ( fq, modules.home._format_last_news );
};
//}}}
//{{{ _format_last_news ( v )
modules.home._format_last_news = function ( v )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var min = modules.home._today.getMinutes();
	if ( parseInt ( min ) < 10 ) min = '0' + min ;
	var str_now = modules.home._today.getHours() + ':' + min;

	$ ( 'last_news_smooth_roll_render' ).innerHTML = '';
	site.smooth_roll.clear();

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;
	
		s = '';
		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;
		row [ '_area_name' ] = '';
		var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
		if ( area_name ) row [ '_area_name' ] = area_name + ' | ';

		if ( row [ 'ORA' ] ) row [ 'ORA' ] = row [ 'ORA' ] + " | ";

		if ( row [ 'ESTREMI' ] ) row [ 'ESTREMI' ] = LinkReplacer.lnk2span ( row [ 'ESTREMI' ] );

		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) 
			s = String.formatDict (  modules.home.templates [ 'last_news_' + row [ "TIPO" ] ], row );
		else 
			s = String.formatDict (  modules.home.templates [ 'last_news_' + row [ "TIPO" ] + '_nologged' ], row );

		site.smooth_roll.add_item ( s );
	}

	/*
	if ( l > 0 ) s = String.formatDict ( modules.home.templates [ 'last_news_cnt' ], { txt: s, _now: str_now } );
	else $ ( 'block_main_body_last_news' ).style.display = 'none';

	$ ( 'block_main_body_last_news' ).innerHTML = s;

	LinkReplacer.replace ( modules.doc._link_replace );
	*/

	$( 'last_news_top_date' ).innerHTML = str_now;
	
	modules.home._set_adnk_top ();

	if ( l > 0 )
	{
		site.smooth_roll.init ();
		site.smooth_roll.start ();
	}
	else $ ( 'block_main_body_last_news' ).style.display = 'none';
};
//}}}
//{{{ _fill_adnk ()
modules.home._fill_adnk = function ()
{
	var fq = new FulQuery ();

	fq.set_fields ( 'ID', 'TITOLO', 'DATA', "COD_OPERA" );
	//fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'S' );
	//fq.add ( 'FLAG_PRIMOPIANO', 'EQUAL', 'S' );
	fq.add ( 'TIPO', 'EQUAL', '75' );
	fq.add ( 'FULTIPO', 'EQUAL', '5' );

	fq.set_id ();
	fq.order_by = "DATA DESC";
	fq.lines = 1;

	fq.db_name = "QUOTYI0QU";
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	kernel.fulquery ( fq, function ( v ) {
		if ( ! v [ 'rows' ] ) 
		{
			$ ( 'block_main_body_adnk' ).style.display = 'none';
		}
		else
		{
			var data = v [ 'row0' ] [ 'DATA' ];
			site._areas.iterate ( function ( v, k ) {
				if ( k == "prpag" ) return;

				fq.add ( 'DATA', 'EQUAL', data );
				fq.add ( "COD_OPERA", "EQUAL", k );

				fq.lines = 99999;

				kernel.fulquery ( fq, function ( v1 ) {
					modules.home._format_adnk ( v1, 'tab_' + k );
				} );
			});

		}
	});
};
//}}}
//{{{ _format_adnk ( v, dest_tab )
modules.home._format_adnk = function ( v, dest_tab )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var title_lim = 110;

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;

		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;

		if ( row [ 'TITOLO' ] && ( row [ 'TITOLO' ].length > title_lim ) ) row [ 'TITOLO' ] = row [ 'TITOLO' ].substr ( 0, title_lim ) + '...';

		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) s += String.formatDict ( modules.home.templates [ 'adnk_antepr_row' ], row );
		else s += String.formatDict ( modules.home.templates [ 'adnk_antepr_row_nologged' ], row );
	}

	if ( l > 0 )
	{
		//$ ( 'block_main_body_adnk' ).innerHTML = modules.home.templates [ 'adnk_antepr' ];
		//$ ( 'adnk_body' ).innerHTML = s;
		$ ( dest_tab ).innerHTML = s;
	}
	else 
	{
		$ ( dest_tab ).innerHTML = '';
		//$ ( 'block_main_body_adnk' ).style.display = 'none';
	}

	modules.home._set_adnk_top ();
};
//}}}

modules.home._set_adnk_top = function ()
{
	return;
	var rbarh = $ ( 'right_bar_site' ).offsetTop + $ ( 'right_bar_site' ).offsetHeight;
	var spacerh = $ ( 'adnk_spacer' ).offsetTop;

	$ ( 'adnk_spacer' ).style.height = Math.abs ( spacerh - rbarh ) + 'px';
};
//{{{ _fill_rassegna_stampa ()
modules.home._fill_rassegna_stampa = function ()
{
	var fq = new FulQuery ();
	var d = new Date ();

	fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'FILE_NAME', 'COD_OPERA', 'ORD_AREA' );
	//fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'S' );
	//fq.add ( 'FLAG_PRIMOPIANO', 'EQUAL', 'S' );

	//FIXME: quando online decommentare per le news del giorno
	//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

	fq.add ( 'TIPO', 'EQUAL', '34' );
	fq.add ( 'FULTIPO', 'EQUAL', '5' );
	fq.set_id ();
	fq.order_by = "DATA DESC";
	fq.lines = 1;

	fq.db_name = "QUOTYI0QU";
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	$ ( 'block_main_body_rass_stampa' ).innerHTML = modules.home.templates [ 'progress' ];
	$ ( 'block_main_body_rass_stampa' ).style.display = 'block';

	kernel.fulquery ( fq, function ( v ) {
		if ( ! v [ 'rows' ] ) $ ( 'block_main_body_rass_stampa' ).style.display = 'none';
		else
		{
			var data = v [ 'row0' ] [ 'DATA' ];
			//data = data.split ( "-" );
			fq.add ( 'DATA', 'EQUAL', data );
			fq.lines = 99999;
			fq.order_by = 'ORD_AREA';

			kernel.fulquery ( fq, function ( v1 ) {
				modules.home._format_rassegna_stampa ( v1 );
			} );
		}
	});
};
//}}}
//{{{ _format_rassegna_stampa ( v )
modules.home._format_rassegna_stampa = function ( v )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var templ_row = modules.home.templates [ 'rass_stampa_row' ];
	var templ_row_nologged = modules.home.templates [ 'rass_stampa_row_nologged' ];
	var d = new Date ();

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;

		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;
		row [ '_area' ] = "";
		var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
		if ( area_name ) row [ '_area' ] = area_name + ' | ';


		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) s += String.formatDict ( templ_row, row );
		else s += String.formatDict ( templ_row_nologged, row );
	}

	if ( l > 0 ) 
	{
		var lnk_pdf = '';
		lnk_pdf = String.formatDict ( modules.home.templates [ 'lnk_create_rass_stampa' ], { 
			_year: d.getFullYear(), 
			_month: d.getMonth () + 1, 
			_day: d.getDate () 
		} );

		s = String.formatDict ( modules.home.templates [ 'rass_stampa' ], { txt: s, _txt_create_pdf: lnk_pdf } );

		if ( site.user_check_opera ( "I0QU" ) ) s += modules.home.templates [ 'lnk_lst_rass_stampa' ];
		else s += modules.home.templates [ 'lnk_lst_rass_stampa_nologged' ];

		$ ( 'block_main_body_rass_stampa' ).innerHTML = s;
	}
	else $ ( 'block_main_body_rass_stampa' ).style.display = 'none';
};
//}}}
//{{{ create_rass_stampa ()
modules.home.create_rass_stampa = function ()
{
	alert ( 'Genero PDF' );
};
//}}}
//{{{ _fill_primo_piano ( cback )
modules.home._fill_primo_piano = function ( cback )
{
	var fq = new FulQuery ();

	fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'AUTORE', 'OCCHIELLO', 'TIPO', 'ESTREMI', 'COD_OPERA', 'ORA' );

	fq.add ( 'TIPO', 'IN_NUM', '92|86' );
	fq.lines = 3;

	if ( modules.home._cur_opera && modules.home._cur_opera != "prpag" )
	{
		fq.add ( "COD_OPERA", "EQUAL", modules.home._cur_opera );
		fq.add ( 'FLAG_PRIMOPIANO', 'EQUAL', 'S' );
		//FIXME: quando online decommentare per le news del giorno
		fq.lines = 1;
	}
	else
	{
		fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'S' );
		var d = new Date ();
		//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );
	}

	fq.set_id ();
	fq.order_by = "DATA DESC, ORA DESC";

	fq.db_name = "QUOTYI0QU";
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	$ ( 'block_main_body_news' ).innerHTML = modules.home.templates [ 'progress' ];

	kernel.fulquery ( fq, function ( v ) { modules.home._format_primo_piano ( v, cback ); } );
};
//}}}
//{{{ _format_primo_piano ( v, cback )
modules.home._format_primo_piano = function ( v, cback )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var templ_row = modules.home.templates [ 'news_primop_row' ];
	var templ_row_nologged = modules.home.templates [ 'news_primop_row_nologged' ];

	var ids = [];

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;

		row [ '_news_img' ] = '';
		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;

		if ( row [ 'ESTREMI' ] ) row [ 'ESTREMI' ] = LinkReplacer.lnk2span ( row [ 'ESTREMI' ] );

		row [ '_area_name' ] = '';
		row [ '_sep' ] = '';

		if ( modules.home._cur_opera && modules.home._cur_opera == "prpag" )
		{
			var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
			if ( area_name )
			{
				row [ '_area_name' ] = area_name;
				row [ '_sep' ] = ' | ';
			}

			if ( t == 0 ) row [ '_news_img' ] = modules.home.templates [ 'news_img_home' ];
		}

		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) s += String.formatDict ( templ_row, row );
		else s += String.formatDict ( templ_row_nologged, row );

		ids.push ( row [ 'ID' ] );
	}

	if ( l > 0 )
	{
		s = String.formatDict ( modules.home.templates [ 'news_primop' ], { txt: s } );
		$ ( 'block_main_body_news' ).style.visibility = 'visible';
	}
	else $ ( 'block_main_body_news' ).style.visibility = 'hidden';

	$ ( 'block_main_body_news' ).innerHTML = s;

	LinkReplacer.replace ( modules.doc._link_replace );

	site.get_corrs ( ids, [ '78', '80', '81' ], modules.home._render_corrs );

	if ( cback ) cback ( ids );
};
//}}}
//{{{ _fill_home_area_news ( area, ids )
modules.home._fill_home_area_news = function ( area, ids )
{
	var fq = new FulQuery ();
	var d = new Date ();

	fq.set_fields ( 'ID', 'DATA', 'TITOLO', 'ABSTRACT', 'AUTORE', 'OCCHIELLO', 'TIPO', 'ESTREMI', 'COD_OPERA', 'ORA' );
	fq.add ( 'TIPO', 'IN_NUM', '92|86' );
	fq.add ( "COD_OPERA", "EQUAL", modules.home._cur_opera );
	//fq.add_date ( d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), d.getFullYear(), ( d.getMonth() + 1 ), d.getDate(), 'DATA' );

	ids = ids.join ( "|" );
	if ( ids ) fq.add ( "ID", "NOT_IN_STR", ids );

	/*
	if ( modules.home._cur_opera && modules.home._cur_opera != "prpag" )
	{
		fq.add ( 'FLAG_PRIMOPIANO', 'EQUAL', 'N' );
	}
	else
	{
		fq.add ( 'FLAG_ANTEPRIMA', 'EQUAL', 'N' );
	}
	*/

	fq.set_id ();
	fq.order_by = "DATA DESC, ORA DESC";
	fq.lines = 9;

	fq.db_name = "QUOTYI0QU";
	fq.mode = 'QUERY';
	fq.opera = 'I0QU';

	$ ( 'block_main_body_area_news_sx' ).innerHTML = modules.home.templates [ 'progress' ];
	$ ( 'block_main_body_area_news_dx' ).innerHTML = modules.home.templates [ 'progress' ];

	kernel.fulquery ( fq, modules.home._format_home_area_news );
};
//}}}
//{{{ _format_home_area_news ( v )
modules.home._format_home_area_news = function ( v )
{
	var t, l = v [ 'rows' ];//( v [ 'rows' ] > 7 ? 7 : v [ 'rows' ] );
	var row;
	var s = '';
	var templ_row = modules.home.templates [ 'home_news_area_row' ];
	var sx = "";
	var dx = "";
	var ids = [];

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row ) continue;

		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;

		if ( row [ 'ESTREMI' ] ) row [ 'ESTREMI' ] = LinkReplacer.lnk2span ( row [ 'ESTREMI' ] );

		row [ '_area_name' ] = '';
		row [ '_sep' ] = '';
		row [ '_news_img' ] = '';

		if ( modules.home._cur_opera && modules.home._cur_opera == "prpag" )
		{
			var area_name = site.get_short_areaname ( row [ "COD_OPERA" ] );
			if ( area_name )
			{
				row [ '_area_name' ] = area_name;
				row [ '_sep' ] = ' | ';
			}
		}


		if ( ! site.user_check_opera ( row [ "COD_OPERA" ] ) ) templ_row = modules.home.templates [ 'home_news_area_row_nologged' ];
		else templ_row = modules.home.templates [ 'home_news_area_row' ];

		if ( t < 4 ) sx += String.formatDict ( templ_row, row );
		else dx += String.formatDict ( templ_row, row );

		ids.push ( row [ 'ID' ] ) ;
	}

	$ ( 'block_main_body_area_news_sx' ).innerHTML = sx;
	$ ( 'block_main_body_area_news_dx' ).innerHTML = dx;

	LinkReplacer.replace ( modules.doc._link_replace );
	
	site.get_corrs ( ids, [ '78', '80', '81' ], modules.home._render_corrs );
};
//}}}
//{{{ _create_page ( dict )
modules.home._create_page = function ( dict )
{
	if ( ! dict.get ( 'page' ) ) return;

	var page = dict.get ( 'page' );

	var frame = dict.get ( 'frame' );
	var s = '';

	if ( frame )
	{
		$ ( 'static_cnt' ).innerHTML = String.formatDict ( modules.home.templates [ 'frame' ], { url: frame } );
	}
	else
	{
		if ( modules.home._static_page [ page ] ) $ ( 'static_cnt' ).innerHTML = modules.home._static_page [ page ];
		else
		{
			$ ( 'static_cnt' ).innerHTML = site.templates [ 'progress' ];
			utils.get_file ( '/static/' + page + '.htm', function ( v ) {
				$ ( 'static_cnt' ).innerHTML = v + modules.home.templates [ 'back2history' ];
				modules.home._static_page [ page ] = v + modules.home.templates [ 'back2history' ];
			} );
		}
		
	}

	switch ( page )
	{
		case "autori":
			s = '<b>I</b> <b>n</b>ostri <b>A</b>utori';
			break;
		case "contatta":
			s = '<b>L</b>a <b>R</b>edazione';
			break;
		case "help":
			s = '<b>H</b>elp';
			break;
		case "newsletter":
			s = '<b>N</b>ewsletter';
			break;
		case "eventi":
			s = '<b>B</b>ox <b>E</b>venti';
			break;
		case "GU":
			s = '<b>G</b>azzetta <b>U</b>fficiale';
			break;
		case "SCAD":
			s = '<b>S</b>cadenzario';
			break;
	}

	$ ( 'block_main_top_pag' ).innerHTML = s;
	$ ( 'block_main_top_data' ).style.display = 'none';
};
//}}}
//{{{ ds_back2home ( area, search_mask )
modules.home.ds_back2home = function ( area, search_mask )
{
	site.set_area_tabs();
	var dct = {};
	dct [ 'area' ] = area;
	if ( search_mask ) dct [ 'search_form' ] = search_mask;

	kernel.go( 'home', dct );
};
//}}}
//{{{ _render_corrs ( v )
modules.home._render_corrs = function ( v )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var cnt_corr;
	var templ = '';

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row || ! row [ 'TIPO_RIF' ] || ! row [ 'KEY_RIF' ] ) continue;

		cnt_corr = null;
		templ = null;


		var append = '_nologged';

		row [ "COD_OPERA" ] = row [ 'KEY_RIF' ].substr ( 0, 4 );
		if ( site.user_check_opera ( row [ "COD_OPERA" ] ) ) append = '';

		switch ( row [ 'TIPO_RIF' ] )
		{
			case "78":
				cnt_corr = $ ( 'view_comm_' + row [ 'KEY_DOC' ] );
				row [ '_txt' ] = 'Leggi il commento';
				templ = modules.home.templates [ 'lnk_view_comm' + append ];
				break;

			/*
			case "80":
				cnt_corr = $ ( 'view_tabell_' + row [ 'KEY_DOC' ] );
				row [ '_txt' ] = 'Leggi la tabella';
				templ = modules.home.templates [ 'lnk_view_tabell' + append ];
				break;
			*/

			case "81":
				cnt_corr = $ ( 'view_ccnl_' + row [ 'KEY_DOC' ] );
				row [ '_txt' ] = 'Leggi la sintesi del rinnovo';
				templ = modules.home.templates [ 'lnk_view_ccnl' + append ];
				break;
		}

		if ( ! cnt_corr ) continue;

		row [ '_cur_area' ] = modules.home._cur_area;
		row [ '_search_form' ] = modules.home._cur_search_mask;
		
		cnt_corr.innerHTML = String.formatDict ( templ, row );
	}
};
//}}}


modules.home.templates = {};

var self = modules.home.templates;

self [ 'progress' ] = '<div class="progress_div">&nbsp;</div>';

self [ 'top_pag' ] = '<b>%(first_c)s</b>%(first)s <b>%(second_c)s</b>%(second)s'; 
self [ 'top_data' ] = '<b>%(day)s</b> %(month)s <b>%(year)s</b>'; 

self [ 'news_primop' ] = 	'<div class="title">News in primo piano</div>' +
				'<div class="body">' +
				'	<div class="main_box">%(txt)s</div>' +
				'</div>';

self [ 'news_img_home' ] = '<img src="/static/home_imgs/news_home.jpg" border="0" width="180" alt="" title="" />';

self [ 'news_primop_row' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<table><tr>' +
				'	<td valign="top">%(_news_img)s</td>' +
				'	<td valign="top"><div class="txt"><span class="abs_area">%(_area_name)s</span> %(_sep)s %(ABSTRACT)s</div></td>' +
				'</tr></table>' +
				'<div class="txt">%(ESTREMI)s</div>' +
				'<div class="view_comm" id="view_comm_%(ID)s"></div>' +
				'<div class="view_ccnl" id="view_ccnl_%(ID)s"></div>';
				//'<div class="view_ccnl" id="view_tabell_%(ID)s"></div>';

self [ 'news_primop_row_nologged' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<table><tr>' +
				'	<td valign="top">%(_news_img)s</td>' +
				'	<td valign="top"><div class="txt" ><span class="abs_area">%(_area_name)s</span> %(_sep)s %(ABSTRACT)s</div></td>' +
				'</tr></table>' +
				'<div class="txt" >%(ESTREMI)s</div>' +
				'<div class="view_comm" id="view_comm_%(ID)s"></div>' +
				'<div class="view_ccnl" id="view_ccnl_%(ID)s"></div>';
				//'<div class="view_ccnl" id="view_tabell_%(ID)s"></div>';

self [ 'home_news_area_row' ] = '<div class="main_box">' + self [ 'news_primop_row' ] + '</div>';
self [ 'home_news_area_row_nologged' ] = '<div class="main_box">' + self [ 'news_primop_row_nologged' ] + '</div>';

self [ 'rass_stampa' ] = 	'<div class="title">La rassegna stampa ' +
				'	<span class="lnk_get_rass_stampa">%(_txt_create_pdf)s</span>' +
				'	<span class="rass_stampa_autore">a cura di Saverio Cinieri</span>' +
				'</div>' +
				'<div class="body">' +
				'	<div class="main_box" style="height: 140px; overflow: auto;" >%(txt)s</div>' +
				'</div>';

//self [ 'lnk_create_rass_stampa' ] = '<a href="javascript:modules.home.create_rass_stampa()">Preleva la rassegna</a>';
self [ 'lnk_create_rass_stampa' ] = '';//'<a href="/archivio/home_file/rassegna.pdf">Preleva la rassegna</a>';

//self [ 'rass_stampa_row' ] = 	'<div class="titolo"><a href="%(FILE_NAME)s">%(TITOLO)s</a></div>';
self [ 'rass_stampa_row' ] = 	'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})"><span class="abs_area">%(_area)s</span> %(TITOLO)s</a></div>';
self [ 'rass_stampa_row_nologged' ] = 	'<div class="titolo"><a href="javascript:site.nologged(\'%(_cur_area)s\')"><span class="abs_area">%(_area)s</span> %(TITOLO)s</a></div>';

self [ 'lnk_lst_rass_stampa' ] = '<div class="lnk_rass_stampa"><a href="javascript:modules.home.list_rass_stampa()">Tutta la rassegna</a></div>';
self [ 'lnk_lst_rass_stampa_nologged' ] = '<div class="lnk_rass_stampa"><a href="javascript:site.nologged(\'area_prpag\')">Tutta la rassegna</a></div>';

self [ 'tbar_rass_stampa' ] = 	'<div id="toolbar_rass_stampa" class="toolbar" style="display: none;">' +
				'	<div class="tbar_sx"></div>' +
				'	<div id="toolbar_rass_stampa_body" class="tbar"></div>' +
				'	<div class="tbar_dx"></div>' +
				'</div>';

self [ 'cnt_rass_stampa' ] = 	'<div id="cnt_lst_rass_stampa"></div>' +
				self [ 'tbar_rass_stampa' ];

self [ 'lst_rass_stampa_row' ] = 	'<div class="doc_txt">' +
					'<span style="color: black; font-weight: bold; margin-left: -5px;">%(_area_name)s</span> ' +
					'%(DOCUMENT_TEXT)s' +
					'</div>';
					/*'<div class="titolo">' +
					'	<a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">' +
					'		<span style="color: red;">%(_area_name)s</span> %(TITOLO)s' +
					'	</a>' +
					'</div>';*/

self [ 'lst_rass_stampa_row_nologged' ] = '<div class="doc_txt">' +
					'<span style="color: black; font-weight: bold; margin-left: -5px;">%(_area_name)s</span> ' +
					'%(DOCUMENT_TEXT)s' +
					'</div>';
					//'<div class="titolo"><a href="javascript:site.nologged(\'%(_cur_area)s\')"><span style="color: red;">%(_area_name)s</span> %(TITOLO)s</a></div>';

self [ 'rass_stampa_cnt' ] = 	'<div class="rass_stampa_cnt_body">' +
				'	<div class="main_box">%(txt)s</div>' +
				'</div>';



self [ 'adnk_antepr' ] = 	'<div class="adnk_logo"></div>' +
				'<div id="adnk_header">' +
				'	FISCO | DIRITTO | LAVORO | BILANCIO | ECONOMIA | P.A.' +
				'</div>  ' +
				'<div id="adnk_body"></div>';

//self [ 'adnk_antepr_row' ] = 	'<div class="titolo"><a href="javascript:kernel.go(\'home\',{mask:\'adnk\',id:\'%(ID)s\'})">%(TITOLO)s</a></div>';
self [ 'adnk_antepr_row' ] = 	'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>';

self [ 'adnk_antepr_row_nologged' ] = 	'<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>';

self [ 'last_news_cnt' ] = 	'<div style="width: 100%; background-color: #85B81F; overflow: auto;">' +
				'	<div class="title">Le ultime News</div>' +
				'	<div class="top_date">%(_now)s</div>' +
				'</div>' +
				'<div class="body">' +
				'	<div id="last_news_smooth_roll_render" class="main_box"></div>' +
				'</div>';

self [ 'last_news_86' ] = 	'<div class="last_news_header">%(ORA)s %(_area_name)s %(OCCHIELLO)s</div>' +
				'<div class="titolo">' +
				'	<a id="%(ID)s" href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a>' +
				'<\/div>' +
				'<div class="txt_hide" style="display: none;">%(ABSTRACT)s</div>';

self [ 'last_news_92' ] = self [ 'last_news_86' ];

self [ 'last_news_86_nologged' ] = 	'<div class="last_news_header">%(ORA)s %(_area_name)s %(OCCHIELLO)s</div>' +
					'<div class="titolo">' +
					'	<a id="%(ID)s" href="javascript:site.nologged(\'%(COD_OPERA)s\');">%(TITOLO)s<\/a>' +
					'<\/div>' +
					'<div class="txt_hide" style="display: none;">%(ABSTRACT)s</div>';

self [ 'last_news_92_nologged' ] = self [ 'last_news_86_nologged' ];

self [ 'today_comm_header' ] = '<div class="title">I Commenti</div>';

self [ 'last7_comm' ] = '<div class="last_list">' +
			'<img src="gfx/icon_commen.gif" border="0" alt="commenti della settimana" title="commenti della settimana" onclick="kernel.go(\'home\',{mask:\'last7comm\',area:\'%(area)s\'})" style="cursor: pointer;"/> ' +
			'<a href="javascript:kernel.go(\'home\',{mask:\'last7comm\',area:\'%(area)s\'})">' +
			'Leggi gli altri commenti</a>' +
			'</div>';

self [ 'today_comm_cnt' ] = 	'<div class="body">' +
				'	<div class="main_box">%(txt)s</div>' +
				'</div>';

self [ 'today_comm_row' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<div class="txt"><span class="abs_area">%(_area_name)s</span> %(_sep)s %(ABSTRACT)s</div>' +
				'<div class="estremi">%(ESTREMI)s</div>';

self [ 'today_comm_row_nologged' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<div class="txt"><span class="abs_area">%(_area_name)s</span> %(_sep)s %(ABSTRACT)s</div>' +
				'<div class="estremi">%(ESTREMI)s</div>';

self [ 'today_list_comm_row' ] = 	'<div class="arg_doc%(_cls_tipo)s">%(OCCHIELLO)s</div>' +
				'<div class="titolo_doc%(_cls_tipo)s"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<div class="txt_black">%(ABSTRACT)s</div>' +
				'<div class="autore">%(ESTREMI)s</div>';

self [ 'today_list_comm_row_nologged' ] = 	'<div class="arg_doc%(_cls_tipo)s">%(OCCHIELLO)s</div>' +
				'<div class="titolo_doc%(_cls_tipo)s"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>' +
				'<div class="txt_black">%(ABSTRACT)s</div>' +
				'<div class="autore">%(ESTREMI)s</div>';

self [ 'commr_vista_cnt' ] = 	'<div class="body2">' +
				'       <div class="main_box">%(txt)s</div>' +
				'</div>';

self [ 'commr_vista_row' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>';

self [ 'commr_vista_row_nologged' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
				'<div class="autore">%(AUTORE)s</div>';

self [ 'dat_tabel_cnt' ] = self [ 'commr_vista_cnt' ];

self [ 'dat_tabel_row' ] = '<div class="titolo_datitab"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>';

self [ 'dat_tabel_row_nologged' ] = '<div class="titolo_datitab"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>';

self [ 'rinn_ccnl_cnt' ] = self [ 'commr_vista_cnt' ];

self [ 'rinn_ccnl_row' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="txt_black">%(ABSTRACT)s</div>';

self [ 'rinn_ccnl_row_nologged' ] = 	'<div class="arg">%(OCCHIELLO)s</div>' +
				'<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
				'<div class="txt_black">%(ABSTRACT)s</div>';

self [ 'oss_giurisp_cnt' ] = self [ 'commr_vista_cnt' ];

self [ 'oss_giurisp_row' ] = 	'<div class="titolo"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'<div class="txt_black" style="margin-bottom: 15px;">%(ABSTRACT)s</div>';

self [ 'oss_giurisp_row_nologged' ] =  '<div class="titolo"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
					'<div class="txt_black" style="margin-bottom: 15px;">%(ABSTRACT)s</div>';

self [ 'oss_giurisp_row2' ] = 	'<div class="occhiello" style="font-weight: bold;">%(OCCHIELLO)s</div>' +
				'<div class="titolo_doc_comm"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
				'%(_txt)s';

self [ 'oss_giurisp_row2_nologged' ] =  '<div class="occhiello">%(OCCHIELLO)s</div>' +
					'<div class="titolo_doc_comm"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
					'%(_txt)s';

self [ 'today_last7_comm_row' ] = 	'<div class="arg_doc%(_cls_tipo)s">%(OCCHIELLO)s</div>' +
					'<div class="titolo_doc%(_cls_tipo)s"><a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(TITOLO)s</a></div>' +
					'<div class="autore">%(AUTORE)s</div>' +
					'<div class="txt_black">%(ABSTRACT)s</div>' +
					'<div class="autore">%(ESTREMI)s</div>';

self [ 'today_last7_comm_row_nologged' ] = 	'<div class="arg_doc%(_cls_tipo)s">%(OCCHIELLO)s</div>' +
					'<div class="titolo_doc%(_cls_tipo)s"><a href="javascript:site.nologged(\'%(COD_OPERA)s\')">%(TITOLO)s</a></div>' +
					'<div class="autore">%(AUTORE)s</div>' +
					'<div class="txt_black">%(ABSTRACT)s</div>' +
					'<div class="autore">%(ESTREMI)s</div>';

self [ 'right_bar_box' ] = 	'<div class="title">:: Sezioni di Area</div>' +
				'<div id="rightbar_box_body" class="body"></div>';

self [ 'right_bar_box_item' ] = '<div class="item" onclick="%(func)s">:: %(lbl)s</div>';

self [ 'ds_table_start' ] = 	'<table border="0" cellpadding="0" cellspacing="0" class="tab_res" width="98%">' +
				'	<tr class="throw" style="border: 1px solid blue;">' +
				'		<th>Tipo</th>' +
				'		<th>Titolo</th>' +
				'		<th>Area/Data</th>' +
				'		<th>Autore</th>' +
				'	</tr>';
self [ 'ds_table_header' ] = '';
self [ 'ds_table_end' ] = '</table>';

self [ 'print_template' ] = 	'	<td valign="top">%(_descr_tipo)s</td>' +
				'	<td valign="top"><a href="%(func)s">' +
				'       %(_titolo)s</a></td>' +
				'	<td valign="top">%(_area)s<br />%(_data)s</td>' +
				'	<td valign="top">%(COGNOME_AUTORE)s</td>';

self [ 'ds_table_row' ] = 	'<tr class="row">' + 
					self [ 'print_template' ] +
				'</tr>';

self [ 'ds_table_row_func' ] = 'javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(ID)s\',pos:%(_pos)s,area:\'%(_cur_area)s\',ds_name:\'%(_ds_name)s\'%(_highlight)s %(_search_form)s})';

self [ 'ds_table_row_func_nologged' ] = 'javascript:site.nologged(\'%(COD_OPERA)s\')';

self [ 'ds_prev_page' ] = '<a href="%(_prev_page)s">&lt;&lt;</a>';
self [ 'ds_next_page' ] = '<a href="%(_next_page)s">&gt;&gt;</a>';
self [ 'ds_table_footer' ] = '';

self [ 'cnt_results_tree' ] = 	'<div class="title">Filtra per materia</div>' +
				'<div id="tree_body_results_%(name)s" >&nbsp;</div>';

self [ 'cnt_navi' ] = 	'<div id="navi_tot_%(name)s">&nbsp;</div>' +
			'<div id="navi_page_%(name)s">&nbsp;</div>' +
			'<div id="results_navi_body_%(name)s">&nbsp;</div>';

self [ 'cnts_results' ] = 	'<div id="results_top_%(name)s"></div>' +
				'<div id="results_tree_%(name)s">' + self [ 'cnt_results_tree' ] + '</div>' +
				'<div id="results_body_%(name)s">&nbsp;</div>' +
				'<div id="results_navi_%(name)s">' + self [ 'cnt_navi' ] + '</div>';

//self [ 'ds2areahome' ] = '<div class="ds_back2home"><a href="javascript:modules.home.ds_back2home(\'area_%(name)s\')">Torna alla Home Page - %(home)s</div>';
self [ 'ds2areahome' ] = '<div class="ds_back2home"><a href="javascript:modules.home.ds_back2home(\'%(name)s\')">Torna alla home</div>';

self [ 'cnt_result_ds' ] = 	'<div id="cnt_results_%(name)s" style="display: none;" class="cnt_results">' +
				'	<div id="results_top_%(name)s" class="results_top">' +
				'	</div>' +
				'	<div id="results_tree_%(name)s" class="results_tree">' + 
						self [ 'cnt_results_tree' ] +
				'	</div>' +
				'	<div id="results_body_%(name)s" class="results_body"></div>' +
				'	<div id="results_navi_%(name)s" class="results_navi">' + 
				'		<div id="navi_tot_%(name)s" class="navi_tot"></div>' +
				'		<div id="navi_page_%(name)s" class="navi_page"></div>' +
				'		<div id="results_navi_body_%(name)s" class="results_navi_body"></div>' +
				'	</div>' +
				'</div>';

self [ 'toolbar' ] =	'<div id="toolbar" class="toolbar" style="display: none;">' +
			'	<div class="tbar_sx"></div>' +
			'	<div id="toolbar_body" class="tbar"></div>' +
			'	<div class="tbar_dx"></div>' +
			'</div>';

self [ 'no_res' ] = '<div class="nores">Nessun Risultato</div>';

self [ 'back2results' ] = '<div class="goback"><a href="javascript:site.show_global_divs(\'search\')">Torna ai risultati</a></div>';

self [ 'back2history' ] = '<div class="goback"><a href="javascript:history.go(-1)">Indietro</a></div>';

self [ 'doc' ] = 	'<div id="cnt_doc" class="cnt_doc">' +
			'	<div class="doc_header">' +
			//'		<div class="doc_tipo">%(DESCR_TIPO)s</div>' +
			//'		<div class="doc_data">%(_data)s</div>' +
			'	</div>' +
			'	<div class="doc_txt">%(_text)s</div>' +
			'		%(_back2res)s ' +
			'	<div id="doc_navi" class="doc_navi"></div>' +
			'</div>';

self [ 'prev_doc' ] = '<div class="doc_navi_prev">&lt;&lt; <a href="%(_prev_doc)s"><i>Risultato precedente<\/i><\/a></div>';

self [ 'next_doc' ] = '<div class="doc_navi_next"><a href="%(_next_doc)s"><i>Risultato successivo<\/i><\/a> &gt;&gt;</div>';

self [ 'adnk_tabs' ] = 	'  <div class="tab" id="RES_fisco"><\/div>' +
			'  <div class="tab" id="RES_diritto"><\/div>' +
			'  <div class="tab" id="RES_bilancio"><\/div>' +
			'  <div class="tab" id="RES_lavoro"><\/div>' +
			'  <div class="tab" id="RES_economia"><\/div>';

self [ 'cnt_adnk_tab_results' ] =	'<div class="os3tabs_header" id="main_header">&nbsp;<\/div>' +
				'       <div id="result_top" style="display:none;"><\/div>' +
				'       <div class="os3tabs_body" id="main_body">' +
				'	<\/div>' +
				'       <div id="result_bottom" style="display:none;"><\/div>' +
				'<\/div>';

self [ 'datitab_start' ] = 	'<div id="%(_code)s" class="datitab">' + 
				'	<div class="tit_datitab">%(_descr_datitab)s</div>';

self [ 'frame' ] = '<iframe src="%(url)s" frameborder="0" style="width: 100%; height: 700px;" ></iframe>';

self [ 'lnk_view_comm' ] = '<a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',id:\'%(KEY_RIF)s\',area:\'%(_cur_area)s\',search_form:\'%(_search_form)s\'})">%(_txt)s</a>';

self [ 'lnk_view_ccnl' ] = self [ 'lnk_view_comm' ];
self [ 'lnk_view_tabell' ] = self [ 'lnk_view_comm' ];

self [ 'lnk_view_comm_nologged' ] = '<a href="javascript:site.nologged(\'%(_cur_area)s\')">%(_txt)s</a>';
self [ 'lnk_view_ccnl_nologged' ] = self [ 'lnk_view_comm_nologged' ];
self [ 'lnk_view_tabell_nologged' ] = self [ 'lnk_view_comm_nologged' ];

self [ 'print_lists' ] = 	'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' +
				'  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' +
				'<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">' +
				'<head><title>Quotidiano Unico %(_title)s</title>' +
				'	<link rel="stylesheet" type="text/css" href="/css/print.css"/>' +
				'</head><body>%(_content)s' +
				'<div style="margin: auto; text-align: center; border-top: 0px !important;" class="copy">' +
				'Copyright &copy; 2008 Wolters Kluwer Italia - P.I. 10209790152<br/>' +
				'Sviluppato da <a target="_blank" href="http://www.os3.it">OS3 srl</a></div>' +
				'</body></html>';

self [ 'page2print' ] = '<table border="0" cellpadding="0" cellspacing="3">' +
			'	<tr>' +
			'		<td colspan="2" align="center">Si possono stampare %(limit_page)s pagine</td>' +
			'	</tr>' +
			'	<tr>' +
			'		<td>Da pagina</td><td><input type="text" id="from_page" size="4" maxlength="6" value="1" /></td>' +
			'	</tr>' +
			'	<tr>' +
			'		<td>a pagina</td><td><input type="text" id="to_page" size="4" maxlength="6" value="" /></td>' +
			'	</tr>' +
			'	<tr>' +
			'		<td>&nbsp;</td><td><button onclick="modules.home.get_page2print()">Stampa</button></td>' +
			'	</tr>' +
			'</table>';

self [ 'quot_arch_view_month' ] = '<a href="javascript:kernel.go(\'home\',{mask:\'arch_quot_month\',year:%(year)d,month:%(month)d,area:\'%(area)s\'})">%(txt)s</a>';
self [ 'rass_arch_view_month' ] = '<a href="javascript:kernel.go(\'home\',{mask:\'rass_quot_month\',year:%(year)d,month:%(month)d})">%(txt)s</a>';

//self [ 'list_arch_row' ] = '<div class="quoty_arch_file"><a href="/archivio/%(fpath)s">%(day)s %(monthname)s %(year)s</a></div>';
self [ 'list_arch_row' ] = '<div class="quoty_arch_file"><a href="%(fpath)s">%(day)s %(monthname)s %(year)s</a></div>';

self [ 'cnt_quoty_arch' ] = '<div id="cnt_quoty_arch_%(name)s" class="cnt_quoty_arch" style="display: none;">' + self [ 'progress' ] + '</div>';

self [ 'quoty_arch_month_cnt' ] = 	'<div id="%(year)s_%(month)s">' +
					'	<div id="header_%(year)s%(month)s" ><div class="quoty_arch_month"><a href="javascript:modules.home.get_quoty_arch_file_list(\'%(type)s\',\'%(year)s\',\'%(opera)s\',\'%(month)s\')"">%(txt)s</a></div></div>' +
					'	<div id="cnt_files_%(year)s_%(month)s">' +
					'	</div>' +
					'</div>';

self [ 'rass_arch_year_cnt' ] = 	'<div id="cnt_%(year)s">' +
					'	<div id="header_years" ><div class="quoty_arch_year"><a href="javascript:modules.home.get_rass_arch_month_list(\'%(year)s\',\'%(opera)s\')">%(txt)s</a></div></div>' +
					'	<div id="cnt_%(year)s_months">' +
					'	</div>' +
					'</div>';

self [ 'quoty_arch_year_cnt' ] = 	'<div id="cnt_%(year)s">' +
					'	<div id="header_years" ><div class="quoty_arch_year"><a href="javascript:modules.home.get_quoty_arch_month_list(\'%(year)s\',\'%(opera)s\')">%(txt)s</a></div></div>' +
					'	<div id="cnt_%(year)s_months">' +
					'	</div>' +
					'</div>';

self [ 'quoty_arch_container' ] = 	'<div id="container_years">' +
					'	<div id="header_years" ></div>' +
					'	<div id="cnt_years">' +
							self [ 'progress' ] +
					'	</div>' +
					'</div>';

self [ 'quoty_arch_cnt_cols' ]  = 	'<div id="header_quoty_arch"></div>' +
					'<div id="cnt_quoty_arch">' +
					'	<div id="col_years">' + self [ 'progress' ] + '</div>' +
					'	<div id="col_months"></div>' +
					'	<div id="col_files"></div>' +
					'</div>';

self [ 'quoty_arch_year_row' ] = '<div class="quoty_arch_year"><a href="javascript:modules.home.get_quoty_arch_month_list(\'%(year)s\',\'%(opera)s\')">%(txt)s</a></div>';
self [ 'rass_arch_year_row' ] = '<div class="quoty_arch_year"><a href="javascript:modules.home.get_rass_arch_month_list(\'%(year)s\')">%(txt)s</a></div>';

self [ 'quoty_arch_month_row' ] = '<div class="quoty_arch_month"><a href="javascript:modules.home.get_quoty_arch_file_list(\'quoty\',\'%(year)s\',\'%(opera)s\',\'%(month)s\')"">%(txt)s</a></div>';

self [ 'rass_arch_month_row' ] = '<div class="quoty_arch_month"><a href="javascript:modules.home.get_quoty_arch_file_list(\'rass\',\'%(year)s\',\'%(opera)s\',\'%(month)s\')"">%(txt)s</a></div>';

self [ 'view_quoty_arch_lnk_header' ] = '<div class="quoty_arch_lnk_header">Scegli l\'area e preleva gli arretrati</div>';

self [ 'view_quoty_arch_lnk' ] = 	'<div class="quoty_arch_lnk">' +
					'<a href="javascript:kernel.go(\'home\',{mask:\'quoty_arch\',area:\'area_%(area)s\'})" >%(txt)s</a>' +
					'</div>';



modules.doc = {}

modules.doc._today = null;
modules.doc._cur_search_mask = null;

//{{{ init ( dict, data )
modules.doc.init = function ( dict, data )
{
	modules.doc._today = new Date ();

	modules.doc._cur_search_mask =  dict.get ( 'search_form', "search" );
	modules.doc._cur_area = dict.get ( 'area', 'area_prpag' );

	modules.doc._highlight = '';

	var mask = modules.doc._cur_mask = dict.get ( "mask", "" );
	switch ( mask )
	{
		case "show_doc":
			site.show_global_divs ( 'doc' );
			site.create_home_details ( dict, data );
			//site.create_home ( dict, data );
			$ ( 'block_main_top_pag' ).innerHTML = modules.doc.templates [ 'progress_small' ];
			window.scrollTo (0,0);
			if ( ! data ) data = {};
			data [ 'DOCUMENT_TEXT' ] = dict.get ( 'highlight', '' );
			data [ 'mode' ] = 'doc';
			if ( ! $ ( "DOCUMENT_TEXT" ) )
				site.show_mask ( modules.doc._cur_search_mask, dict, data, modules.home.show_mask_done );
			//site.create_home_top ( dict.get ( 'area', '' ) );
			modules.doc.show_doc ( dict, data );
			break;
	}
};
//}}}
//{{{ show_doc ( dict )
modules.doc.show_doc = function ( dict )
{
        var ds = '';
        var pos = dict.get ( 'pos', 0 );

	Note.cbacks [ "change" ] = modules.doc._nota_change;
        
	$ ( 'block_main_body_doc' ).innerHTML = modules.doc.templates [ 'progress' ];

	if ( dict.get ( 'ds_name' ) ) ds = dict.get ( 'ds_name' );

        ds = DataSet.get ( ds );

        if ( ! ds )
        {
                modules.doc._show_doc ( dict );
                return;
        }

        ds.prefetch ( pos + 1, function () { modules.doc._show_doc ( dict ); } );

};
//}}}
//{{{ _show_doc ( dict )
modules.doc._show_doc = function ( dict )
{
	var pos = 0;
	var next = null;
	var prev = null;

	if ( ! dict.get ( 'id' ) )
	{
		$ ( "block_main_body_doc" ).innerHTML = "Documento non trovato";
		return;
	}

	//site.keyman.set ( dict.get ( 'id' ) );
	var cod_opera = dict.get ( 'id' ).substr ( 0, 4 );
	if ( ! site.user_check_opera ( cod_opera ) )
	{
		site.nologged ( cod_opera );
		$ ( "block_main_body_doc" ).innerHTML = site.templates [ 'msg_noopera' ];
		return;
        }

	var ds_name = dict.get ( 'ds_name', '' );

	if ( ds_name )
	{
		var ds = DataSet.get ( ds_name );
		if ( ds )
		{
			pos = parseInt ( dict.get ( 'pos', 0 ) );
			var row = ds.get_row ( pos );

			if ( ! row )
			{
				modules.doc._show_doc_done ( {}, {} );
				return;
			}

			ds.set_curr_doc ( pos );

			if ( pos > 0 ) prev = parseInt ( pos ) - 1;
			if ( pos < ds.num_rows - 1 ) next = parseInt ( pos ) + 1;
		}
        }

        var fq = new FulQuery ();

        fq.lines = 1;
        fq.db_name = "QUOTYI0QU";
	fq.mode = 'SHOW';
	fq.opera = cod_opera;
	//fq.opera = site.keyman.opera;

        fq.set_fields ( "ID", "TIPO", "TITOLO", "OCCHIELLO", "DATA", "DESCR_TIPO", "AUTORE", "DOCUMENT_TEXT", "COD_OPERA", "DATA_FORM", "ESTREMI", "ABSTRACT" );
        fq.add ( "KEY", "EQUAL", dict [ "id" ] );

        if ( dict.get ( "highlight" ) )
        {
                fq.highlight = true;
                fq.add ( "DOCUMENT_TEXT", "FULTXT", dict.get ( "highlight" ) );
                modules.doc._highlight = dict.get ( "highlight" );
        }
        else modules.doc._highlight = '';

        kernel.fulquery ( fq, function ( v ) {
                if ( ! v.get ( "row0" ) )
                {
                        $ ( "block_main_body_doc" ).innerHTML = "Documento non trovato";
                        return;
                }

                modules.doc._show_doc_done ( v [ "row0" ], dict, prev, next, pos );
        }, true );
};
//}}}
//{{{ _show_doc_done ( row, v, prev, next, pos )
modules.doc._show_doc_done = function ( row, v, prev, next, pos )
{
	//TODO: controllare se abilitato all'opera AUTH
	if ( ! row )
	{
		$ ( 'block_main_body_doc' ).innerHTML = 'Documento non trovato';
		return;
	}

	var id_prev, id_next;

	var dict = {
		module: 'doc',
		opera: 'I0QU',
		id: row [ "ID" ],
		mask: 'show_doc'
	};


	var ds = null;

	if ( v.get ( 'ds_name' ) )
	{
		dict [ 'ds_name' ] = v.ds_name;
		ds = DataSet.get ( v.ds_name );
	}

	if ( v.get ( 'pos', -1 ) != -1 ) dict [ 'pos' ] = v.pos;


	if ( ! row [ "DOCUMENT_TEXT" ] ) row [ "DOCUMENT_TEXT" ] = row [ "TITOLO" ];

	if ( row.get ( "DATA" ) ) row [ "_data" ] = utils.order_date ( row [ "DATA" ], "-", "IT", "/" );
	else row [ "_data" ] = '';

	row [ '_text' ] = "";

	//PATCH: per katia su doc I0Q4 e tipo = 88
	if ( row [ "COD_OPERA" ] == "I0Q4" && row [ 'TIPO' ] == '88' )
	{
		ossdoc = true;
		console.debug ( "DOC 88 MODIFICATO" );
		if ( row [ 'OCCHIELLO' ] && ( row [ 'OCCHIELLO' ].length > 5 ) )
			row [ '_text' ] = '<div class="quotidiano_occhiello_comm">' + row [ 'OCCHIELLO' ] + '</div>';

		row [ '_text' ] += '<div class="quotidiano_titolo_comm">' + row [ 'TITOLO' ] + '</div>';

		//if ( row [ 'ABSTRACT' ].length > 5 ) row [ '_text' ] += '<div class="quotidiano_abstract">' + row [ 'ABSTRACT' ] + '</div>';

		row [ '_text' ] += '<div id="doctxt_cnt">' + row [ 'DOCUMENT_TEXT' ] + '</div>';

		if ( row [ 'ESTREMI' ] && ( row [ 'ESTREMI' ].length > 5 ) )
			row [ '_text' ] += '<div class="quotidiano_estremi_doc">' + row [ 'ESTREMI' ] + '</div>';

		row [ '_text' ] = LinkReplacer.lnk2span ( row [ '_text' ] );
	}
	else
		row [ '_text' ] = LinkReplacer.lnk2span ( row [ 'DOCUMENT_TEXT' ] );


	row [ '_back2res' ] = "";

	//PATCH per silvia
	if ( row [ 'TIPO' ] == "86" )  row [ 'DESCR_TIPO' ] = "News";

	$ ( 'block_main_top_pag' ).innerHTML = row [ 'DESCR_TIPO' ] + " " + site._areas.get ( row [ 'COD_OPERA' ] ).lbl;

	if ( ds )
	{
		ds.prefetch ( next ? next : 0, function () { 
			ds.prefetch ( prev ? prev : 0, function () {
				if ( next != null ) id_next = ds.get_row ( next ).get ( 'ID' ) ? ds.get_row ( next ).get ( 'ID' ) : ds.get_row ( next ).get ( 'ID' );
				if ( prev != null ) id_prev = ds.get_row ( prev ).get ( 'ID' ) ? ds.get_row ( prev ).get ( 'ID' ) : ds.get_row ( prev ).get ( 'ID' );
				modules.doc._show_doc_done2 ( ds, row, v, prev, next, pos, id_prev, id_next, dict );
			} );
		} );
	}
	else
		modules.doc._show_doc_done2 ( ds, row, v, prev, next, pos, id_prev, id_next, dict );
};

modules.doc._show_doc_patch = function ( row )
{
	function _set_divs ( elems )
	{
		if ( ! elems ) elems = [];

		var t, l = elems.length;

		for ( t = 0; t < l; t ++ )
		{
			elems [ t ].style.display = 'none';
		}
	}

	if ( row [ "COD_OPERA" ] == "I0Q4" && row [ 'TIPO' ] == '88' )
	{
		//tipo modificato spengo i div del document_text per evitare duplicazioni
		_set_divs ( site.utils.getElementsByClass ( "quotidiano_occhiello", "div", $ ( "doctxt_cnt" ) ) );
		_set_divs ( site.utils.getElementsByClass ( "quotidiano_titolo", "div", $ ( "doctxt_cnt" ) ) );
		_set_divs ( site.utils.getElementsByClass ( "quotidiano_estremi", "div", $ ( "doctxt_cnt" ) ) );
		_set_divs ( site.utils.getElementsByClass ( "quotidiano_abstract", "div", $ ( "doctxt_cnt" ) ) );
	}
};

modules.doc._show_doc_done2 = function ( ds, row, v, prev, next, pos, id_prev, id_next, dict )
{
	$ ( "block_main_body_doc" ).innerHTML = String.formatDict ( modules.doc.templates [ 'doc' ], row );

	modules.doc._show_doc_patch ( row );

	//modules.doc._manip_doc ( row );

	$ ( 'cnt_doc' ).style.display = 'block';

	row [ '_highlight' ] = ',null';
	if ( modules.doc._highlight )
		row [ '_highlight' ] = ',\'' + modules.doc._highlight.replace ( /\'/g, "\\'" ) + '\'';

	row [ '_search_form' ] = 'search';
	if ( modules.doc._cur_search_mask ) row [ '_search_form' ] = ',\'' + modules.doc._cur_search_mask + '\'';

	//navigazione
	if ( prev != null ) prev = String.formatDict ( modules.doc.templates [ "prev_doc" ], { _prev_doc: 'javascript:modules.doc.move_doc(\'' +
			ds.name + '\', \'' + modules.doc._cur_mask + '\', \'' + modules.doc._cur_area + '\', ' + prev + ',\'' + id_prev + '\' ' + row [ '_highlight' ] + row [ '_search_form' ] + ')' } );
			//modules.home._cur_area + '\'' + row [ '_highlight' ] + ')' } );
        if ( next != null ) next = String.formatDict ( modules.doc.templates [ "next_doc" ], { _next_doc: 'javascript:modules.doc.move_doc(\'' +
			ds.name + '\', \'' + modules.doc._cur_mask + '\', \'' + modules.doc._cur_area + '\', ' + next + ',\'' + id_next + '\' ' + row [ '_highlight' ] + row [ '_search_form' ] + ')' } );
			//modules.home._cur_area + '\'' + row [ '_highlight' ] + ')' } );

	site.get_corrs ( [ row [ 'ID' ] ], [], function ( corrs ) {
		modules.doc._render_corrs ( corrs, row );
	} );

	var navi = prev ? prev : "";
	if ( next ) navi += next;

	$ ( "doc_navi" ).innerHTML = navi;

	if ( ds )
	{
		$ ( 'block_main_top_downl' ).innerHTML = String.formatDict ( modules.doc.templates [ 'top_back2results' ], { _cur_area: modules.doc._cur_area } ) ;
		$ ( 'block_main_top_downl' ).style.display = 'block';
	}

	LinkReplacer.replace_anchors ( $ ( "block_main_body_doc" ), true );
	LinkReplacer.replace ( modules.doc._link_replace );


	modules.doc._curdoc = row;

	var tbar = new Toolbar.instance ( 'doctbar' );
	if ( site.serv_centr ) tbar.add ( '<img src="/gfx/icon_annot01.gif" border="0" alt="ANNOTA" title="ANNOTA" />', modules.doc.annota );

	if ( kernel.user_info [ 'device_family' ] != 'ipad' )
	{
		tbar.add ( '<img src="/gfx/icon_print.gif" border="0" alt="STAMPA" title="STAMPA" />', modules.doc.stampa );
		tbar.add ( '<img src="/gfx/icon_disk.gif" border="0" alt="SALVA" title="SALVA" />', modules.doc.salva );
	}
	if ( site.serv_centr ) tbar.add ( '<img src="/gfx/icon_elenco.gif" border="0" alt="ARCHIVIA" title="ARCHIVIA" />', modules.doc.add_bookmark );
	tbar.render ('cnt_doc_tbar' );

	Note.get ( 'I0QU',  modules.doc._curdoc [ "ID" ] );
};
//}}}

modules.doc.add_bookmark = function ()
{
	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "lb_doc_save", "Salvataggio documento", 500, 500 );

	$ ( "lb_doc_save" ).innerHTML = '<div class="label">Scegli la cartella in cui salvare i documenti:</div>' +
					'<div id="bookmarks"></div>' +
					'<div class="button"><button onclick="modules.doc._do_salva()">Salva</button></div>';

	Bookmarks.init ( true, { opera: "I0QU" }, function () { Bookmarks.render ( "bookmarks" ); } );
};


modules.doc._do_salva = function ()
{
	var selnode = Bookmarks.get_selected ();
	if ( ! selnode ) return;

	var res = [];
	var r = modules.doc._curdoc;

        var data = {
                'id_parent': selnode
        };

	var s = "";

	s = "I0QU|";
	if ( r [ 'id' ] ) s += r [ "id" ] + "|";
	else if ( r [ 'ID' ] ) s += r [ "ID" ] + "|";
	s += "show_doc|";

	var titolo = r [ "TITOLO" ];
	titolo = titolo.replace ( /<br *\/?>/g, " - " );
	s += titolo + "||";

	data [ "key0" ] = s;

        Bookmarks.multi_insert ( data, function ( v ) {

                liwe.lightbox.close ();

        } );
};

modules.doc.salva = function ()
{
	window.open ( "/cgi-bin/DocPrint?MODE=open&_X_OPERA=I0QU&_X_DBNAME=QUOTY&KEY0='" + modules.doc._curdoc [ "ID" ] + "'" );
};

modules.doc.stampa = function ()
{
	window.open ( "/cgi-bin/DocPrint?MODE=open&_X_OPERA=I0QU&_X_DBNAME=QUOTY&KEY0='" + modules.doc._curdoc [ "ID" ] + "'" );
};

modules.doc.annota = function ()
{
	Note.edit ( 'I0QU', 'show_doc', modules.doc._curdoc [ "ID" ], modules.doc._curdoc [ "TITOLO" ] );
};

//{{{ _link_replace ( lnk )
modules.doc._link_replace = function ( lnk )
{
        var opera = lnk.getAttribute ( 'opera' );
        var tipo = lnk.getAttribute ( 'tipo' );
        var fname = lnk.getAttribute ( 'filename' );
        var chiavi = lnk.getAttribute ( 'chiavi' );
        var mime = lnk.getAttribute ( 'mime' );
        var href = '';

        var t, l;
        var lst = [];

        if ( chiavi ) lst = chiavi.split ( " " );

	if ( ! site.user_check_opera ( opera ) ) return "javascript:site.nologged('" + opera + "')";

        if ( fname )
        {
		href = "/cgi-bin/downloader.cgi?OPERA=I0QU&FILE=" + opera + "/" + fname;
		if ( mime ) href += "&MIME=" + mime;
        }
        else
        {
                if ( lst.length > 1 )
                {
                        chiavi = chiavi.replace ( / /g, "+" );
                }

                href = "javascript:kernel.go('doc',{mask:'show_doc',id:'" + chiavi+ "', search_form:'" + modules.doc._cur_search_mask + "'})";
        }

        return href;
};
//}}}
//{{{ move_doc ( ds_name, mask, area, pos, id, highlight, search_form )
modules.doc.move_doc = function ( ds_name, mask, area, pos, id, highlight, search_form )
{
	kernel.go ( 'doc', { ds_name: ds_name, 'mask': mask, 'area': area, pos: pos, opera: 'I0QU', id: id, mask: "show_doc", move: true, highlight: highlight, 'search_form': search_form } );
};
//}}}

modules.doc._nota_change = function ( v )
{
	if ( v && v [ "text" ] )
		$ ( "doctbar_btn_0" ).firstChild.src = "/gfx/icon_annot02.gif";
	else
		$ ( "doctbar_btn_0" ).firstChild.src = "/gfx/icon_annot01.gif";
};

//{{{ _render_corrs ( v, row )
modules.doc._render_corrs = function ( v, doc )
{
	var t, l = v [ 'rows' ];
	var row;
	var s = '';
	var cnt_corr = $ ( 'doc_corrs' );
	var s = '';

	for ( t = 0; t < l; t ++ )
	{
		row = v [ "row" + t ];
		if ( ! row || ! row [ 'TIPO_RIF' ] ) continue;

		switch ( row [ 'TIPO_RIF' ] )
		{
			case "78":
				row [ '_txt' ] = 'Leggi il commento';
				break;
			case "79":
				row [ '_txt' ] = 'Leggi la news';
				break;
			case "80":
				row [ '_txt' ] = 'Leggi la tabella';
				break;
			case "81":
				row [ '_txt' ] = 'Leggi la sintesi del rinnovo';
				break;
			case "82":
				row [ '_txt' ] = 'Tabelle retributive';
				break;
		}
		row [ '_cur_area' ] = modules.doc._cur_area;
		row [ '_search_mask' ] = modules.doc._cur_search_mask;
		row [ '_img' ] = 'corr_' + row [ 'TIPO_RIF' ];

		row [ 'KEY_RIF' ] = row [ 'KEY_RIF' ].Strip();
		
		if ( site.user_check_opera ( doc [ "COD_OPERA" ] ) ) 
			s += String.formatDict (  modules.doc.templates [ 'corr_lnk' ], row );
		else
			s += String.formatDict (  modules.doc.templates [ 'corr_lnk_nologged' ], row );

	}
	cnt_corr.innerHTML = s;
};
//}}}

modules.doc.ds_back = function ( elem, area )
{
	site.show_global_divs ( 'search' );

	var s = String.formatDict (  modules.doc.templates [ 'ds2areahome' ], { name: area } );
	$ ( 'block_main_top_downl' ).innerHTML = s;
	$ ( 'block_main_top_downl' ).style.display = 'block';

	modules.doc._top_pag_arrange ( modules.doc._cur_area.replace ( "area_", "" ) );
};

modules.doc._top_pag_arrange = function ( area )
{
	var s = '';
	if ( area == 'prpag' ) s = 'Tutti i risultati';
	else s = 'Risultati ' + site._areas.get ( area ).lbl;
	$ ( 'block_main_top_pag' ).innerHTML = s;
};

modules.doc._manip_doc = function ( doc )
{
	var elems = $ ( 'cnt_doc' ).getElementsByTagName ( 'div' );

	modules.doc._class_arrange ( doc, elems, RegExp( 'quotidiano_titolo' ) );
	modules.doc._class_arrange ( doc, elems, RegExp( 'quotidiano_occhiello' ) );
};

modules.doc._class_arrange = function ( doc, elems, pattern )
{
	var classElements = new Array();
	var i, l = elems.length;

	for ( i = 0; i < l; i++ )
		if ( pattern.test ( elems[i].className ) ) classElements.push( elems [ i ] );

	if ( classElements.length <= 0 ) return;

	var el = classElements [ 0 ];

	var cls_name = site.tipo2name ( doc [ 'TIPO' ] );
	if ( cls_name ) el.className = el.className + '_' + cls_name;
};



modules.doc.templates = {};

var self = modules.doc.templates;

self [ 'progress' ] = '<div class="progress_div">&nbsp;</div>';
self [ 'lnk_back2results' ] = 	'<a href="javascript:modules.doc.ds_back(this,\'%(_cur_area)s\')">Torna ai risultati</a>';

self [ 'back2results' ] = '<div class="goback">' + self [ 'lnk_back2results' ] + '</div>';

self [ 'back2history' ] = '<div class="goback"><a href="javascript:history.go(-1)">Indietro</a></div>';

self [ 'top_back2results' ] = '<div class="ds_back2home">' + self [ 'lnk_back2results' ] + '</div>';

self [ 'ds2areahome' ] = '<div class="ds_back2home"><a href="javascript:modules.home.ds_back2home(\'%(name)s\')">Torna alla home</div>';

self [ 'doc' ] =        '<div id="cnt_doc" class="cnt_doc" style="display: none;">' +
			'       <div class="doc_header">' +
			//'               <div class="doc_tipo">%(DESCR_TIPO)s</div>' +
			//'               <div class="doc_data">%(_data)s</div>' +
			'       </div>' +
			'	<div class="doc_dataform">%(DATA_FORM)s</div>' +
			'       <div class="doc_txt">%(_text)s</div>' +
			'	<div id="main_tbar">' +
			'		<div class="tbar_sx">&nbsp;</div>' +
			'		<div id="cnt_doc_tbar" class="tbar"></div>' +
			'		<div class="tbar_dx">&nbsp;</div>' +
			'	</div>' +
			'	<div id="doc_corrs" class="doc_corrs"></div>' +
			'       <div id="doc_navi" class="doc_navi"></div>' +
			'</div>';

self [ 'prev_doc' ] = '<div class="doc_navi_prev">&lt;&lt; <a href="%(_prev_doc)s"><i>Risultato precedente<\/i><\/a></div>';

self [ 'next_doc' ] = '<div class="doc_navi_next"><a href="%(_next_doc)s"><i>Risultato successivo<\/i><\/a> &gt;&gt;</div>';

self [ 'corr_lnk' ] = 	'<div class="last_list" style="width: auto;">' +
			'	<a href="javascript:kernel.go(\'doc\',{mask:\'show_doc\',area:\'%(_cur_area)s\',id:\'%(KEY_RIF)s\',search_form:\'%(_search_mask)s\'})">' +
			'	<img border="0" title="" alt="" src="gfx/%(_img)s.gif"/>' +
			'	%(_txt)s</a>' +
			'</div>';

self [ 'corr_lnk_nologged' ] = '';

self [ 'progress_small' ] = '<div class="progress_div_small" style="width: 100px; height: 22px;">&nbsp;</div>';


modules.scrivania = {};


modules.scrivania.init = function ( dict, data )
{
	//site.navi_path.set_title ( 'Scrivania' );

	//site.right_bar.render ( "right_block_top" );

	Bookmarks.cbacks [ "save_print" ] = Bookmarks._save_print;
	Bookmarks.cbacks [ "deleted" ] = function () { ServCentr.refresh_all_docs (); };

	site.show_global_divs ( "doc" );

	var mask = dict.get ( "mask", "" );
	switch ( mask )
	{
		case "ricerche_effettuate":
			modules.scrivania.ricerche ( 0 );
			break;

		case "ricerche_salvate":
			modules.scrivania.ricerche ( 1 );
			break;

		case "documenti_annotati":
			//site.navi_path.add ( "Documenti annotati", { module: "scrivania", mask: "documenti_annotati" } );
			modules.scrivania.documenti_annotati ();
			break;

		case "pratiche":
			//site.navi_path.add ( "Gestione pratiche" );
			modules.scrivania.pratiche ( true );
			break;

		case "documenti_salvati":
			//site.navi_path.add ( "Documenti salvati", { module: "scrivania", mask: "documenti_salvati" } );
			modules.scrivania.pratiche ( false );
			break;
	}
};


modules.scrivania.ricerche = function ( saved )
{
	//site.navi_path.add ( saved ? "Ricerche salvate" : "Ricerche effettuate" );

	Ricerca.list ( 'block_main_body_doc', saved );
};

modules.scrivania.documenti_annotati = function ()
{
	Note.show_docs ( "block_main_body_doc" );
};


modules.scrivania.pratiche = function ( folder_only )
{
	$ ( "block_main_body_doc" ).innerHTML = modules.scrivania.templates [ "pratiche" ];


	Bookmarks.item_dblclick_event = modules.scrivania._bookmark_dblclick;

	Bookmarks.init ( folder_only, { opera: "AP", 'print_note': 1 }, function () { 
		Bookmarks.checkall = true;
		Bookmarks.render ( "pratiche" ); 
	} );
};

modules.scrivania._bookmark_dblclick = function ( data )
{
	var tipo = data [ "node_type" ];

	kernel.go ( 'doc', { mask: 'show_doc', maschera: tipo, opera: data.opera, id: data.doc_key } );
};



modules.scrivania.templates = {};

modules.scrivania.templates [ 'ricerca_row' ] =      '<tr>' +
					'  <td><a href="javascript:modules.scrivania.go_ricerca(%(id_ricerca)s)">%(created)s<\/a><\/td><td>%(descr)s<\/td>' +
					'<\/tr>';

modules.scrivania.templates [ 'ricerca_result' ] = 	'<table id="ricerca_head">' +
							'  <tr>' +
							'    <th>Data<\/th>' +
							'    <th>Descrizione<\/th>' +
							'  <\/tr>' +
							'  %(rows)s' +
							'<\/table>'; 

modules.scrivania.templates [ "pratiche" ] =         '<div id="pratiche"><\/div>';



var actionbar = {};

actionbar._ds = null;
actionbar._div = null;
actionbar._type = null;


actionbar.init = function ( ds, div, type, template )
{
	actionbar._ds = ds;
	actionbar._div = div;
	actionbar._type = type;
	actionbar._templ = template;
};

actionbar._get_rows = function ()
{
	var div = $( actionbar._div );
	var checks = div.getElementsByTagName ( 'INPUT' );
	var t, l = checks.length;
	var res = [];
	var chk;
	var row, pos;

	for ( t = 0; t < l; t ++ )
	{
		chk = checks [ t ];
		if ( chk.type != 'checkbox' )  continue;
		if ( ! chk.checked ) continue;

		pos = chk.id.split ( ":" ) [ 1 ];

		row = actionbar._ds.get_row ( parseInt ( pos ) );

		res.push ( row );
	}

	return res;
};


actionbar.salva = function ( rows )
{
	if ( ! rows ) rows = actionbar._get_rows ();
	if ( ! rows.length ) return;

	actionbar._rows = rows;
	
	liwe.lightbox.fade = false;
	liwe.lightbox.easy ( "lb_doc_save", "Salvataggio documento", 500, 420 );

	$ ( "lb_doc_save" ).innerHTML = '<div class="label">Scegli la pratica in cui salvare i documenti:<\/div>' +
					'<div id="bookmarks"><\/div>' +
					'<div class="button"><button onclick="actionbar._do_salva()">Salva<\/button><\/div>';

	Bookmarks.init ( true, { opera: "AP" }, function () { Bookmarks.render ( "bookmarks" ); } );
};


actionbar._do_salva = function ()
{
	var selnode = Bookmarks.get_selected ();
	if ( ! selnode ) return;

	var rows = actionbar._rows;

	var res = [];
	var i, l = rows.length;
	for ( i = 0; i < l ; i++ )
	{
		var r = rows [ i ];

		if ( ! rows [ i ] ) continue;

		res.push ( r [ "opera" ] );
		if ( r [ 'id' ] ) res.push ( r [ "id" ] );
		else if ( r [ 'ID' ] ) res.push ( r [ "ID" ] );
		res.push ( actionbar._type );

		var titolo = r [ "_estrcomp" ];
		titolo = titolo.replace ( /<br *\/?>/g, " - " );
		res.push ( titolo );
	}
	
	var mkey = "|".join ( res );

	var data = {
		'id_parent': selnode,
		'multi_key': mkey
	};

	Bookmarks.multi_insert ( data, function ( v ) {

		liwe.lightbox.close ();

	} );
};

actionbar.stampa = function ()
{
	var rows = actionbar._get_rows ();
	var t, l = rows.length;
	var s = '';

	if ( ! l ) return;

	for ( t = 0; t < l; t ++ )
	{
		if ( ! rows [ t ] ) continue;

		if ( rows [ t ].get ( 'id' ) ) s += "'" + rows [ t ] [ 'id' ] + "'@";
		else if ( rows [ t ].get ( 'ID' ) ) s += "'" + rows [ t ] [ 'ID' ] + "'@";
	}

	if ( s )
		window.open ( "/cgi-bin/DocPrint?MODE=OPEN&TEMPLATE=" + actionbar._templ + "&FULTIPO=5&KEY0=" + s );
};

actionbar.print_search_results = function ()
{
	var wnd;

	wnd = window.open ();
	wnd.document.write ( actionbar._ds.to_string () );
	wnd.document.close ();
	wnd.print ();
	wnd.close ();
};



