var s = null;

window.addEvent('domready', function() {
	init();
	window.fireEvent('siteready');
});

window.addEvent('siteready', function() {
	$$('.js').setStyle('visibility', 'visible');
});

window.addEvent('unload', function() {
	uninit();
} );

function init()
{
	// initialize map engine
	s = new siteEngine();
	s.init();
	s.initBlock( s.body );
	
	document.addEvent('updateblock', function(obj) {
		s.initBlock( obj );
	} );
	
	document.addEvent('removeblock', function(obj) {
		s.removeBlock( obj );
	} );
}

function uninit()
{
	s = null;
}

function siteEngine()
{
	this.init = function()
	{
		this.plugins = new Array();
		this.widgets = new Array();
		this.body = document.getElement('body');
		this.body.importProps();
		window.fireEvent('resize');
		
		document.addEvent('mousemove', function(e) {
			this.mouse = { 'x': e.page.x, 'y': e.page.y };
		}.bind(this) );
		
		if ( (Browser.Engine.name == 'trident') && (Browser.Engine.version < 5) && (this.body.ie6redirect) )
			self.location.href = this.body.ie6redirect;
	},
	
	this.refresh = function( )
	{
		var refresh = document.getElements('.refresh');
		for (var i=0; i<refresh.length; i++)
		{
			refresh[i].importProps();
			this.execBlock( refresh[i] );
		}
	},
	
	this.refreshBlock = function( id )
	{
		var obj = $(id);
		obj.importProps();
		this.execBlock( obj );
	},
	
	this.initBlock = function( obj )
	{
		var objs = obj.getElements('.exec');
		objs[objs.length] = obj;
		for (var i=0; i<objs.length; i++)
		{
			objs[i].importProps();
			if (objs[i].hasClass('save'))			this.addSave(objs[i]);
			if (objs[i].hasClass('update'))			this.addUpdate(objs[i]);
			if (objs[i].hasClass('widget'))			this.addWidget(objs[i]);
			if (objs[i].hasClass('ratings'))		this.addRating(objs[i]);
			if (objs[i].hasClass('rating-star'))	this.addRatingValue(objs[i]);
			if (objs[i].hasClass('scroller'))		this.addScroller(objs[i]);
			if (objs[i].hasClass('popup'))			this.addPopup(objs[i]);
			if (objs[i].hasClass('pager'))			this.addPager(objs[i]);
			if (objs[i].hasClass('onfly'))			this.addOnFly(objs[i]);
			
			if (objs[i].hasClass('delayed'))		this.addDelayed(objs[i]);
			if (objs[i].hasClass('relabel'))		this.addRelabel(objs[i]);
			if (objs[i].hasClass('radio-group'))	this.addRadioGroup(objs[i]);
			if (objs[i].hasClass('change-input'))	this.addChangeInput(objs[i]);
			if (objs[i].hasClass('put-input'))		this.addPutInput(objs[i]);
			if (objs[i].hasClass('range'))			this.addRangeSlider(objs[i]);
			if (objs[i].hasClass('sortable'))		this.addSortable(objs[i]);
			if (objs[i].hasClass('thumbslide'))		this.addThumbSlide(objs[i]);
			if (objs[i].hasClass('tip'))			this.addTip(objs[i]);
			if (objs[i].hasClass('gallery'))		this.addGallery(objs[i]);
			if (objs[i].hasClass('clock'))			this.addClock(objs[i]);
			
			// SHOW/HIDE
			if (objs[i].hasClass('tab'))			this.addTab(objs[i]);
			if (objs[i].hasClass('expand'))			this.addExpand(objs[i]);
			if (objs[i].hasClass('accordion'))		this.addAccordion(objs[i]);
			
			// FX
			if (objs[i].hasClass('highlight'))		this.highlight(objs[i]);
			
			// last
			if (objs[i].hasClass('question'))		this.addConfirm(objs[i]);
		}
	},
	
	this.removeBlock = function( obj )
	{
		olds = obj.getElements('.exec')
		for (var i=0; i<olds.length; i++)
			olds[i].fireEvent('remove');
	},
	
	this.addConfirm = function( obj )
	{
		obj.addEvent('click', function(obj) {
			if (!obj.continueClick()) return false;
		}.pass(obj, this) );
	},
	
	this.login = function( post )
	{
		this.popupMng.addEvent('onUpdate', function() { document.fireEvent('updateblock', this.popupMng.content); }.bind(this) );
		this.popupMng.fromElement( $('enter'), { 'url': $('enter').getURL() } );
	},
	
	this.initPopup = function( )
	{
		SqueezeBox.initialize({
			ajaxOptions: {
				method: 'get'
			}
		});
		this.popupMng = SqueezeBox;
	},
	
	this.initMouseTip = function( )
	{
		this.mouseTip = new Element('div', {'class': 'mousetip'}).setStyles({'position':'absolute', 'z-index': 100000}).inject(this.body);
		this.mouseTip.fx = new Fx.Tween(this.mouseTip, { 'property': 'opacity', 'link': 'cancel' } ).set(0);
		this.plugins['mousetip'] = true;
	},
	
	this.execBlock = function( obj )
	{
		this.addMouseTip( obj.loadmsg || 'Caricamento...', 0 );
		var url = obj.getURL();
		obj.xhr = new Request( {
			url: url
		} ).send();
		obj.xhr.addEvent('onComplete', function(obj) {
			var response = obj.xhr.response.text
			if (this.parseResponse(response))
				obj.setContent( response );
			this.closeMouseTip( );
		}.pass(obj, this) );
	},
	
	this.execForm = function( obj )
	{
		this.addMouseTip( obj.loadmsg || 'Caricamento...', 0 );
		var url = obj.getURL();
		if (obj.xhr)
			obj.xhr.cancel();
		obj.xhr = new Request( {
			'url': url,
			'data': obj.getQueryString(),
			'method': (obj.get('method') || 'post')
		} ).send();
		obj.xhr.addEvent('onComplete', this.parseSave.pass(obj, this) );
		return false;
	},
	
	this.addSave = function( obj )
	{
		if (obj.unload)	
			window.addEvent('beforeunload', function(obj) { if (!confirm(obj.unload)) return true; }.pass(obj, this) );
		obj.addEvent('submit', this.execForm.pass(obj, this) );
		//obj.addEvent('submit', function(e) { new Event(e).stop(); return false; } );
	},
	
	this.parseSave = function( obj )
	{
		var response = obj.xhr.response.text;
		if (this.parseResponse(response))
		{
			switch (obj.targetEl)
			{
				case 'popup':
					this.popupMng.setContent( 'string', response );
				break;
				case 'redirect':
					self.location.href = obj.redirect;
				break;
				case 'none':
				break;
				default:
					$(obj.targetEl).setContent(response);
				break;
			}
		}
		this.closeMouseTip( );
	},
	
	this.parseResponse = function( text )
	{
		var trigger = '[goto:';
		if (text.indexOf(trigger) !== -1)
		{
			self.location.href = text.substr( trigger.length, text.length - trigger.length - 1 );
			return false;
		}
		if (text == '[login]')
		{
			this.login();
			return false;
		}
		return true;
	},
	
	this.addUpdate = function( obj )
	{
		if (obj.get('tag') == 'form')
			this.updateFormDelay(obj);
		if (obj.get('tag') == 'select')
		{
			obj.addEvent('change', function(event) {
				new Event(event).stop();
				this.feedSelect(obj);
				return false;
			}.pass(obj, this) );
		}
	},
	
	this.updateFormDelay = function( obj )
	{
		var inputs = obj.getElements('input,select,textarea');
		var autosave = obj.getElement('.autosave');
		var func = function(obj)
		{
			if (obj.autosave)
				if (!obj.autosave.get('checked'))
					return true;
			
			if (obj.updateTimer)
				$clear( obj.updateTimer );
			obj.updateTimer = this.execForm.delay(obj.delay, this, obj);
			//return false;
		}.pass(obj, this);
		for (var i=0; i<inputs.length; i++)
		{
			if ( (!inputs[i].hasClass('no-update')) && (inputs[i].get('type') != 'file') )
			{		
				inputs[i].addEvent('change', func);
				inputs[i].addEvent('keypress', func);
			}
		}
	},
	
	this.addWidget = function( obj )
	{
		obj.widget = new Widget( obj, obj.name, obj.get, obj.functions );
		obj.widget.addEvent('login', function( obj ) {
			this.login();
		}.pass(obj, this) );
		obj.widget.addEvent('added', function( obj ) {
			this.addMouseTip('Questo modulo è stato aggiunto al tuo pannello!', 1);
		}.pass(obj, this) );
		obj.widget.addEvent('removed', function( obj ) {
			this.addMouseTip('Questo modulo è stato rimosso dal tuo pannello!', 1);
		}.pass(obj, this) );
		this.widgets[ this.widgets.length ] = obj.widget;
	},
	
	this.addRating = function( obj )
	{
		if (!this.plugins['ratings'])
		{
			this.plugins['ratings'] = new Asset.javascript("includes/libraries/ratings.js");
			this.plugins['ratings'].addEvent('load', this.addRatingBlock.pass(obj, this) );
		}
		else
			this.addRatingBlock( obj );
	},
	
	this.addRatingBlock = function( obj )
	{
		obj.ratings = new Ratings( obj );
	},
	
	this.addRatingValue = function( obj )
	{
		obj.thisHTML = obj.get('html');
		obj.empty();
		obj.container = new Element('div', {'class': 'rating-container'}).set('title', obj.thisHTML).inject( obj );
		obj.size = obj.container.getSize();
		if (obj.size.x == 0) obj.size.x = 120; // avoid problems with width when parent layer is hidden
		obj.stars = new Element('div', {'class': 'rating-stars'}).setStyles({'width': obj.size.x * obj.value / obj.base}).set('html', '&nbsp').inject( obj.container );
	},
	
	this.addScroller = function( obj )
	{
		obj.scroll = $(obj.scrollEl);
		obj.target = $(obj.targetEl);
		if (!obj.scroll.fx)
		{
			obj.scroll.fx = new Fx.Scroll(obj.scroll, {
										wait: false,
										duration: 500,
										offset: {'x': 0, 'y':0},
										transition: Fx.Transitions.Quad.easeInOut
									});
		}
		obj.addEvent('click', function(obj) {
			obj.scroll.fx.toElement(obj.targetEl);
		}.pass(obj, this) );
		obj.addEvent('click', function(event) {
			event = new Event(event).stop();
		} );
	},
	
	this.addPopup = function( obj )
	{
		if (obj.blank == 'true')
		{
			obj.addEvent('click', function(obj) {
				window.open( obj.getURL(), 'new', 'menubar=no,width='+obj.width+',height='+obj.height+',location=no,resizable=no,scrollbars=yes,status=no' );
			}.pass(obj, this) );
		}
		else
		{
			if (!this.plugins['popup'])
			{
				this.plugins['popup'] = new Asset.javascript("includes/libraries/popup.js", { 'onload': this.initPopup.bind(this) });
				//this.plugins['popup'].addEvent('onComplete', this.initPopup.bind(this) );
			}
			obj.addEvent('click', function(obj) {
				//alert(obj.getURL());
				var options = {
					url: obj.getURL(),
					size: { x: (obj.width || 550),
							y: (obj.height || 500) }
				}
				if (!obj.continueClick()) return false;
				this.popupMng.addEvent('onUpdate', function() { document.fireEvent('updateblock', this.popupMng.content); }.bind(this) );
				this.popupMng.fromElement(obj, options);
			}.pass(obj, this) );
		}
		obj.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	this.addMouseTip = function( content, closeAfter )
	{
		if (!this.plugins['mousetip'])
			this.initMouseTip();
		
		this.mouseTip.fn = function(e) {
			this.mouseTip.setStyles({'display': 'block', 'left': this.mouse.x, 'top': this.mouse.y});
		}.bind(this)
		
		if (this.mouseTip.status)
			document.removeEvent('mousemove', this.mouseTip.fn);
		document.addEvent('mousemove', this.mouseTip.fn );
		this.mouseTip.status = true;
		this.mouseTip.setStyles({'left': this.mouse.x, 'top': this.mouse.y});
		this.mouseTip.set('html', content);
		this.mouseTip.fx.start(1);
		$clear(this.mouseTip.delayTimer);
		if (closeAfter)
			this.mouseTip.delayTimer = this.closeMouseTip.delay(2000, this);
	},
	
	this.closeMouseTip = function()
	{
		this.mouseTip.fx.start(0).chain( function() {
			document.removeEvent('mousemove', this.mouseTip.fn);
			this.mouseTip.status = false;
			this.mouseTip.setStyle('display', 'none');
		}.bind(this) );
	},
	
	this.addExpand = function( obj )
	{
		obj.status = false;
		obj.toggler = obj.getElement('.expand-toggler');
		obj.block = obj.getElement('.expand-block').setStyle('overflow', 'hidden');
		obj.block.fx = new Fx.Tween( obj.block, { 'property': 'height', 'link': 'cancel'} ).set(0);
		if (obj.show == 'true') this.openExpand(obj); else this.closeExpand(obj);
		obj.toggler.addEvent('click', function(obj) {
			if (!obj.continueClick()) return false;
			if (obj.status)
				this.closeExpand( obj );
			else
				this.openExpand( obj );
		}.pass(obj, this) );
		if (obj.toggler.get('tag') == 'a')
			obj.toggler.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	this.openExpand = function( obj )
	{
		obj.block.fx.start( obj.block['scrollHeight'] ).chain( function(block) { block.setStyle('height', 'auto'); }.pass(obj.block) );
		obj.toggler.addClass('expand-open');
		obj.status = true;
	},
	
	this.closeExpand = function( obj )
	{
		obj.block.fx.set(obj.block['scrollHeight']).start( 1 );
		obj.toggler.removeClass('expand-open');
		obj.status = false;
	},
	
	this.addTab = function( obj )
	{
		if (obj.hasClass('tab-selected'))
			this.openTab( obj );
		
		switch (obj.load)
		{
			case 'url':
				obj.addEvent('click', this.openURLTab.pass(obj, this) );
				obj.addEvent('click', function(e) { new Event(e).stop(); } );
			break;
			default:
				obj.addEvent('click', this.openTab.pass([obj,null], this) );
				//obj.addEvent('click', function(e) { new Event(e).stop(); } );
			break;
		}
	},
	
	this.removeTab = function( obj )
	{
		if (!obj.continueClick()) return false;
		if (obj.hasClass('tab-selected'))
		{
			var prevtab = null;
			var tabs = obj.block.getElements('.' + obj.tabCSS);
			for (var i=0; i<tabs.length; i++)
			{
				if (obj == tabs[i])
					break;
				prevtab = tabs[i];
			}
			this.openTab( prevtab );
		}
		obj.remove();
	}
	
	this.addPager = function( obj )
	{
		obj.pager = new Pager( obj, {
			target: obj.targetEl,
			urlproto: obj.urlproto,
			current: obj.current,
			pages: obj.pages,
			total: obj.total
		} );
	},
	
	this.addOnFly = function( obj )
	{
		obj.addEvent('click', function(obj) {
			if (!obj.continueClick()) return false;
			this.addMouseTip( obj.loadmsg || 'Caricamento...', 0 );
			var url = obj.getURL();
			var options = { url: url, method: 'post' }
			if (obj.post)
			{
				options.data = $(obj.post).toQueryString();
			}
			obj.xhr = new Request( options ).send();
			obj.xhr.addEvent('onComplete', function(obj) {
				var response = obj.xhr.response.text;
				if (obj.targetEl == 'popup')
					this.popupMng.setContent( 'string', response );
				else
				{
					if (obj.targetEl == '[same]')
						var target = obj;
					else
						var target = $(obj.targetEl);
					if (obj.transition)
						target.transition = obj.transition;
					target.setContent( response );
				}
				this.closeMouseTip( );
				obj.fireEvent('success');
			}.pass(obj, this) );
		}.pass(obj, this) );
		obj.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	this.addDelayed = function( obj )
	{
		if (!obj.loadedDelay)
		{
			var url = obj.getURL();
			obj.xhr = new Request( {
				url: url
			} ).send();
			obj.xhr.addEvent('onComplete', function(obj) {
				obj.loadedDelay = true;
				obj.setContent( obj.xhr.response.text );
			}.pass(obj, this) );
		}
	},
	
	/// TABS ///
	this.openURLTab = function( obj )
	{
		if (!obj.continueClick()) return false;
		//obj.addClass('loading');
		var url = obj.getURL();
		obj.xhr = new Request( {
			url: url
		} ).send();
		obj.xhr.addEvent('onComplete', function(obj) {
			this.openTab( obj, obj.xhr.response.text );
		}.pass(obj, this) );
	},
	
	this.openTab = function( obj, html )
	{
		if (!obj.continueClick()) return false;
		var index = 0;
		//obj.removeClass('loading');
		obj.block = $(obj.tabBlock);
		
		var tabs = obj.block.getElements('li.' + obj.tabCSS);
		if (obj.pageCSS)
			var pages = obj.block.getElements('.' + obj.pageCSS);
		if (obj.pageTarget)
			var page = $(obj.pageTarget);
		for (var i=0; i<tabs.length; i++)
		{
			if (tabs[i] == obj)
			{
				tabs[i].addClass('tab-selected');
				index = i;
			}
			else
			{
				tabs[i].removeClass('tab-selected');
			}
		}
		if (obj.pageCSS)
		{
			for (var i=0; i<pages.length; i++)
			{
				if (i == index)
				{
					pages[i].setStyle('display', 'block');
				}
				else
				{
					pages[i].setStyle('display', 'none');
				}
			}
		}
		if (obj.pageTarget)
		{
			if (html)
			{
				page.setContent(html);
			}
		}
	},
	
	this.addRelabel = function( obj )
	{
		obj.set('value', obj.label);
		
		obj.addEvent('focus', function() {
			if (obj.get('value') == obj.label)
				obj.set('value', '');
		}.pass(obj, this) );
		
		obj.addEvent('blur', function() {
			if (obj.get('value') == '')
				obj.set('value', obj.label);
		}.pass(obj, this) );
	},
	
	this.addRadioGroup = function( obj )
	{
		var radios = obj.getElements('.'+obj.childs);
		var labels = obj.getElements('label');
		for (var i=0; i<radios.length; i++)
		{
			radios[i].importProps();
			if (!radios[i].css)
				radios[i].css = 'radio';
			// found label
			for (var j=0; j<labels.length; j++)
			{
				if ( radios[i].get('id') == labels[j].get('for') )
					radios[i].label = labels[j];
			}

			radios[i].setStyles( { 'display': 'none' } );
			radios[i].replace = new Element('a', {'href': 'javascript:;', 'class': radios[i].css }).set('html', '<span>&nbsp;</span>').inject(radios[i], 'after');
			this.switchRadio( radios[i], radios[i].get('checked') );
			if (radios[i].get('disabled'))
				radios[i].replace.addClass(radios[i].css + '-disabled');
			radios[i].replace.addEvent('click', function(obj) {
				if (!obj.disabled)
				{
					obj.click();
					obj.fireEvent('change');
				}
			}.pass(radios[i], this ) );
			if (obj.selection == 'multiple')
			{
				radios[i].addEvent('change', function(obj) {
					this.switchRadio( obj, obj.get('checked') );
				}.pass(radios[i], this ) );
			}
			else
			{
				radios[i].addEvent('change', function(obj, index) {
					for (var i=0; i<radios.length; i++)
					{
						this.switchRadio( radios[i], (i == index) && (radios[i].get('checked')) );
           			}
				}.pass([radios, i], this ) );
			}
			if (radios[i].label)
			{
				radios[i].label.addEvents( {
					'mouseenter': function(obj) { obj.replace.addClass(obj.css + '-over'); }.pass(radios[i], this),
					'mouseleave': function(obj) { obj.replace.removeClass(obj.css + '-over'); }.pass(radios[i], this)
				} );
			}
		}
	},
	
	this.switchRadio = function( obj, status )
	{
		if (status)
		{
			obj.replace.addClass(obj.css + '-selected');
			if (obj.label)
				obj.label.addClass(obj.css + '-selected');
		}
		else
		{
			obj.replace.removeClass(obj.css + '-selected');
			if (obj.label)
				obj.label.removeClass(obj.css + '-selected');
		}
	},
	
	this.addChangeInput = function( obj )
	{
		obj.addEvent('click', function(obj) {
			obj.input = $(obj.input);
			obj.input.set('value', obj.set);
			if (obj.forcesubmit == 'true')
			{
				obj.getParent('form').removeEvents('submit');
				obj.getParent('form').submit();
			}
			else
				obj.input.fireEvent('change');
		}.pass(obj,this) );
	},
	
	this.addPutInput = function( obj )
	{
		obj.original_url = obj.getURL();
		this.parseInput(obj);
		obj.addEvent('click', this.parseInput.pass(obj, this) );
		obj.addEvent('preload', this.parseInput.pass(obj, this) );
	},
	
	this.parseInput = function( obj )
	{
		var url = obj.original_url;
		var trigger = '[input,';
		var indend = 0;
		var inputnames = [];
		for (var i=0; i<url.split(trigger).length; i++)
		{
			var indstart	= url.indexOf(trigger, indend);
			var indend		= url.indexOf(']', indstart);
			if (indstart !== -1)
			{
				inputnames[inputnames.length] = url.substring(indstart + trigger.length, indend);
			}
		}
		for (var i=0; i<inputnames.length; i++)
		{
			url = url.replace( '[input,'+inputnames[i]+']', $(inputnames[i]).get('value') );
		}
		if (obj.tagName == 'DIV')
			obj.urlproto = url;
		else
			obj.set('href', url);
	},
	
	this.highlight = function( obj )
	{
		obj.hlFx = new Fx.Tween(obj, { 'property': 'opacity', 'wait': false, 'duration': 400, 'fps': 100}).set(.8);
		obj.addEvents( {
			'mouseenter': function(obj) {
				obj.hlFx.start(1);
			}.pass(obj,this),
			'mouseleave': function(obj) {
				obj.hlFx.start(.8);
			}.pass(obj,this)
		} );
	}
	
	this.addRangeSlider = function( obj )
	{
		if (!this.plugins['rangeslider'])
		{
			this.plugins['rangeslider'] = new Asset.javascript("includes/libraries/range.js", { 'onload': this.addRangeSlider.pass(obj, this) } );
			return false;
		}
		// saving inputs
		obj.inputFrom = obj.getElement('.from');
		obj.inputTo = obj.getElement('.to');
		var fromValue = parseInt(obj.inputFrom.get('value'));
		var toValue = parseInt(obj.inputTo.get('value'));
		obj.slider = new Element('div', {'class': 'range-slider'} ).inject(obj);
		obj.knobLeft = new Element('div', {'class': 'range-knob knob-left'} ).inject(obj.slider);
		obj.knobRight = new Element('div', {'class': 'range-knob knob-right'} ).inject(obj.slider);
		obj.rangeSlider = new RangeSlider(obj.slider, obj.knobLeft, obj.knobRight, {
			steps: parseInt(obj.steps),
			minValue: parseInt(obj.min),
			maxValue: parseInt(obj.max)
		}).set( { from: fromValue, to: toValue } );
		obj.rangeSlider.addEvent('onChange', function(step) {
			this.inputFrom.set('value', step.from);
			this.inputTo.set('value', step.to);
			if (!this.disabled)
			{
				this.inputFrom.fireEvent('change', '');
				this.inputTo.fireEvent('change', '');
			}
		}.bind(obj) );
		// actions...
		obj.inputFrom.addEvent('change', function()
		{
			obj.rangeSlider.setFrom( parseInt(this.getProperty('value')) );
		} );
		obj.inputTo.addEvent('change', function()
		{
			obj.rangeSlider.setTo( parseInt(this.getProperty('value')) );
		} );
	}
	
	this.addSortable = function( obj )
	{
		if (obj.sortable)
			obj.sortable = null;
		obj.sortable = new Sortables( obj.getElements('.' + obj.list), {
			handle: '.' + obj.handle,
			constrain: false,
			//clone: true,
    		revert: { duration: 500, transition: 'bounce:out' },
			onComplete: this.parseOrder.pass(obj,this)
		});
	}
	
	this.parseOrder = function( obj )
	{
		var inputs = obj.getElements('.' + obj.input);
		for (var i=0; i<inputs.length; i++)
		{
			inputs[i].set('value', i);
			inputs[i].fireEvent('change');
		}
	}
	
	this.addThumbSlide = function( obj )
	{
		if (obj.total > 1)
		{
			var params = { total: obj.total }
			if (obj.id)
			{
				var proto = '';
				var pt = obj.getProperty('src').split("/");
				for (var i=0; i<pt.length-1; i++)
				{
					proto += pt[i] + '/';
				}
				proto += obj.id + '_[num].jpg';
				params.proto = proto;
			}
			if (obj.files)
			{
				params.files = obj.files.split(',');
			}
			obj.thumbslide = new Thumbchange( obj, params );
			obj.addEvent('click', function(event) {
				new Event(event).stop();
				this.thumbslide.start();
				return false;
			} );
			/*obj.addEvent('mouseleave', function(event) {
				new Event(event).stop();
				this.thumbslide.stop();
				return false;
			} );*/
		}
	},
	
	this.addAccordion = function( obj )
	{
		var togglers = obj.getElements('.toggler');
		var blocks = obj.getElements('.block');
		obj.accordion = new Accordion(togglers, blocks, {
			display: null,
			opacity: true,
			alwaysHide: true
		} );
		obj.accordion.addEvents( {
			'onActive': function(toggler,block) {
				toggler.addClass('toggler-selected');
				block.addClass('block-selected');
			},
			'onBackground': function(toggler,block) {
				toggler.removeClass('toggler-selected');
				block.removeClass('block-selected');
			}
		} )
		if ( (togglers.length > 0) && (obj.getElement('.selected')) )
		{
			var found = 0;
			for (var i=0; i<togglers.length; i++)
				if (togglers[i].hasClass('selected'))
					var found = i;
			togglers[found].addClass('toggler-selected');
			obj.accordion.display( found );
		}
	},
	
	this.addTip = function( obj )
	{
		obj.addEvent('click', function(obj) {
			this.addMouseTip( obj.get('title'), obj.delay || 2000 )
		}.pass(obj, this) );
	},
	
	this.addGallery = function( obj )
	{
		obj.main = obj.getElement('.photo-main')
		obj.mainImg = obj.getElement('.photo-main img');
		obj.mainCaption = obj.getElement('.photo-main-desc');
		obj.scroller = obj.getElement('.photo-scroller');
		if (obj.scroller)
		{
			obj.slide = obj.getElement('.photo-slide').setStyles({'width': obj.totalWidth});
			obj.fx = new Fx.Tween(obj.slide, {'property': 'margin-left', 'link': 'cancel', 'duration': 1000, 'fps': 50, 'transition': Fx.Transitions.Expo.easeOut });
			obj.thumbs = obj.getElements('.photo-thumb');
			obj.screenWidth = obj.scroller.getSize().x - 50;
			obj.scroller.setStyle('width', obj.screenWidth);
			obj.totalWidth = obj.thumbs.length * (obj.thumbs[0].getSize().x);
		
		/*
		obj.mainImg.fx = new Fx.Tween(obj.mainImg, {'property': 'width'});
		obj.mainImg.addEvent('dblclick', function(obj) {
			obj.mainImg.fx.start( parseInt(obj.mainImg.getStyle('width')) + 200 );
		}.pass(obj, this) );
		obj.mainImg.makeDraggable( {
			//'container': obj.getElement('.photo-main'),
			//'overflown': obj.getElement('.photo-main')
		} );
		*/

			if (obj.totalWidth > obj.screenWidth)
				this.addGalleryNavigation(obj);
			
			for (var i=0; i<obj.thumbs.length; i++)
			{
				obj.thumbs[i].mode = obj.gallerymode;
				this.parseThumbGallery( obj, i );
			}
		}
	},
	
	this.addGalleryNavigation = function( obj )
	{
		obj.prev = new Element('a', {'href': 'javascript:;', 'html': '<span>avanti</span>', 'class': 'photo-prev photo-nav-disabled'}).inject( obj.scroller, 'before' );
		obj.next = new Element('a', {'href': 'javascript:;', 'html': '<span>indietro</span>', 'class': 'photo-next'}).inject( obj.scroller, 'before' );
		obj.prev.addEvent('click', function(obj) {
			this.navigateGallery( obj, '+' );
		}.pass(obj, this) );
		obj.next.addEvent('click', function(obj) {
			this.navigateGallery( obj, '-' );
		}.pass(obj, this) );
	},
	
	this.navigateGallery = function( obj, sign )
	{
		var position = parseInt( obj.slide.getStyle('margin-left') );
		var maxLeft = - (obj.totalWidth - obj.screenWidth);
		if (sign == '-') position -= obj.screenWidth; else position += obj.screenWidth;
		position = position.limit(maxLeft, 0);
		obj.fx.start( position );
		if (position == 0) obj.prev.addClass('photo-nav-disabled'); else obj.prev.removeClass('photo-nav-disabled');
		if (position == maxLeft) obj.next.addClass('photo-nav-disabled'); else obj.next.removeClass('photo-nav-disabled');
	},
	
	this.goToThumb = function( obj, i )
	{
		//var position = parseInt( obj.slide.getStyle('margin-left') );
		var position = - (obj.thumbs[0].getSize().x * i);
		var maxLeft = - (obj.totalWidth - obj.screenWidth);
		position = position.limit(maxLeft, 0);
		obj.fx.start( position );
	},
	
	this.parseThumbGallery = function( obj, i )
	{
		var thumb = obj.thumbs[i];
		thumb.importProps();
		thumb.link = thumb.getElement('a');
		thumb.thumb = thumb.getElement('img');
		thumb.link.addEvent('click', this.showImageGallery.pass([obj, i, true], this) );
		thumb.link.addEvent('click', function(e) { new Event(e).stop(); } );
		
		thumb.addEvent('selected', function(obj,i) { this.goToThumb(obj,i); this.showImageGallery(obj, i, false) }.pass([obj, i], this) );
	},
	
	this.showImageGallery = function( obj, i, selectpoi )
	{
		var thumb = obj.thumbs[i];
		switch (obj.mode)
		{
			default:
			case 'normal':
				obj.main.loading(1);
				obj.mainImg.addEvent('load', function(obj) { obj.mainImg.removeEvents('load'); obj.main.loading(0); }.pass(obj, this) );
				obj.main.getElement('a').set('href', thumb.link.get('rel'));
				obj.mainImg.set('src', thumb.link.get('href') );
				if (obj.mainCaption)
				{
					if (thumb.source == 'panoramio') {  obj.mainCaption.getElement('.photo-main-desc-source').set('href', thumb.gotolink); obj.mainCaption.getElement('.photo-main-desc-source').removeClass('ghost'); } else obj.mainCaption.getElement('.photo-main-desc-source').addClass('ghost');
					obj.mainCaption.getElement('span').set('html', '<strong>'+thumb.link.get('title')+'</strong> di <a href="'+thumb.authorlink+'">'+thumb.author+'</a>');
				}
				
				if (thumb.poi && selectpoi)
					thumb.poi.select( );
			break;
			
			case 'marker':
			case 'bottom':
				if (obj.mode == 'bottom')
				{			
					var size = obj.getSize();
					var pos = obj.getPosition();
				}
				if (obj.mode == 'marker')
				{
					var size = thumb.poi.getMain()._el.getSize();
					var pos = thumb.poi.getMain()._el.getPosition();
					pos.y -= (size.y / 2) - (thumb.poi.marker._img.getSize().y / 2);
				}
				
				if (!this.galleryDiv)
				{
					this.fxOptions = { 'link': 'cancel', 'duration': 'long', 'transition': Fx.Transitions.Sine.easeOut }
					this.galleryDiv = new Element('div', {'class': 'gallery-image'}).setStyles({'z-index': 10000, 'position':'absolute','left': pos.x + (size.x / 2) - (obj.width / 2), 'top': pos.y - obj.height - 100}).inject(this.body, 'top');
					this.galleryDiv.fx = new Fx.Morph(this.galleryDiv, this.fxOptions ).start({'opacity': 0});
					this.galleryImg = new Element('img').inject( this.galleryDiv );
					this.galleryImg.fx = new Fx.Morph(this.galleryImg, this.fxOptions );
					this.galleryImg.addEvent('load', function() {
						this.galleryImg.setStyle('display', 'block');
					}.bind(this) );
					this.galleryCaption = new Element('div', {'class': 'gallery-caption'}).setStyles({'z-index': 100, 'position':'absolute', 'left': 0, 'bottom': 0}).inject(this.galleryDiv);
					this.galleryCaption.span = new Element('span').inject( this.galleryCaption );
					this.galleryCaption.fx = new Fx.Morph(this.galleryCaption, this.fxOptions );
					this.galleryClose = new Element('a', {'href': 'javascript:;', 'class': 'gallery-close'}).setStyles({'float': 'right'}).set('html', '<span>x</span>').inject( this.galleryCaption, 'top');
					this.galleryClose.addEvent('click', function() {
						this.galleryDiv.fx.start({ 'opacity': 0 });
					}.bind(this) );
				}
				
				this.galleryImg.setStyle('display', 'none');
				this.galleryImg.set('src', obj.link.get('href') );
				this.galleryCaption.span.set('html', obj.link.get('title') );
				this.galleryDiv.fx.start({
					'width': obj.width, 
		   			'height': obj.height,
					'left': pos.x + (size.x / 2) - (obj.width / 2),
					//'top': pos.y - obj.height,
					'top': pos.y + size.y,
					'opacity': 1
				});
				this.galleryImg.fx.start({
					'width': obj.width, 
		   			'height': obj.height
				});
				this.galleryCaption.fx.start({
					'width': obj.width
				});
				
				if (thumb.poi && selectpoi)
					thumb.poi.select( );
			break;
		}
	},
	
	this.addClock = function( obj )
	{
		obj.addSeconds = 0;
		obj.d = new Date();
		obj.d.setTime(obj.time * 1000);
		this.stepClock.periodical(1000, this, obj);
	},
	
	this.stepClock = function( obj )
	{
		obj.addSeconds++;
		obj.d.setTime(obj.time * 1000 + obj.addSeconds * 1000 );
		this.displayClock( obj );
	},
	
	this.displayClock = function( obj )
	{
		obj.clock = '<span>'+(obj.d.getHours()+'').strpad(2) + '</span><span>' + (obj.d.getMinutes()+'').strpad(2) + '</span><span>' + (obj.d.getSeconds()+'').strpad(2) + '</span>';
		obj.set('html', obj.clock);
	}
}

/******* OBJECTS *****************/
var DragDrop = new Class({
	Implements: Events,
	
	initialize: function(el, target, options){
		this._el = $(el);
		this._target = target;
		this._options = options;
		this.launch();
	},
	
	launch: function( )
	{
		this._el.addEvent('mousedown', function(e) {
			e = new Event(e).stop();
			this.dragTimer = this.build.delay(200, this, e);
		}.bindWithEvent(this) );
		this._el.addEvent('mouseup', function() {
			$clear(this.dragTimer);
		}.bind(this) );
		this._el.addEvent('selectstart', function() { return false; } );
	},
	
	build: function( e )
	{
		//e = new Event(e).stop();
		this.fireEvent('start');
		this.cloned = this._el.clone().setStyles( this._el.getCoordinates() ).setStyles({'opacity': 0.7, 'position': 'absolute', 'z-index': 100000}).inject(document.body, 'top');
		//this._target.addEvent('drop', function () { this.reset(); this.fireEvent('drop'); }.bind(this) ); // REMOVE
		this.drag = this.cloned.makeDraggable({droppables: [this._target]});
		this.drag.addEvent('drop', function () { this.reset(); this.fireEvent('drop'); }.bind(this) );
		this.cloned.addEvent('emptydrop', this.reset.bind(this) )
		this.drag.start(e);
	},
	
	reset: function( )
	{
		this._target.removeEvents('drop');
		this.fxRemove = new Fx.Tween( this.cloned, { 'property': 'opacity', 'fps': 100, 'duration': 500 } ).start( 0 );
		this.fxRemove.addEvent('onComplete', function() {
			this.cloned.dispose();
		}.bind(this) );
	},
	
	getMouse: function( )
	{
		return this.drag.mouse.now;
	}
});

var Pager = new Class({
	initialize: function(el, options){
		this._el = el;
		this._options = options;
		this._el.empty();
		this._el.size = this._el.getSize();
		this._el2 = new Element('div', {'class': 'pager-right'}).inject( this._el );
		var knobWidth = parseInt(this._el.size.x / this._options.pages);
		knobWidth = ( (knobWidth < 50) ? 50 : knobWidth );
		this._knob = new Element('div', {'class': 'pager-knob'}).setStyles({'width': knobWidth }).inject( this._el2 );
		this._prev = new Element('a', {'class': 'pager-knob-prev'}).addEvent('click', this.prevPage.bindWithEvent(this)).inject( this._knob );
		this._next = new Element('a', {'class': 'pager-knob-next'}).addEvent('click', this.nextPage.bindWithEvent(this)).inject( this._knob );
		this._knob_body = new Element('div', {'class': 'pages-knob-body'}).inject( this._knob );
		
		this._target = $(this._options.target);
		this._page = parseInt( (this._options.current || 1) );
		this._pages = parseInt( this._options.pages );
		this._slider = new Slider( this._el, this._knob, {
			snap: true,
			steps: this._pages - 1,
			wheel: true
		} );
		this._slider.set( this.page2Step(this._page) );
		this._slider.addEvent('onComplete', this.changePage.bind(this) );
	},
	
	changePage: function( step )
	{
		page = parseInt(step) + 1;
		var url = this._options.urlproto.replace( '[page]', parseInt(page) );
		this.xhr = new Request( { url: url, autoCancel: true } ).send();
		this.xhr.addEvent('onComplete', function(page) {
			this._page = page;
			this._target.setContent( this.xhr.response.text );
		}.pass(page, this) );
	},
	
	prevPage: function(e)
	{
		new Event(e).stop();
		if ( this._page > 1)
			this._slider.set(this.page2Step(this._page - 1));
	},
	
	nextPage: function(e)
	{
		new Event(e).stop();
		if ( this._page < this._pages)
			this._slider.set(this.page2Step(this._page + 1));
	},
	
	page2Step: function(page)
	{
		return page - 1;
	}
});

var Widget = new Class({
	initialize: function(el, name, get, functions){
		this._el = el;
		this._name = name;
		this._get = get;
		
		this._top = this._el.getElement('.widget-top');
		this._title = this._el.getElement('h2');
		this._body = this._el.getElement('.widget-body');
		//this._body.fx = new Fx.Tween(this._body, 'height');
		this._status = true;
		this._body.transition = 'none';
		this._body.fx = new Fx.Tween(this._body, { 
			'property': 'height',
			'link': 'cancel',
			'fps': 100,
			'duration': 300,
			'transition': Fx.Transitions.Expo.easeIn
		} );
		this._bottom = new Element('div', {'class': 'widget-bottom'}).inject(this._body, 'after');
		this._bottom.span = new Element('span', {'class': 'widget-bottom-left'}).set('html', '&nbsp;').inject(this._bottom);
		if (functions)
		{
			this._functions = {
				'_switch': 	functions.indexOf('switch'),
				'_add': 	functions.indexOf('add'),
				'_sub': 	functions.indexOf('sub'),
				'_custom': 	functions.indexOf('custom'),
				'_onmap': 	functions.indexOf('onmap'),
				'_popup': 	functions.indexOf('popup')
			};
			if ( (this._functions._add !== -1) || (this._functions._sub !== -1) || (this._functions._onmap !== -1) )
				this._buttons = new Element('ul', {'class': 'widget-buttons'}).inject(this._top, 'top');
			
			if (this._functions._add !== -1)
				this.addWidget();
			if (this._functions._sub !== -1)
				this.subWidget();
			if (this._functions._custom !== -1)
				this.addCustom();
			if (this._functions._switch !== -1)
				this.addSwitch();
			if (this._functions._onmap !== -1)
				this.addOnMap();
		}
		this._paginated = this._body.getElement('.pagination');
		if (this._paginated)
			this.addPagination();
		this._sorting = this._el.getElement('.widget-sorting');
		if (this._sorting)
			this.addSorting();
	},
	
	addPagination: function()
	{
		this._paginated.importProps();
		if (parseInt(this._paginated.total) > 1)
		{
		this._pagination_container = new Element('div', {'class': 'widget-navigation'}).inject( this._top, 'after' );
		this.pages = Math.ceil( this._paginated.total / this._paginated.ipm );
		this.total = new Element('span', {'class': 'widget-total'}).inject( this._pagination_container );
		this.parseTotal();
		if (this.pages > 1)
		{
			this.page = parseInt(this._paginated.page) || 1;
			this.ajaxproto = this._paginated.ajaxproto;
			var size = this._body.getSize();
			var pos = this._body.getPosition();
			this.pagination = new Element('div')/*.inject(this._body, 'before')*/;
			this.pagination.next = new Element('a', {'href': 'javascript:;', 'class': 'widget-next'})/*.setStyles({'position':'absolute', 'margin-left': size.x - 9, 'height': 	size.y})*/.set('html', '<span>Avanti</span>').inject( this._pagination_container, 'top' );
			this.pagination.prev = new Element('a', {'href': 'javascript:;', 'class': 'widget-prev'})/*.setStyles({'position':'absolute', 'height': size.y})*/.set('html', 	'<span>Indietro</span>').inject( this._pagination_container, 'top' );
			this.pagination.next.addEvent('click', function(e) {
				new Event(e).stop();
				if (!this.pagination.next.disabled)
					this.goNextPage();
			}.bind(this) );
			this.pagination.prev.addEvent('click', function(e) {
				new Event(e).stop();
				if (!this.pagination.prev.disabled)
					this.goPrevPage();
			}.bind(this) );
			/*this.pagination.fx = new Fx.Tween( this.pagination, {
				'property': 'opacity',
				'link': 'cancel',
				'fps': 100,
				'duration': 200,
				'transition': Fx.Transitions.Expo.easeIn
			} ).set(0).start(1);*/
			this.controlPagination();
		}
		//this._pagination_container_bottom = this._pagination_container.clone().inject( this._bottom, 'before' );
		}
	},
	
	parseTotal: function()
	{
		var counter = '';
		if (this.pages > 1)
		{
			if (this._paginated.ipm == 1)
				counter = this.page;
			else
				counter = ((this.page - 1) * this._paginated.ipm + 1) + '-' + ((this.page) * this._paginated.ipm);
			counter = '<em>' + counter + '</em>';
			this.total.set('html', '<span><strong>' + counter + '</strong> di <strong>' + this._paginated.total + '</strong> totali</span>');
		}
		else
		{
			this.total.set('html', '<span><em class="total-left"><strong>' + this._paginated.total + '</strong> totali</em></span>');
		}
	},
	
	goNextPage: function()
	{
		this.page = this.page + 1;
		var url = this.ajaxproto.replace( '[page]', this.page ) + (this.sort ? '&sort=' + this.sort : '');
		this._body.loading(1);
		this.nextXHR = new Request( {
			url: url,
			method: "post"
		} ).send();
		this.nextXHR.addEvent('onComplete', function() { this._body.setContent(this.nextXHR.response.text); this.controlPagination(); this._body.loading(0); }.bind(this) );
	},
	
	goPrevPage: function()
	{
		this.page = this.page - 1;
		var url = this.ajaxproto.replace( '[page]', this.page ) + (this.sort ? '&sort=' + this.sort : '');
		this._body.loading(1);
		this.prevXHR = new Request( {
			url: url,
			method: "post"
		} ).send();
		this.prevXHR.addEvent('onComplete', function() { this._body.setContent(this.prevXHR.response.text); this.controlPagination(); this._body.loading(0); }.bind(this) );
	},
	
	rebuildPagination: function()
	{
		if (this._body.getElement('.repagination'))
		{
			this._paginated = this._body.getElement('.pagination');
			if (this._pagination_container)
				this._pagination_container.dispose();
			this.addPagination();
			
		}
	},
	
	controlPagination: function()
	{
		if ( (this.page + 1) > this.pages )
		{
			this.pagination.next.disabled = true;
			this.pagination.next.addClass('disabled');
		}
		else
		{
			this.pagination.next.disabled = false;
			this.pagination.next.removeClass('disabled');
		}
		if ( (this.page - 1) <= 0 )
		{
			this.pagination.prev.disabled = true;
			this.pagination.prev.addClass('disabled');
		}
		else
		{
			this.pagination.prev.disabled = false;
			this.pagination.prev.removeClass('disabled');
		}
		this.parseTotal();
	},
	
	addSorting: function()
	{
		var sorts = this._sorting.getElements('a');
		for (var i=0; i<sorts.length; i++)
		{
			sorts[i].addEvent('click', function(sorts, i) {
				var obj = sorts[i];
				this.sort = obj.get('rel');
				var url = this.ajaxproto.replace( '[page]', 1 ) + '&sort=' + this.sort;
				this._body.loading(1);
				this.sortXHR = new Request( {
					url: url,
					method: "post"
				} ).send();
				this.sortXHR.addEvent('onComplete', function(sorts, i) { this._body.setContent(this.sortXHR.response.text); this.rebuildPagination(); this.chooseSorting(sorts, i); this._body.loading(0); }.pass([sorts, i], this) );
				return false;
			}.pass([sorts, i], this) );
		}
	},
	
	chooseSorting: function(sorts, i)
	{
		for (var k=0; k<sorts.length; k++)
		{
			if (k==i) sorts[k].addClass('sort-selected'); else sorts[k].removeClass('sort-selected');
		}
	},
	
	addWidget: function()
	{
		this._add = new Element('li').set('html', '<a href="javascript:;" class="add"><span>Aggiungi alla scrivania</span></a>').inject(this._buttons);
		this._add.addEvent('click', function() {
			this.addXHR = new Request( {
				url: 'ajax.php?name=profile&task=add_widget&widget='+this._name+'&'+this._get,
				method: "post"
			} ).send();
			this.addXHR.addEvent('onComplete', function() { if (this.addXHR.response.text == '[login]') this.fireEvent('login'); else this.fireEvent('added'); }.bind(this) );
		}.bind(this) );
		this._add.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	subWidget: function()
	{
		this._sub = new Element('li').set('html', '<a href="javascript:;" class="sub"><span>Cancella dalla scrivania</span></a>').inject(this._buttons);
		this._sub.addEvent('click', function() {
			this.subXHR = new Request( {
				url: 'ajax.php?name=profile&task=remove_widget&widget='+this._name+'&'+this._get,
				method: "post"
			} ).send();
			this.subXHR.addEvent('onComplete', function() { if (this.subXHR.response.text == '[login]') this.fireEvent('login'); else {
				this._el.remove();
				this.fireEvent('removed');
			}
			}.bind(this) );
		}.bind(this) );
		this._sub.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	addCustom: function()
	{
		this._custom = new Element('li').set('html', '<a href="javascript:;" class="custom"><span>Personalizza</span></a>').inject(this._buttons);
		this._custom.addEvent('click', function() {
			this.customXHR = new Request( {
				url: 'ajax.php?load=widget&output=custom&name='+this._name+'&get='+this._get,
				method: "post"
			} ).send();
			this.customXHR.addEvent('onComplete', function() {
				if (!this._form)
				{
					this._form = new Element('div', {'class': 'widget-form'}).inject( this._body, 'top' );
					this._form.fx = new Fx.Slide(this._form).hide();
				}
				this._form.set('html', this.customXHR.response.text );
				this._form.fx.slideIn();
			}.bind(this) );
		}.bind(this) );
		this._custom.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	addSwitch: function()
	{
		this.height = this._body.getSize().y;
		this._bottom.span.empty();
		this._switch = new Element('div').set('html', '<a href="javascript:;" class="switch"><span>Cambia visibilità</span></a>').inject(this._top, 'top');
		this._switch.addEvent('click', this.switchWidget.bind(this) );
		this._switch.addEvent('click', function(e) { new Event(e).stop(); } );
		this._title.addEvent('click', this.switchWidget.bind(this) );
		this._title.setStyle('cursor', 'pointer');
	},
	
	switchWidget: function()
	{
		if (this._status)
		{
			this.height = this._body.getSize().y;
			this._body.setStyle('height', this.height);
			this._body.fx.start(0);
			this._switch.addClass('collapse');
			if (this.pagination) this.pagination.fx.start(0);
		}
		else
		{
			this._body.fx.start(this.height).chain( function() { this._body.setStyle('height','auto'); }.bind(this) );
			this._switch.removeClass('collapse');
			if (this.pagination) this.pagination.fx.start(1);
		}
		this._status = !this._status;
	},
	
	addOnMap: function()
	{
		this._onmap = new Element('li').set('html', '<a href="javascript:;" class="onmap"><span>Visualizza sulla mappa</span></a>').inject(this._buttons);
		this._onmap.addEvent('click', this.switchViewOnMap.bind(this) );
		this._onmap.addEvent('click', function(e) { new Event(e).stop(); } );
	},
	
	switchViewOnMap: function()
	{
		if (this._viewonmap)
		{
			this._body.fx.start(0);
			this._switch.addClass('collapse');
			if (this.pagination) this.pagination.fx.start(0);
		}
		else
		{
			this._body.fx.start(this.height);
			this._switch.removeClass('collapse');
			if (this.pagination) this.pagination.fx.start(1);
		}
		this._viewonmap = !this._viewonmap;
	},
	
	search: function( search, lat, lng )
	{
		this._search = search;
		var url = 'ajax.php?load=widget&name=' + this._name + '&search=' + search + '&lat=' + lat + '&lng=' + lng;
		this.xhr = new Request( {
			url: url,
			method: "post"
		} ).send();
		this.xhr.addEvent('onComplete', this.loaded.bind(this) );
	},
	
	loaded: function( response )
	{
		this._el.setContent( response );
	}
});

Widget.implement(new Events, new Options);

var Thumbchange = new Class ({
	Implements: [Events, Options],
	
	options: {
		total: 1,
		delay: 1000,
		bullet: { 'width': 12, 'height': 12 }
	},
	
	initialize: function(element, options) {
		this.element  	= element;
		this.origsrc  	= element.src;
		this.running  	= false;
		this.runnable 	= true;
		this.images   	= new Array();
		this.srcs		= new Array();
		this.loaded		= new Array();
		this.setOptions(options);
		this.build();
	},
	
	build: function() {
		this.element.set('title', '');
		this.fx = new Fx.Tween( this.element, { 'property': 'opacity', 'link':'cancel'} );
		this.temp = new Element('img').inject( document.body, 'bottom' );
		this.temp.fx = new Fx.Tween(this.temp, { 'property': 'opacity', 'link':'cancel'}).set(0);
		this.counter = new Element('span', {'class': 'thumbslide-counter'}).setStyle('width', (this.options.bullet.width * this.options.total)).inject( this.element, 'after' );
		this.selection = new Element('strong').set('html', '<span>&nbsp;</span>').inject( this.counter );
		if (this.options.files)
		{
			for (var i=0; i<this.options.files.length; i++)
				this.srcs[i] = this.options.files[i];
		}
		else
		{
			for (var i=0; i<this.options.total; i++)
				this.srcs[i] = this.options.proto.replace('[num]', (i+1) );
		}
	},
	
	start: function () {
		this.element.addClass('highlight-on');
		if (this.runnable) {
			this.running = true;
			this.load.delay( this.options.delay, this, 1 );
		}
	},
	
	stop: function () {
		this.element.removeClass('highlight-on');
		if (this.runnable) {
			this.to( this.origsrc );
			this.selection.setStyle('background-position', '0px -'+this.options.bullet.height+'px');
			this.running = false;
		}
	},
	
	load: function (num) {
		if (this.timer) $clear(this.timer);
		if (this.running) {
			if (!this.loaded[num])
			{
				this.images[num] = new Element('img').set('src', this.srcs[num] );
				this.images[num].addEvent('load', this.animate.pass(num, this) );
			}
			else
				this.animate(num);
		}
	},
	
	animate: function (num) {
		if (this.running)
		{
			this.loaded[num] = true;
			this.selection.setStyle('background-position', (num * this.options.bullet.width) + 'px -'+this.options.bullet.height+'px');
			this.to( this.images[num].src );
			
			var next = (num == this.options.total-1) ? 0 : num + 1;
			this.timer = this.load.delay( this.options.delay, this, next );
		}
	},
	
	to: function( src )
	{
		var pos = this.element.getPosition();
		this.temp.set('src', src);
		this.temp.setStyles( { 'position': 'absolute', 'left': pos.x, 'top': pos.y } );
		this.fx.start(0);
		this.temp.fx.start(1).chain( function() {
			this.element.src = this.temp.src;
			this.destroy();
		}.bind(this) );
	},
	
	destroy: function( )
	{
		this.fx.set(1);
		this.temp.fx.set(0);
	}
});

/******* IMPLEMENTATION ***********/
Array.prototype.sum = function(){
	for(var i=0,sum=0;i<this.length;sum+=this[i++]);
	return sum;
}
Array.prototype.max = function() {
	return Math.max.apply({},this)
}
Array.prototype.min = function() {
	return Math.min.apply({},this)
}
String.prototype.strpad = function() {
	return (!isNaN(this) && this.toString().length==1)?"0"+this:this;
}

Element.implement({
	importProps: function()
	{
		this.saveProps( this, this );
	},
	
	copyProps: function( obj )
	{
		this.saveProps( obj, this );
	},
	
	saveProps: function( source, target )
	{
		var trigger = "logics@";
		if (source.className.indexOf(trigger) !== -1)
		{
			// import rel settings
			var logics = source.className.substring( source.className.indexOf(trigger) + trigger.length );
			var parts = logics.split('|');
			for (var j=0; j<parts.length; j++)
			{
				kv = parts[j].split(':');
				if (kv.length == 2)
				{
					kv[1] = kv[1].replace('[http]', 'http://');
					eval("target."+kv[0]+" = '"+kv[1]+"'");
				}
			}
		}
	},
	
	getURL: function( )
	{
		var uri = (this.tagName == 'FORM' ? this.get('action') : this.get('href') );
		if (this.urlproto)
			var url = this.urlproto.replace( '[url]', uri + '&' );
		else
			var url = uri;
		return url;
	},
	
	getQueryString: function(){
		var queryString = [];
		this.getElements('input, select, textarea').each(function(el){
			if (!el.name || el.disabled) return;
			var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
			if ((typeof tinyMCE == undefined) && (el.className.indexOf('editor') > -1))
				value = tinyMCE.get(el.get('id')).getContent();
			$splat(value).each(function(val){
				if (val) queryString.push(el.name + '=' + escape(val));
			});
		});
		return queryString.join('&');
	},
	
	getPosition: function(relative){
		if (Browser.Engine.trident)
			var offset = {'x': this.getBoundingClientRect().left, 'y': this.getBoundingClientRect().top }
		else
			var offset = this.getOffsets();
		var scroll = this.getScrolls();
		var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
		var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};
		return {x: position.x - relativePosition.x, y: position.y - relativePosition.y};
	},
	
	continueClick: function( )
	{
		if (this.hasClass('confirm'))
		{
			if (confirm(this.question))
				return true;
			else
				return false;
		}
		return true;
	},
	
	loading: function( mode )
	{
		if (!this.loadingDiv)
		{
			this.loadingDiv = new Element('div', {'class': 'loading-trip-panel'}).setStyles({'position':'absolute', 'z-index': 10000000}).set('html', '&nbsp;').inject( this, 'top' );
			this.loadingFx = new Fx.Tween(this.loadingDiv, {'link': 'chain', 'property': 'opacity'}).set(0);
		}
		var size = this.getSize();
		this.loadingDiv.setStyles( { 'width': size.x, 'height': size.y } );
		switch (mode)
		{
			case 1: this.loadingFx.start(.7); break;
			case 0: this.loadingFx.start(0); break;
		}
	},
	
	setContent: function( html )
	{
	  	switch (this.transition)
	  	{
		default:
		
			// cancel if
			if (this.settingContent)
			{
				this.nextHTML = html;
				return;
			}
				
			this.size = this.getCoordinates();
			
			// build
			this.view = new Element('div').setStyles( {'position': 'relative', 'overflow': 'hidden'} ).inject( this, 'before' );
				this.view.setStyles( {'width': this.size.width, 'height': this.size.height} );
			this.wrapper = new Element('div').inject( this.view );
				this.wrapper.setStyles( {'width': this.size.width * 2 + 10, 'height': this.size.height, 'margin-left': 0} );
			this.exitDiv = new Element('div').set('html', this.get('html')).setStyles( {'width': this.size.width, 'float': 'left'} ).inject( this.wrapper );
			this.enterDiv = this.exitDiv.clone( ).set('html', html).inject( this.wrapper );
			this.empty();
			
			// slide
			this.nextHeight = this.enterDiv.getSize().y
			this.fxAdjust = new Fx.Tween( this.view, { 'property': 'height' } );
			this.fxScroll = new Fx.Tween( this.wrapper, { 'property': 'margin-left', 'fps': 100, 'duration': 1000, 'transition': Fx.Transitions.Sine.easeOut} );
			// starting animation
			this.settingContent = true;
			this.fxAdjust.start( this.nextHeight );
			
			this.setStyles({'display': 'none'});
			document.fireEvent('removeblock', this.exitDiv);
			this.set('html', html);
			document.fireEvent('updateblock', this.enterDiv);
			
			this.fxAdjust.addEvent('onComplete', function() {
				this.fxScroll.start( -this.size.width );
			}.bind(this) );
			
			this.fxScroll.addEvent('onComplete', function() {
				this.setStyles({'display': 'block'});
				document.fireEvent('updateblock', this);
				this.fireEvent('updated');
				this.destroySettingContent();
				if (this.nextHTML)
				{
					this.setContent( this.nextHTML );
					this.nextHTML = null;
				}
			}.bind(this) );
			
		break;
			
		case 'none':
			document.fireEvent('removeblock', this);
			this.set('html', html);
			document.fireEvent('updateblock', this);
		break;
		}
	},
	
	destroySettingContent: function( )
	{
		this.exitDiv.destroy();
		this.enterDiv.destroy();
		this.wrapper.destroy();
		this.view.destroy();
		this.fxAdjust = null;
		this.fxScroll = null;
		this.exitDiv = this.enterDiv = this.wrapper = this.view = null;
		this.settingContent = false;
	}
} );

function docFromXML( txt )
{
	if (Browser.Engine.trident)
	{
		xml = new ActiveXObject("Microsoft.XMLDOM");
		xml.async="false";
		xml.loadXML(txt);
		var xmlDoc = xml.documentElement;
	}
	else
	{
		parser = new DOMParser();
		xml = parser.parseFromString(txt, "text/xml");
		var xmlDoc = xml.documentElement;
	}
	return xmlDoc;
}

function getXMLdata( node )
{
	var data;
	
	if (node.nodeValue)
		data = node.nodeValue;
	else if (node.firstChild)
		data = node.firstChild.data;
	
	if (!data)
		return null;
	
	return decodeHTML( data );
}

function decodeHTML( html )
{
	// DECODE HTML entities...let's the browser do the job! ^_^
	var temp_div = new Element('div').set('html', html);
	return temp_div.get('html');
}
