/********************* 
***	Settings
**********************/
var options = {
	// default tabs & contents
	defaultSettings: {
		"tabs": 
			[{ 
				"name": "Home Page",
				"tabId": 0,
				"color": "color_001",
				"cols":
					[{
						"colId": 0,
						"items":
							[{
								type: 'include',
								itemId: 0,
								link: "/live/SerieA/giornata_corrente-sunto.html",
								title: "Risultati Serie A",
								local: true
							},
							{
								type: 'include',
								itemId: 1,
								link: "/live/SerieA/classifica-compatta.html",
								title: "Classifica Serie A",
								local: true
							}]
					}, 
					{
						"colId": 1,
						"items":
							[{
								type: 'rss',
								itemId: 2,
								link: "/rss/piu_visti.json",
								title: "I pi\u00f9 visti 24 ore",
								local: true
							},
							{
								type: 'rss',
								itemId: 3,
								link: "/rss/Calcio-3.json",
								title: "News Calcio",
								local: true
							}]
					}, 
					{
						"colId": 2,
						"items":
							[{
								type: 'include',
								itemId: 4,
								link: "/piuvisti/foto24ore.html",
								title: "Fotogallery pi\u00f9 viste",
								local: true
							},
							{
								type: 'rss',
								itemId: 5,
								link: "/rss/Formula-1-7.json",
								title: "News Formula1",
								local: true
							}]
					}]
			}]
	},
	/*
		eg: {
			"tabs": 
				[{
					"name": "ggg4", 
					"tabId": "0",
					"cols": 
						[{
							"colId": "0",
							"items": 
								[{
									itemId: "",
									link: "http://localhost:8080",
									title: "My Feed"
								}]
						}]
				}] 
			}
	*/

	// HTML ids and classes
	status_bar: 'status_bar', // id
	sel_tab_colori: 'sel_tab_colori', // id
	sel_tab_items: 'sel_tab_items', // id
	new_tab_link: 'new_tab_link', // id
	new_col_link: 'new_col_link', // id
	del_tab_link: 'del_tab_link', // id
	del_col_link: 'del_col_link', // id
	rename_tab_link: 'rename_tab_link', // id
	tab_contents: 'tab_contents', // id
	tab_li_container: 'tab_li_container', // id
	tab_li_new: 'tab_li_new', // id
	tab_commands: 'CommandLine', // id
	tab_header: 'MyCorriere_Header', // id
	tab_name: 'tab_name', // input name
	tab_button: 'tab_btn', // class
	tab_button_sel: 'selected', // class
	tab_column: 'tab_MyCorriere', // class
	tab_content: 'MyCorriere_Body minHeight', // class
	
	block: 'block', // class
	block_content: 'content', // class
	block_handle: 'handle', // class
	block_hover: 'hover', // class
	block_toggle: 'block-toggle', // class
	item_list: 'item-list', // class
	item_entry: 'item-entry', // class
	more_link: 'more-link', // class
	
	// URLs			
	load_url: '/dinamiche/LoadSettings',
	save_url: '/dinamiche/SaveSettings',
	get_feed: '/dinamiche/Feed',
	login_url: '/dinamiche/login.jsp?srv=2',
	rss_page_url: '/rss/rss.shtml',
	default_thumb: '/res/img/img_74x55.png',
	
	// messages
	loading_msg: 'Loading...',
	load_error_msg: 'Errore nel caricamento delle impostazioni personali.',
	save_error_msg: 'Errore nel salvataggio delle impostazioni personali.',
	not_logged_in_msg: 'L\'utente non \u00E8 loggato. Le modifiche non verranno salvate.',
	enter_to_confirm: 'Premere invio per confermare le modifiche.',
	item_added_msg_template: new Template('Il contenuto \u00e8 stato aggiunto alla pagina "#{tabname}"'),
	msg_display_interval: 5, // in seconds
	
	// save settings every N seconds (-1 to save every time settings are modified)
	save_interval: 120,
	// update block item content every N seconds (-1 to disable)
	update_block_interval: 60,
	
	// tabs and columns: min and max counts
	min_column_count: 2,
	max_column_count: 3,
	min_tab_count: 1,
	max_tab_count: 10,
	
	// news per box
	max_news_per_item: 5,
	
	// default tab name
	default_tab_name: 'Nuova Pagina',
	tab_name_max_length: 15,
	default_color: 'color_001',
	
	// item text truncate (#chars)
	item_title_truncate: 50,
	item_description_truncate: 100,
	item_full_truncate: 150
}

/*********************
*** Class BlockItem
**********************/
var BlockItem = Class.create();
BlockItem.prototype = {
	/* creates a new block item */
	initialize: function (col, options) {
		this.col = col;
		this.options = options; // type, itemId, link, title, local
		this.last_feed_link = '';
		this.updater = null;
		this.req_active = false; // is ajax request in execution?

		new Insertion.Bottom('col_' + col.options.colId,
			'<div class="box ' + mhpObj.options.block + '" id="item_' + options.itemId +
			'" class="' + mhpObj.options.block_handle + '">' +			
			'<div class="MC_tr"><h2 class="clearfix"><img src="/res/img/ico_FavIco_Corriere.png" />' +
			'<span id="span_box_' + options.itemId + '">' + options.title + '</span><span id="span_box_edit_' + 
			options.itemId + '" style="display:none"><input type="text" value="' + options.title + 
			'" /></span></h2><ul><li><a href="javascript:;" id="rename_itm_' + options.itemId + 
			'" title="Modifica nome"><img src="/res/img/btn_MC_edit.png" alt="Modifica nome" /></a></li>' +
			'<li><a href="javascript:;" id="del_itm_' + options.itemId + '" title="Elimina contenitore">' +
			'<img src="res/img/btn_MC_del.png" alt="Elimina contenitore" /></a></li>' +
			'</ul></div><div class="' + mhpObj.options.block_content + ' MC_body clearfix" id="cts_itm_' + 
			options.itemId + '"><ul id="ul_itm_' + options.itemId + 
			'" class="listNews ArchiveList underlined clearfix">' +
			'<li class="clearfix firstLine"><h3><span>Loading...</span></h3></li></ul></div>' +
			'<div class="MC_br"><div class="MC_bl"></div></div></div>'
		);

		// setting event handlers
		Event.observe('del_itm_' + options.itemId, 'click', this.deleteItem.bindAsEventListener(this), false);
		Event.observe('rename_itm_' + options.itemId, 'click', this.renameItem.bindAsEventListener(this), false);
		Event.observe($('span_box_edit_' + options.itemId).firstDescendant(), 'keypress', this.onKeyPress.bindAsEventListener(this), false);
		Event.observe($('span_box_edit_' + options.itemId).firstDescendant(), 'blur', this.doRename.bindAsEventListener(this), false);
		
		mhpObj.updateSortables();
		
		// show label "[Aggiunto]"
		var addedId = 'added_' + this.options.link.replace(/[^\w]/g, '');
		if ($(addedId)) {
			$(addedId).show();
		}
		
		if (options.type == 'rss') {
			// setting content and periodical content updater
			if (mhpObj.options.update_block_interval > 0) {
				this.updater = 
					new PeriodicalExecuter(this.updateContent.bind(this), mhpObj.options.update_block_interval);
			}
	
			this.updateContent();
		} else if (options.type == 'include') {
			new Ajax.Updater('cts_itm_' + options.itemId, options.link, {
				method: 'get',
				evalScripts: true,
				onComplete: function () {
					var elms = $('cts_itm_' + this.options.itemId).immediateDescendants();
					elms = elms.findAll(function (elm) {
						return elm.visible() && !elm.hasClassName('mhp_show');
					});
					if (elms.length > 0) {
						var width = (100 / elms.length) - 0.1;
						elms.each(function (elm) {
							elm.setStyle({ width: width + '%', cssFloat: 'left' });
						});
					}
					$A($('cts_itm_' + this.options.itemId).getElementsByClassName('mhp_show')).each(function (elm) {
						elm.setStyle({ width: '99.9%', display: '', padding: '0px' });
					});
				}.bind(this)
			});					
		}
	},
	
	/* deletes the item */
	deleteItem: function () {
		if (!mhpObj.checkLoggedIn()) return;
	
		// deleting items
		$('item_' + this.options.itemId).remove();
		
		// updating settings
		this.col.options.items = this.col.options.items.reject(function (item) {
			return item.itemId == this.options.itemId;
		}.bind(this));
		mhpObj.settingsChanged();

		// updating references		
		this.col.items = this.col.items.reject(function (item) {
			return item == this;
		}.bind(this));
		
		// hide label "[Aggiunto]" if no more items with this link are in page
		var allItems = mhpObj.settings.tabs.pluck('cols').flatten().pluck('items').flatten();
		if (allItems) {
			var stillInPage = allItems.pluck('link').member(this.options.link);
			if (!stillInPage) {
				var addedId = 'added_' + this.options.link.replace(/[^\w]/g, '');
				if ($(addedId)) {
					$(addedId).hide();
				}
			}
		}
		
		// stopping updater
		if (this.updater != null) {
			this.updater.stop();
		}
	},
	
	/* shows the input box to rename the item */
	renameItem: function () {
		if (!mhpObj.checkLoggedIn()) return;
	
		$('span_box_edit_' + this.options.itemId).firstDescendant().value = this.options.title;
		$('span_box_' + this.options.itemId).hide();
		$('span_box_edit_' + this.options.itemId).show();
		$('span_box_edit_' + this.options.itemId).firstDescendant().focus();
		//mhpObj.displayMessage(false, mhpObj.options.enter_to_confirm);
	},
	
	onKeyPress: function (event) {
		if (event.keyCode == 13 || event.which == 13) {
			// enter pressed
			this.doRename();
		} else if (event.keyCode == 27 || event.which == 27) {
			// esc pressed
			$('span_box_' + this.options.itemId).show();
			$('span_box_edit_' + this.options.itemId).hide();
		}
	},
	
	doRename: function () {
		var newTitle = $('span_box_edit_' + this.options.itemId).firstDescendant().value;
		$('span_box_' + this.options.itemId).innerHTML = newTitle;
		
		this.options.title = newTitle; 
		mhpObj.settingsChanged();
		
		$('span_box_' + this.options.itemId).show();
		$('span_box_edit_' + this.options.itemId).hide();
	},
	
	/* updates the content asking the server for a new version */
	updateContent: function () {		
		if (this.req_active) {
			// previous request is still executing
			return;
		}
		
		if (this.options.local) {
			// static content on server
			new Ajax.Request(this.options.link, {
				onSuccess: this.updateContent_OnSuccess.bind(this),
				onCreate: function () { this.req_active = true }.bind(this),
				onComplete: function () { this.req_active = false }.bind(this)
			});
		} else {
			// via proxy
			new Ajax.Request(mhpObj.options.get_feed, {
				parameters: { link: this.options.link, last: this.last_feed_link },
				onSuccess: this.updateContent_OnSuccess.bind(this),
				onCreate: function () { this.req_active = true }.bind(this),
				onComplete: function () { this.req_active = false }.bind(this)
			});
		}
	},
	
	/* update content Ajax request handler */
	updateContent_OnSuccess: function (transport) {
		// evaluating response -> defines var newContent
		eval(transport.responseText);
		
		// checking whether link it is allowed
		if (newContent.not_allowed) {
			this.updateContent_OnNotAllowed();
			return;
		}

		// checking whether it has been modified
		if (this.options.local) {
			if (newContent.entries.length > 0 && 
				newContent.entries[0].link == this.last_feed_link) {
				return;
			}
		} else {
			if (!newContent.modified) {
				// not modified, nothing to do
				return;
			}
		}
		
		// removing previous content
		var ul = $('ul_itm_' + this.options.itemId);
		ul.childElements().invoke('remove');
		
		// setting new content
		var i = 0;
		newContent.entries.each(function (entry) {
			if (i >= mhpObj.options.max_news_per_item) {
				return;
			}
		
			var linkUrl = entry.link;
			if (!linkUrl || linkUrl == '') {
				linkUrl = this.options.local ? mhpObj.options.rss_page_url : this.options.link;
			}
		
			var linkText = "";		
			var pText = "";
			if (entry.title && entry.title != '') {				
				if (entry.description && entry.description != '') {
					linkText = entry.title.truncate(mhpObj.options.item_title_truncate);
					pText = "<p>" + entry.description.truncate(mhpObj.options.item_description_truncate) + "</p>";
				} else {
					linkText = entry.title.truncate(mhpObj.options.item_full_truncate);
				}
			} else {
				linkText = entry.link;
				if (entry.description && entry.description != '') {
					pText = "<p>" + entry.description.truncate(mhpObj.options.item_description_truncate) + "</p>";
				}
			}
			
			var attrLinkText = prepareStringForAttr(linkText);
			
			new Insertion.Bottom(ul, '<li class="clearfix ' + (i++ == 0? 'firstLine' : '') + '">' +
				(this.options.local ? 
				'<div class="imgBox_74x55 fleft"><div class="imgThumb"><span class="imgSpan"></span><a href="' + 
				linkUrl + '" target="_top" title="' + attrLinkText + '"><img src="' + 
				(entry.image != '' ? entry.image : mhpObj.options.default_thumb) + 
				'" alt="' + attrLinkText + '" /></a></div></div>' : '') +
				'<h3><a href="' + linkUrl + '" target="_top" title="' + 
				attrLinkText + '">' + linkText + '</a></h3>' + pText + '</li>');
		}.bind(this));
		
		// getting last link
		if (newContent.entries.length > 0) {
			this.last_feed_link = newContent.entries[0].link; 
		}
	},
	
	/* handles a not allowed link */
	updateContent_OnNotAllowed: function () {
		// diplay message		
		$('cts_itm_' + this.options.itemId).innerHTML = 'Link non disponibile. Si prega di rimuovere.';
		
		// stop updater
		if (this.updater != null) {
			this.updater.stop();
		}
	}
}

/********************* 
***	Class TabColumn
**********************/
var TabColumn = Class.create();
TabColumn.prototype = {
	/* creates a new column in a tab */
	initialize: function (tab, options) {
		this.tab = tab;
		this.options = options; // colId, items

		// IE6 seems not to like inserting td's via Insertion object
		var newCol = document.createElement('td');
		newCol.id = 'col_' + options.colId;
		newCol.className = mhpObj.options.tab_column;
		$('tab_row_' + tab.options.tabId).appendChild(newCol);
		
		// create items
		this.items = $A(options.items).collect(function (itemOpts) {
			return new BlockItem(this, itemOpts);
		}.bind(this));
		
		mhpObj.updateSortables();
	},
	
	/* deletes the column from its tab */
	deleteColumn: function () {
		// deleting items
		this.items.each(function (item) {
			item.deleteItem();
		});
		
		// deleting column
		$('col_' + this.options.colId).remove();
		
		// updating settings
		this.tab.options.cols = this.tab.options.cols.reject(function (col) {
			return col.colId == this.options.colId;
		}.bind(this));
		mhpObj.settingsChanged();
		
		// updating references
		this.tab.cols = this.tab.cols.reject(function (col) {
			return col == this;
		}.bind(this));

		// updating column width for remaining colunms
		this.tab.updateColumnWidth();
	},
	
	copyItemsTo: function (targetCol) {
		// update settings and references
		this.options.items.each(function (item) {
			var newItemId = mhpObj.getNextItemId();
			var itemOpts = $H({ 
				type: item.type, 
				itemId: newItemId, 
				title: item.title, 
				link: item.link, 
				local: item.local 
			});
			var newItem = new BlockItem(targetCol, itemOpts);
			targetCol.options.items.push(itemOpts);
			targetCol.items.push(newItem); 
		});
		mhpObj.settingsChanged();
	}
};


/********************* 
***	Class Tab
**********************/
var Tab = Class.create();
Tab.prototype = {
	/* constructor, creates the tab */
	initialize: function (options) {
		this.options = options; // tabId, name, cols
		
		if (!options.no_rendering) {
			// insert tab_button and tab_contents
			new Insertion.Before(mhpObj.options.tab_li_new,'<li id="tab_b_' + options.tabId + 
				'" class="' + mhpObj.options.tab_button + '"><h2><a id="sel_tab_' + options.tabId + 
				'" href="javascript:;"><span id="span_tab_' + options.tabId + '">' + options.name + 
				'</span><span id="span_tab_edit_' + options.tabId + '" style="display:none"><input type="text" value="' + 
				options.name + '" maxlength="' + mhpObj.options.tab_name_max_length + '" /></span></a></h2></li>');
				
			new Insertion.Bottom(mhpObj.options.tab_contents, '<div id="tab_' + options.tabId + 
				'" class="' + mhpObj.options.tab_content + ' ' + mhpObj.color + '" style="display: none;">' +
				'<table class="twoColoumns" style="width:100%"><tbody><tr id="tab_row_' + options.tabId + 
				'"></tr></tbody></table></div>');
			
			// bind event handlers
			Event.observe($('sel_tab_' + options.tabId), 'click', this.selectTab.bindAsEventListener(this), false);
			Event.observe($('span_tab_edit_' + options.tabId).firstDescendant(), 'keypress', this.onKeyPress.bindAsEventListener(this));
			Event.observe($('span_tab_edit_' + options.tabId).firstDescendant(), 'blur', this.renameTab.bindAsEventListener(this));
			
			// create tab columns
			this.cols = $A(options.cols).collect(function (colOpts) {
				return new TabColumn(this, colOpts);
			}.bind(this));
			
			if (this.cols.length == 0) {
				this.createColumn();
				this.createColumn();
			}
			
			this.updateColumnWidth();
			//theScroller.update();
		}
	},
	
	/*  handles keypressed on tab name input box */
	onKeyPress: function (event) {
		if (event.keyCode == 13 || event.which == 13) {
			// enter pressed
			this.renameTab();
		} else if (event.keyCode == 27 || event.which == 27) {
			// esc pressed
			$('span_tab_' + this.options.tabId).show();
			$('span_tab_edit_' + this.options.tabId).hide();
		}
	},

	renameTab: function (event) {
		var newTabName = $('span_tab_edit_' + this.options.tabId).firstDescendant().value;
		$('span_tab_' + this.options.tabId).innerHTML = newTabName;
		
		this.options.name = newTabName; 
		mhpObj.settingsChanged();
		
		$('span_tab_' + this.options.tabId).show();
		$('span_tab_edit_' + this.options.tabId).hide();
	},

	/* deletes the tab */
	deleteTab: function () {
		// deleting tab columns
		mhpObj.skipSave = true;
		this.cols.each(function (col) {
			col.deleteColumn();
		});
		mhpObj.skipSave = false;
		
		// deleting tab and tab button
		$('tab_b_' + this.options.tabId).remove();
		$('tab_' + this.options.tabId).remove();
		
		// update references
		mhpObj.tabs = mhpObj.tabs.reject(function (tab) {
			return tab == this;
		}.bind(this));

		// handling selected tab		
		if (mhpObj.selTabId == this.options.tabId) {
			mhpObj.selTabId = null;
			if (mhpObj.tabs.length > 0) {
				mhpObj.tabs[0].selectTab();
			}
		}
		
		// updating settings
		mhpObj.settings.tabs = mhpObj.settings.tabs.reject(function (tab) {
			return tab.tabId == this.options.tabId;
		}.bind(this));
		mhpObj.settingsChanged();
		
		//theScroller.update();
	},
	
	/* selects (open) the tab */
	selectTab: function () {
		if (mhpObj.selTabId == this.options.tabId) {
		 	return;
		}
		
		// deselecting previous tab
		if (mhpObj.selTabId != null) {
			if (mhpObj.selTabId != 'items' && 
					this.options.tabId != 'items' &&
					mhpObj.selTabId != 'colori' &&
					this.options.tabId != 'colori') {
				$('tab_b_' + mhpObj.selTabId).removeClassName(mhpObj.options.tab_button_sel);
			}
			if (mhpObj.prevSelTabId != null && 
					(mhpObj.selTabId == 'items' || mhpObj.selTabId == 'colori') &&
					(this.options.tabId != 'items' && this.options.tabId != 'colori')) {
				$('tab_b_' + mhpObj.prevSelTabId).removeClassName(mhpObj.options.tab_button_sel);
			}
			$('tab_' + mhpObj.selTabId).hide();
		}
		
		// selecting tab
		if (this.options.tabId != 'items' && this.options.tabId != 'colori') {
			$('tab_b_' + this.options.tabId).addClassName(mhpObj.options.tab_button_sel);
			$(mhpObj.options.tab_commands).show();
		} else {
			if (!mhpObj.checkLoggedIn()) return;
			$(mhpObj.options.tab_commands).hide();
		}
		$('tab_' + this.options.tabId).show();
		
		if (mhpObj.selTabId != 'items' && mhpObj.selTabId != 'colori') {
			mhpObj.prevSelTabId = mhpObj.selTabId;
		}
		mhpObj.selTabId = this.options.tabId;
	},
	
	/* updates the column width */
	/* to be called when adding or deleting columns */
	updateColumnWidth: function () {
		if (this.cols) {
			if (this.cols.size() <= 2) {
				$('tab_' + this.options.tabId).firstDescendant().className = 'twoColoumns';
			} else {
				$('tab_' + this.options.tabId).firstDescendant().className = 'threeColoumns';
			}
		}
	},
	
	/* creates a new column inside this tab */
	createColumn: function () {
		var newColId = mhpObj.getNextColumnId();
		var opts = $H({ colId: newColId, items: [] });
		
		// creating the column and updating settings
		var newColumn = new TabColumn(this, opts);
		this.options.cols.push(opts);
		mhpObj.settingsChanged();
		
		// updating references
		this.cols.push(newColumn);
		
		this.updateColumnWidth();
	}
};


/********************* 
***	Class Mhp 
**********************/
var Mhp = Class.create();
Mhp.prototype = {
	/* constructor */
	initialize: function (options) {
		// general settings
		this.options = options;
		
		// used to consolidate multiple changes into a single server update (-> false; changes...; -> true; save)
		this.skipSave = false;
		
		// currently selected tab id
		this.selTabId = null;
		
		// previously selected tab id
		this.prevSelTabId = null;	
		
		// save only when needed (useful if periodical save enabled)
		this.settingsModified = false;	
		
		// default user settings
		this.settings = $H(this.options.defaultSettings);
		
		this.tabs = $A([]);
		this.color = this.options.default_color;
		
		// counters
		this.nextTabId = 0;
		this.nextColumnId = 0;
		this.nextItemId = 0;
	},
	
	/* loads user settings from server */
	load: function () {
		//this.displayMessage(false, this.options.loading_msg, true);
	
		// items tab
		var itOpts = $H({ name: 'items', tabId: 'items', cols: [], no_rendering: true });
		var itemsTab = new Tab(itOpts);
		
		// colori tab
		var ctOpts = $H({ name: 'colori', tabId: 'colori', cols: [], no_rendering: true });
		var coloriTab = new Tab(ctOpts);
		
		// setting global event handlers
		Event.observe(this.options.new_tab_link, 'click', this.insertNewTab.bindAsEventListener(this), false);
		Event.observe(this.options.new_col_link, 'click', this.insertNewColumn.bindAsEventListener(this), false);
		Event.observe(this.options.del_tab_link, 'click', this.deleteSelectedTab.bindAsEventListener(this), false);
		Event.observe(this.options.del_col_link, 'click', this.deleteRightColumn.bindAsEventListener(this), false);
		Event.observe(this.options.rename_tab_link, 'click', this.renameSelectedTab.bindAsEventListener(this), false);
		Event.observe(this.options.sel_tab_items, 'click', itemsTab.selectTab.bindAsEventListener(itemsTab), false);
		Event.observe(this.options.sel_tab_colori, 'click', coloriTab.selectTab.bindAsEventListener(coloriTab), false);
		
		if (this.isLoggedIn()) {
			// donwload user settings
			new Ajax.Request(this.options.load_url, {
				encoding: 'UTF-8',
				parameters: { what: 'mhpSettings' },
				onSuccess: function (transport) {
					// update settings
					var savedMhpSettings = this.options.defaultSettings; 					
					try {
						eval(transport.responseText); // updates savedMhpSettings
					} catch (e) {
					}
					this.settings = $H({ tabs: [] });
					this.settings.merge(savedMhpSettings);
					
					// apply settings
					this.apply();
					this.onSettingsLoaded();
					
					this.displayMessage(false, null);
					
					// periodical saver
					if (this.options.save_interval > 0) {
						new PeriodicalExecuter(this.save.bind(this), this.options.save_interval);
						
						// save on unload
						Event.observe(window, 'unload', this.unloadSave.bind(this), false);
					}
				}.bind(this),
				onFailure: function (transport) {
					// error downloading user settings
					this.displayMessage(true, this.options.load_error_msg);
					this.apply();
				}.bind(this)
			});
		} else {
			// not logged in
			//this.displayMessage(false, this.options.not_logged_in_msg);
			this.apply();
		}
	},
	
	isLoggedIn: function () {
		return document.cookie.indexOf("CDSauthcookie") >= 0;
	},

	checkLoggedIn: function () {	
		if (!this.isLoggedIn()) {
			setTimeout('document.location = "' + this.options.login_url + '"', 0);
			return false;
		}
		return true;
	},
	
	displayMessage: function (error, message, noClean) {
		if (message == null) {
			$(this.options.status_bar).hide();
			return;
		}
		if (error) {
			$(this.options.status_bar).removeClassName('MessageINFO');
			$(this.options.status_bar).addClassName('MessageERROR');
		} else {
			$(this.options.status_bar).removeClassName('MessageERROR');
			$(this.options.status_bar).addClassName('MessageINFO');
		}
		$(this.options.status_bar).show();
		$(this.options.status_bar).innerHTML = message;
		
		if (!noClean) {
			var timestamp = new Date().getTime();
			this.msg_timestamp = timestamp;
			setTimeout('mhpObj.cleanMessage(' + timestamp + ')', this.options.msg_display_interval * 1000);
		}
	},
	
	cleanMessage: function (timestamp) { 
		if (this.msg_timestamp != timestamp) return;
		$(this.options.status_bar).hide();
	},
	
	/* applies user settings */
	apply: function () {
		// create tabs
		this.tabs = this.settings.tabs.collect(
			function (tabSetting) {
				return new Tab(tabSetting);
			}
		);
		
		// select first tab
		if (this.tabs.length > 0) {
			this.tabs[0].selectTab();
		}
		
		var tempTabs = this.settings.tabs;
		this.nextTabId = tempTabs.length > 0 ? (tempTabs.pluck("tabId").max() + 1) : 0;

		var tempColumns = tempTabs.pluck('cols').flatten();
		this.nextColumnId = tempColumns.length > 0 ? (tempColumns.pluck('colId').max() + 1) : 0;

		var tempItems = tempColumns.pluck('items').flatten();
		this.nextItemId = tempItems.length > 0 ? (tempItems.pluck('itemId').max() + 1) : 0;
		
		this.setColor(this.settings.color);
		
		$(this.options.tab_header).show();
		$(this.options.tab_commands).show();
		
		this.displayMessage(false);
	},
	
	onSettingsLoaded: function () {
		// adding an item if "add_rss_cat" parameter in request
		// addBlockCat<id_category> should be defined in page
		var queryParams = window.location.href.toQueryParams();
		
		var rssCat = queryParams.add_rss_cat; 
		var rssLink = queryParams.add_rss_link; 
		var rssTitle = queryParams.add_rss_title; 
		
		if (rssCat && rssCat != '') {
			// rss interno
			eval('var addBlock = addBlockCat' + queryParams.add_rss_cat);
			if (addBlock != undefined) {
				addBlock();
			}
		} else if (rssTitle && rssLink && rssTitle != '' && rssLink != '') {
			rssTitle = rssTitle.replace(/\+/g, ' ');
			this.addBlockItem('rss', rssTitle, rssLink, false);
		} 
	},
	
	/* save settings to server */
	save: function() {
		if (this.settingsModified == false) {
			return;
		}
		
		this.settingsModified = false;
		
		new Ajax.Request(this.options.save_url, {
			encoding: 'UTF-8',
			parameters: { what: 'mhpSettings', 
				value: 'savedMhpSettings = ' + this.settings.toJSON() + ';' },
			onSuccess: function (transport) {
				//this.displayMessage(false, "OK");
			}.bind(this),
			onFailure: function (transport) {
				this.displayMessage(true, this.options.save_error_msg);
				this.settingsModified = true; // re-enabling as saving failed
			}.bind(this)
		});		
	},
	
	/* called on document unload to save settings if periodical saving enabled*/
	unloadSave: function () {
		new Ajax.Request(this.options.save_url, {
			asynchronous: false,
			parameters: { what: 'mhpSettings',
				value: 'savedMhpSettings = ' + this.settings.toJSON() + ';' },
			onFailure: function (transport) {
				this.displayMessage(true, this.options.save_error_msg);
			}.bind(this)
		});		
	},

	/* handles any change in settings -> saves to server (if needed) */
	settingsChanged: function () {
		this.settingsModified = true;

		// periodical saving disabled -> save on server now
		if (this.options.save_interval <= 0) {
			if (!this.skipSave) { 
				this.save();
			}
		}
	},

	/* returns a fresh item id to be used for newly created item */
	getNextItemId: function () {		
		return this.nextItemId++;
	},
	
	/* returns a fresh column id to be used for newly created column */
	getNextColumnId: function () {
		return this.nextColumnId++;
	},
	
	/* returns a fresh tab id to be used for newly created tab */
	getNextTabId: function () {
		return this.nextTabId++;
	},
	
	/* inserts a new tab (from user request) */
	insertNewTab: function () {	
		if (!this.checkLoggedIn()) return;

		if (this.tabs.length >= this.options.max_tab_count) {
			this.displayMessage(true, "Il numero massimo di pagine \u00E8 " + this.options.max_tab_count);
			return;
		}
	
		// get tab name		
		/*var tabName = window.prompt("Inserire il nome della nuova pagina", "Nuova pagina");
		if (tabName == null || tabName == '') {
			return;
		}*/
		var tabName = this.options.default_tab_name;
		
		var newTabId = this.getNextTabId();
		var opts = $H({ name: tabName, tabId: newTabId, cols: [] });
		
		// creating the tab and updating settings
		var newTab = new Tab(opts);
		this.settings.tabs.push(opts);
		mhpObj.settingsChanged();
		
		// updating references
		this.tabs.push(newTab);
		
		// select newly created tab
		newTab.selectTab();
		
		return newTab;
		// hide name input form
		//$(this.options.new_tab_name).hide();
	},
	
	/* updates drag'n'drop info (i.e. who are the target containers?) */
	/* to be called when inserting new columns */
	updateSortables: function () {
		var sortables = $$('.' + this.options.tab_column); 
		
		sortables.each(function (sortable) {
			Sortable.create(sortable, { 
		        containment: sortables,
		        constraint: false,
		        dropOnEmpty: true,
		        tag: 'div',
		        only: this.options.block,
		        handle: this.options.block_handle,
		        hoverclass: this.options.block_hover,
		        
		        onChange: function (element) {
		        	this.draggedElement = element.id;
		        }.bind(this),
		        onUpdate: function (container) {
		        	this.updateColumnItems(container);
		        }.bind(this)
		    });
	    }.bind(this));
	},
	
	/* updates settings after drag'n'drop */
	updateColumnItems: function (colElm) {
		if (this.draggedElement == undefined) {
			// this function is called twice when drag'n'frop ends, preventing a second execution
			return;
		}
		var itemId = this.draggedElement.substring(5); // item_XXX
		
		// getting source column
		var srcCol = mhpObj.tabs.pluck('cols').flatten().pluck('items').flatten().find(function (item) {
			return item.options.itemId == itemId;
		}.bind(this)).col;
		
		// getting target column
		var trgCol = mhpObj.tabs.pluck('cols').flatten().find(function (currCol) {
			return $('col_' + currCol.options.colId).getElementsBySelector('div').pluck('id').member(this.draggedElement);
		}.bind(this));
		
		if (srcCol.options.colId != trgCol.options.colId) {
			// updating settings
			var temp = srcCol.options.items.partition(function (item) {
				return item.itemId == itemId;
			});
			trgCol.options.items.push(temp[0][0]);
			srcCol.options.items = temp[1];
			mhpObj.settingsChanged();

			// update references
			temp = srcCol.items.partition(function (item) {
				return item.options.itemId == itemId;
			});		
			var item = temp[0][0];
			item.col = trgCol;
			trgCol.items.push(item);
			srcCol.items = temp[1];
		}
		
		// reordering
		trgCol.options.items = trgCol.options.items.sortBy(function (item) {
			return $('item_' + item.itemId).previousSiblings().length;
		});
		
		this.draggedElement = undefined;
	},
	
	/* adds a block item to the previously selected tab (current is 'Items' tab) */
	/* creates a new tab if none was selected */
	/* adds to the first column */
	addBlockItem: function (type, title, link, local) {
		// finding a tab to add to
		var targetTab = null;
		if (this.prevSelTabId != null) {
			// adding to previously selected tab
			targetTab = this.tabs.find(function (tab) {
				return tab.options.tabId == this.prevSelTabId;
			}.bind(this));
		} else if (this.tabs.size() > 0) {
			// adding to first tab
			targetTab = this.tabs[0];	
		} else {
			// creating a tab
			targetTab = this.insertNewTab();
		}
		
		// finding a column to add to
		if (targetTab.cols.size() == 0) {
			// creating a new column
			targetTab.createColumn();
		}
		var targetCol = targetTab.cols[0];
	
		// creating the new block item
		var newItemId = this.getNextItemId();
		var itemOpts = $H({ type: type, itemId: newItemId, title: title, link: link, local: local });
		var newItem = new BlockItem(targetCol, itemOpts);
		
		// update settings
		targetCol.options.items.push(itemOpts);
		this.settingsChanged();
		
		// updating references
		targetCol.items.push(newItem); 
		
		// display message
		//var msg = this.options.item_added_msg_template.evaluate({ tabname: targetTab.options.name });
		//this.displayMessage(false, msg);
	},
	
	getSelectedTab: function () {
		var selectedTab = this.tabs.find(function (tab) {
			return tab.options.tabId == this.selTabId;
		}.bind(this));
		return selectedTab;
	},
	
	renameSelectedTab: function () {
		if (!this.checkLoggedIn()) return;

		var targetTab = this.getSelectedTab();
		if (targetTab != null) {
			$('span_tab_edit_' + targetTab.options.tabId).firstDescendant().value = targetTab.options.name;
			$('span_tab_' + targetTab.options.tabId).hide();
			$('span_tab_edit_' + targetTab.options.tabId).show();
			$('span_tab_edit_' + targetTab.options.tabId).firstDescendant().focus();
			//this.displayMessage(false, this.options.enter_to_confirm);
		}
	},
	
	deleteSelectedTab: function () {
		if (!this.checkLoggedIn()) return;

		if (this.selTabId == 'items') {
			return;
		}
		
		if (this.tabs.length <= this.options.min_tab_count) {
			tihs.displayMessage(true, "Il numero minimo di pagine \u00E8 " + this.options.min_tab_count);
			return;
		}
		
		var targetTab = this.getSelectedTab();
		if (targetTab != null) {
			var confirmed = window.confirm("Sei sicuro di voler eliminare la pagina e tutto il suo contenuto?");
			if (confirmed) {
				targetTab.deleteTab();
			}
		}
	},
	
	deleteRightColumn: function () {
		if (!this.checkLoggedIn()) return;

		if (this.selTabId == 'items') {
			return;
		}
		
		var targetTab = this.getSelectedTab();
		if (targetTab != null) {
			if (targetTab.cols.length <= this.options.min_column_count) {
				this.displayMessage(true, "Il numero minimo di colonne \u00E8 " + this.options.min_column_count);
				return;
			}
			var confirmed = window.confirm("Sei sicuro di voler eliminare la colonna di destra?");
			if (confirmed) {
				if (targetTab.cols.length > 1) {
					targetTab.cols.last().copyItemsTo(targetTab.cols[targetTab.cols.length - 2]);
				}
				targetTab.cols.last().deleteColumn();
			}
		}
	},
	
	insertNewColumn: function () {
		if (!this.checkLoggedIn()) return;
		
		if (this.selTabId == 'items') {
			return;
		}
		
		var targetTab = this.getSelectedTab();
		if (targetTab != null) {
			if (targetTab.cols.length >= this.options.max_column_count) {
				this.displayMessage(true, "Il numero massimo di colonne \u00E8 " + this.options.max_column_count);
				return;
			}
			targetTab.createColumn();
		}		
	},
	
	setColor: function (color) {
		if (!color || color == this.color) {
			return;
		}
		
		$$('.' + this.color).each(function (elm) {
			elm.removeClassName(this.color);
			elm.addClassName(color);
		}.bind(this));
		
		this.color = color;
		this.settings.color = color;
		this.settingsChanged();
		
		var targetTab = this.tabs.find(function (tab) {
			return tab.options.tabId == this.prevSelTabId;
		}.bind(this));
		if (targetTab) {
			targetTab.selectTab();
		}
	}
};

// Mhp.load <- window.onLoad
var mhpObj = new Mhp(options);
Event.observe(window, 'load', mhpObj.load.bindAsEventListener(mhpObj), false);

// preload immagini CSS per IE6
var isIE6 = document.uniqueID /*IE*/ && document.compatMode /*>=IE6*/ 
		&& !window.XMLHttpRequest /*<=IE6*/;
if (isIE6) {
	var cssImages = $A([
		'cornerMC_001_BottomLeft.png',
		'cornerMC_001_BottomRight.png',
		'cornerMC_001_TopLeft.png',
		'cornerMC_001_TopRight.png',
		'tabMC_001_left.png',
		'tabMC_001_right.png',
		'cornerMC_002_BottomLeft.png',
		'cornerMC_002_BottomRight.png',
		'cornerMC_002_TopLeft.png',
		'cornerMC_002_TopRight.png',
		'tabMC_002_left.png',
		'tabMC_002_right.png',
		'cornerMC_003_BottomLeft.png',
		'cornerMC_003_BottomRight.png',
		'cornerMC_003_TopLeft.png',
		'cornerMC_003_TopRight.png',
		'tabMC_003_left.png',
		'tabMC_003_right.png',
		'cornerMC_004_BottomLeft.png',
		'cornerMC_004_BottomRight.png',
		'cornerMC_004_TopLeft.png',
		'cornerMC_004_TopRight.png',
		'tabMC_004_left.png',
		'tabMC_004_right.png',
		'cornerMC_005_BottomLeft.png',
		'cornerMC_005_BottomRight.png',
		'cornerMC_005_TopLeft.png',
		'cornerMC_005_TopRight.png',
		'tabMC_005_left.png',
		'tabMC_005_right.png',
		'cornerMC_006_BottomLeft.png',
		'cornerMC_006_BottomRight.png',
		'cornerMC_006_TopLeft.png',
		'cornerMC_006_TopRight.png',
		'tabMC_006_left.png',
		'tabMC_006_right.png'
	]);
	cssImages.each(function (image) {
		new Image().src = image;
	});
}
