/*
	About:
		Author: Michal Schejbal, 2011
		Version: 1.4

		- Based on mootools 1.3


	Changelog (only vital changes):
	   1.4:
	      - uiInput: refactored
	      - uiHtmlButton: refactored
	      - uiScroller: refactored
	      - uiSelect: refactored
	      - preventing null size
	      - added controls.makeTogglable function

	
	
	   1.3:
	      - uiSlideShow: begin and end effect handling
								new stripe effect,
								code optimalization (=> brute performance increase)
								new onlyWidescreen attibute
								

		1.2:
			- uiTree: ie7 fix
			- uiSlideShow: added effects and better code logic
			- uiList: alpha from this version
			- uiScroller: added own proto-simple-event handling
							min and max limit done
							overlabel to display count/max
			- uiInput: alpha from this version


		1.1:
			- uiCheck: new from this version
			- uiSelect: new from this version


	Usage:
		Type these to element class attribute
		1. Selectors:
			ui-make-[ui control class name]

			Otherwise you can alter _uiConstrols.set function select mechanism

		example:
			ui-make-scroller		// Will find all elements with this class and make them scrollers

		2. Special parameters:
			- ui-omit				// This element will be omitted
			- ui-wrapped			// This element was already wraped


		Styling via css
		1. Available class names:
			Use these class names to style ui elements
			- ui-htmlButton
			- ui-scroller
			- ui-select
			- ui-checkbox
			- ui-radio
			- ui-treeView
			- ui-slideShow
			- ui-input
			- ui-textarea

			- ui-overinput   // mootools implementation

*/


/*
   _uiControls class: Automatic wrapper
   
   USAGE:
   An instance of this class is automaticly made(var controls = new _uiControls();).
   Use constrols object to address class functions.
   
   function Set:
	   - when true, wrapper will search for specified elements and wrap them
		controls.set(
		{
		   button: true,
		   submit: true,
		});
	
	function setBrowserInfo:
		- adds informations to body element class attributte about user browser
		  (mainly used for css)
	
*/
var _uiControls = new Class(
{
	types:
	{
	   button: false,
	   submit: false,
	   reset: false,

	   scroller: false,
	   checkbox: false,
	   radio: false,
	   input: false,

	   treeView: false,
	   slideShow: false,
	   overinput: false
	},


   makes: [
	{
		id: 'ui-make-htmlButton',
		userTypes: {button: 'input[type="button"]', submit: 'input[type="submit"]', reset: 'input[type="reset"]'},
		fn: function(e){new _uiHtmlButton(e);}
	},
	{
		id: 'ui-make-scroller',
		userTypes: {scroller: ''},
		fn: function(e){new _uiScroller(e);}
	},
	{
		id: 'ui-make-select',
		userTypes: {select: 'select'},
		fn: function(e){new _uiSelect(e);}
	},
	{
		id: 'ui-make-checkbox',
		userTypes: {radio: 'input[type="checkbox"]'},
		fn: function(e){new _uiCheckbox(e);}
	},
	{
		id: 'ui-make-radio',
		userTypes: {radio: 'input[type="radio"]'},
		fn: function(e){new _uiRadio(e);}
	},
	{
		id: 'ui-make-input',
		userTypes: {input: 'input[type="text"], input[type="password"]'},
		fn: function(e){new _uiInput(e);}
	},
	{
		id: 'ui-make-textarea',
		userTypes: {textarea: 'textarea'},
		fn: function(e){new _uiTextarea(e);}
	},
	{
		id: 'ui-make-treeView',
		userTypes: {treeView: ''},
		fn: function(e){new _uiTreeView(e);}
	},
	{
		id: 'ui-make-slideShow',
		userTypes: {slideShow: ''},
		fn: function(e)
		{
			var tmp	= e.getElements('img');
			var imgs = new Array();

			for(var i=0; i<tmp.length; i++)
				imgs.push({src: tmp[i].src, title: tmp[i].title ? tmp[i].title : tmp[i].alt});

			e.empty();
			new _uiSlideShow(e, imgs, JSON.decode(e.title));
			e.removeProperty('title');
		}
	},
	{
		id: 'ui-make-overinput',
		userTypes: {overinput: 'input[alt]'},
		fn: function(e)
		{
			new OverText(e, {wrap: false, poll: true});
			e.addClass('ui-wrapped-overinput');
		}
	}],

	set: function(types)
	{
		for(var m=0, ml=this.makes.length; m<ml; m++)
		{
			var item     = this.makes[m];
			var elements = new Array();

			for(var t in item.userTypes)
			{
				if(types[t] && item.userTypes[t])
				{
				   var tmp = $$(item.userTypes[t]);
				   for(var f=0; f<tmp.length; f++)
				      elements.push(tmp[f]);
				}
			}

		   var tmp = $$('.'+item.id);
		   for(var f=0; f<tmp.length; f++)
		      elements.push(tmp[f]);


			for(var e=0, el=elements.length; e<el; e++)
			{
				this.wrap(elements[e], item.fn);
			}
		}
	},
	
	
	wrap: function(e, fn) // Private function
	{
		if(!e.hasClass('ui-wrapped') && !e.hasClass('ui-omit'))
		{
		   fn(e);
		}
	}.protect(),

	setBrowserInfo: function()
	{
		document.id('body').addClass(Browser.name+' '+Browser.name+Browser.version+' flash'+Browser.Plugins.Flash.version+' '+Browser.Platform.name);
		//document.id('body').addEvent('contextmenu',function(e){e.stop();});
	},

	makeTogglable: function(toggler, element, timeout, linkedTogglers)
   {
      if(!timeout)    timeout = 1000;
      if(timeout<500) timeout = 500;


		toggler.store('fxm', new Fx.Morph(element, {duration: timeout-300}).set({opacity: 0}));
		toggler.store('fxs', new Fx.Slide(element, {duration: timeout, mode: 'vertical', transition: 'quad:out', resetHeight: true}).hide());
		if(linkedTogglers) toggler.store('linked', linkedTogglers.length ? linkedTogglers : [linkedTogglers]);

		toggler.addEvent('click', function()
		{
		   this.retrieve('fxm').start({opacity: this.retrieve('fxs').open ? [1,0] : [0,1]});
		   this.retrieve('fxs').toggle();

		   var linked = this.retrieve('linked');
		   if(linked)
		   {
			   var length = linked.length;

			   for(var i=0; i<length; i++)
			   {
				   if(linked[i].retrieve('fxs').open && this!=linked[i])
					{
						linked[i].retrieve('fxm').start({opacity: [1,0]});
				   	linked[i].retrieve('fxs').slideOut();
				   }
			   }
		   }


		   return false;
		});
   }
});

var controls = new _uiControls();




// ---------------------------------------------------------------------------------------------------
// Button
// ---------------------------------------------------------------------------------------------------
var _uiHtmlButton = new Class(
{
	e: null,
	parent: null,
	
	capsule: null,
	link: null,
	
	options:
	{
	   onClick: null
	},

	initialize: function(e, opts)
	{
	   Object.append(this.options, opts);
	
		this.e      = e;
		this.parent = e.getParent();
		var size	   = e.getSize();
		
		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   this.parent.adopt(e);
		}

		e.setStyle('display', 'none');
		e.addClass('ui-wrapped');

		this.capsule = new Element('div',
		{
			'class': 'ui-htmlButton',
			styles:
			{
				width: size.x
			}
		});

		this.link = new Element('a',
		{
			text: e.get('value') ? e.get('value') : e.get('text'),
			title: e.get('title'),
			'class': 'link',
			styles:
			{
				cursor: 'pointer'
			},
			events:
			{
				click: this.options.onClick ? this.options.onClick.bind(this)	:
				function()
				{
					if(e.get('tag')!='a')
					{
						var form = this.e.getParent('form');
						if(form && this.e.get('type')=='submit')
							this.e.getParent('form').submit();
						else this.e.fireEvent('click');
					}

					return true;
				}.bind(this)
			}
		});

		if(e.get('tag')=='a') this.link.set('href', e.get('href'));

		this.capsule.adopt(this.link);


		// Borders and background
		this.capsule.adopt(new Element('div', {'class': 'bg'}));
		
		this.capsule.adopt(new Element('div', {'class': 'border _top'}));
		this.capsule.adopt(new Element('div', {'class': 'border _left'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tr'}));
		
		this.capsule.adopt(new Element('div', {'class': 'border _bottom'}));
		this.capsule.adopt(new Element('div', {'class': 'border _right'}));
		this.capsule.adopt(new Element('div', {'class': 'border _bl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _br'}));

		this.parent.adopt(this.capsule);
		this.capsule.adopt(e);
	}
});



// ---------------------------------------------------------------------------------------------------
// Input
// ---------------------------------------------------------------------------------------------------
var _uiInput = new Class(
{
	e: null,
	capsule: null,

	initialize: function(e)
	{
		this.e     = e;
		var parent = e.getParent();
		var size   = e.getSize();
		
		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		e.addClass('ui-wrapped');


		this.capsule = new Element('div',
		{
			'class': 'ui-input',
			styles:
			{
				width: size.x
			}
		});


		// Borders and background
		this.capsule.adopt(new Element('div', {'class': 'bg'}));
		
		this.capsule.adopt(new Element('div', {'class': 'border _top'}));
		this.capsule.adopt(new Element('div', {'class': 'border _left'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tr'}));

		this.capsule.adopt(new Element('div', {'class': 'border _bottom'}));
		this.capsule.adopt(new Element('div', {'class': 'border _right'}));
		this.capsule.adopt(new Element('div', {'class': 'border _bl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _br'}));

		parent.adopt(this.capsule);
		this.capsule.adopt(e);
		
		if(e.get('alt'))
		{
			new OverText(e, {wrap: false, poll: true});
		}
	}
});


// ---------------------------------------------------------------------------------------------------
// Textarea
// ---------------------------------------------------------------------------------------------------
var _uiTextarea = new Class(
{
	e: null,
	capsule: null,

	initialize: function(e)
	{
		this.e     = e;
		var parent = e.getParent();
		var size   = e.getSize();

		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		e.addClass('ui-wrapped');


		this.capsule = new Element('div',
		{
			'class': 'ui-textarea',
			styles:
			{
				width: size.x
			}
		});


		// Borders and background
		this.capsule.adopt(new Element('div', {'class': 'bg'}));

		this.capsule.adopt(new Element('div', {'class': 'border _top'}));
		this.capsule.adopt(new Element('div', {'class': 'border _left'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _tr'}));

		this.capsule.adopt(new Element('div', {'class': 'border _bottom'}));
		this.capsule.adopt(new Element('div', {'class': 'border _right'}));
		this.capsule.adopt(new Element('div', {'class': 'border _bl'}));
		this.capsule.adopt(new Element('div', {'class': 'border _br'}));

		parent.adopt(this.capsule);
		this.capsule.adopt(e);

		if(e.get('title'))
		{
			new OverText(e, {wrap: false, poll: true});
		}
	}
});




// ---------------------------------------------------------------------------------------------------
// Scroller
// ---------------------------------------------------------------------------------------------------
var _uiScroller = new Class(
{
	Implements: [Options],

	e: null,
	capsule: null,
	label: null,
	count: null,
	options:
	{
		max: 0,							 		// If non-zero checks for maximum value
		min: 0,
		negativeValues: false,
		showMax: false,						// Create max element for displaying max value
		autoWidth: false
	},

	events: null,

	initialize: function(e, opts)
	{
	 	this.e	  = e;
	 	this.count = parseInt(this.e.get('value'));
		var parent = this.e.getParent();
		var size	  = this.e.getSize();
		
		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		this.setOptions(opts);
		this.e.addClass('ui-wrapped');

		this.capsule = new Element('div',
		{
			'class': 'ui-scroller',
			styles:
			{
				position: 'relative',
				width: size.x
			}
		});

		if(this.options.showMax)
		{
			this.label = new Element('input',
			{
				styles:
				{
					position: 'absolute',
					top: 0,
					left: 0,
					width: size.x,
					height: this.e.getStyle('height'),
					'text-align': this.e.getStyle('text-align')
				},
				events:
				{
					keydown: function(ev)
					{
						this.e.fireEvent('keydown', ev);
					}.bind(this)
				}
			});

			this.label.set('value', this.count+'/'+this.options.max);
			this.capsule.adopt(this.label);
		}

		var plus = new Element('a',
		{
			text: '+',
			href: '',
			'class': 'plus',
			styles:
			{
				position: 'absolute'
			},
			events:
			{
				click: function()
				{
					this.plus();
					this._runEvents('plus');
					return false;
				}.bind(this)
			}
		});
		this.capsule.adopt(plus);

		var separator = new Element('div',
		{
			'class': 'separator',
			styles:
			{
				position: 'absolute'
			}
		});
		this.capsule.adopt(separator);

		var minus = new Element('a',
		{
			text: '-',
			href: '#',
			'class': 'minus',
			styles:
			{
				position: 'absolute'
			},
			events:
			{
				click: function()
				{
					this.minus();
					this._runEvents('minus');
					return false;
				}.bind(this)
			}
		});
		this.capsule.adopt(minus);


		e.addEvent('keypress', function(ev)
		{
			switch(ev.code)
			{
				case 38:	// up
					this.plus();
					this._runEvents('plus');
					break;

				case 40:	// down
					this.minus();
					this._runEvents('minus');
					break;
			}

			ev.stop();
			return true;
		}.bind(this));


		e.addEvent('keyup', function(ev)
		{
			switch(ev.code)
			{
				case 38:
				case 40:
					break;

				default:
					this.count = parseInt(this.e.get('value'));
					this._runEvents('change');
					break;
			}

         ev.stop();
			return true;
		}.bind(this));


		// Borders and background
		this.capsule.adopt(new Element('div', {'class': 'bg'}));

		this.capsule.adopt(new Element('div', {'class': 'border _top'}));
		this.capsule.adopt(new Element('div', {'class': 'border _left'}));
		this.capsule.adopt(new Element('div', {'class': 'border _bottom'}));
		this.capsule.adopt(new Element('div', {'class': 'border _right'}));


		e.inject(this.capsule, 'top');
		parent.adopt(this.capsule);
		this.autoWidth();
	},

	plus: function()
	{
		if((this.count+1)<=this.options.max || !this.options.max)
			this.e.set('value', ++this.count);

		if(this.label)
			this.label.set('value', this.count+'/'+this.options.max);

		this.e.fireEvent('change');
		this.autoWidth();
	},

	minus: function()
	{
		if((this.count-1)>=this.options.min || this.options.negativeValues)
			this.e.set('value', --this.count);

		if(this.label)
			this.label.set('value', this.count+'/'+this.options.max);

		this.e.fireEvent('change');
		this.autoWidth();
	},

	autoWidth: function()
	{
		if(this.options.autoWidth)
		{
			var width = parseInt(this.e.getStyle('font-size'))-3;

			if(this.label)
			{
				width = this.label.get('value').length*width;
				this.capsule.setStyle('width', width);
				this.label.setStyle('width', width-2);
				this.e.setStyle('width', width-2);
			}
			else
			{
				width = this.e.get('value').length*width;
				this.capsule.setStyle('width', width);
				this.e.setStyle('width', width);
			}
		}
	},

	addEvent: function(name, fn)
	{
		if(!this.events) this.events = new Array();
		this.events.push({name: name, fn: fn});
	},

	_runEvents: function(name)
	{
		if(this.events)
		{
			var length = this.events.length;

			for(var i=0; i<length; i++)
			{
				var e = this.events[i];
				if(name==e.name) e.fn();
			}
		}
	}
});




// ---------------------------------------------------------------------------------------------------
// Select
// ---------------------------------------------------------------------------------------------------
var _uiSelect = new Class(
{
	Implements: [Options],

	e: null,
	options:
	{
		dropdownTime: 200,
		useWrapped: !true,
		icons: false,
		valueIsLink: false
	},

	capsule: null,
	input: null,
	label: null,
	arrow: null,
	wrapper: null,
	list: null,
	fxList: null,

	inst: null,			// Static
	stack: 9999,      // Static

	initialize: function(e, opts)
	{
	 	this.e	  = e;
		var parent = e.getParent();
		var size	  = e.getSize();

		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		//
		if(this.e.hasClass('ui-select-original')) this.options.useWrapped = false;
		if(this.e.hasClass('ui-select-html')) this.options.useWrapped = true;

		this.setOptions(opts);

		if(!_uiSelect.inst) _uiSelect.inst = new Array();
		_uiSelect.inst.push(this);

		e.addClass('ui-wrapped');
		e.setStyles(
		{
			position: 'absolute',
			top: 0,
			left: 0,
			bottom: 0,
			right: 0,
			width: size.x,
			height: size.y,
			'z-index': 4,
			opacity: 0
		});

		this.capsule = new Element('div',
		{
			'class': 'ui-select',
			styles:
			{
				position: 'relative',
				width: size.x,
				height: size.y
			},
			events:
			{
				click: function()
				{
					if(this.fxList) this.fxList.toggle();
				}.bind(this)
			}
		});

		this.input = new Element('div',
		{
			'class': 'input',
			styles:
			{
				cursor: 'pointer'
			},
			events:
			{
				click: function()
				{
					if(this.fxList) this.fxList.toggle();
				}.bind(this)
			}
		});
		this.capsule.adopt(this.input);

		this.label = new Element('span',
		{
			text: e.options[e.selectedIndex].text,
			'class': 'text'
		});
		this.input.adopt(this.label);

		this.arrow = new Element('div',
		{
			'class': 'arrow',
			styles:
			{
				cursor: 'pointer'
			},
			events:
			{
				click: function()
				{
					if(this.fxList) this.fxList.toggle();
				}.bind(this)
			}
		});

  		this.capsule.adopt(this.arrow);

		// Borders and background
		this.capsule.adopt(new Element('div', {'class': 'bg'}));

		this.capsule.adopt(new Element('div', {'class': 'border _top'}));
		this.capsule.adopt(new Element('div', {'class': 'border _left'}));
		this.capsule.adopt(new Element('div', {'class': 'border _bottom'}));
		this.capsule.adopt(new Element('div', {'class': 'border _right'}));

		this.capsule.adopt(e);
		parent.adopt(this.capsule);

		this.options.useWrapped ? this.useWrapped() : this.useDefault();
	},


	useDefault: function()
	{
		this.e.addEvent('change', function()
		{
			this.input.set('text', this.e.options[this.e.selectedIndex].text);

			if(this.options.valueIsLink && this.e.options[this.e.selectedIndex].value) location.href = this.e.options[this.e.selectedIndex].value;
		}.bind(this));

		this.e.setStyle('visibility', 'visible');
	},


	useWrapped: function()
	{
		var size = this.capsule.getSize();

		document.id('body').addEvent('click', function()
		{
		   this.fxList.slideOut();
		}.bind(this));

		if(this.options.icons) this.input.adopt(new Element('div', {'class': 'icon'}));

		this.wrapper = new Element('div',
		{
			'class': 'listWrapper',
			styles:
			{
				position: 'absolute',
				top: size.y+1,
				left: 0,
				right: 0,
				width: size.x,

				'z-index': 1
			}
		});

		this.list = new Element('ol',
		{
			'class': 'list',
			styles:
			{
				position: 'absolute',
				top: 0,
				left: 0,
				right: 0,
				'max-height': '300px',
				margin: 0,

				'overflow-y': 'auto',
				'overflow-x': 'hidden',

				'z-index': 1
			}
		});

      var len = this.e.options.length;
		for(var i=0; i<len; i++)
		{
		   var optClass = this.e.options[i].className;
		   if(optClass!='default')
		   {
				var li = new Element('li',
				{
					'class': (!(i%2) ? 'odd ' : 'even ') + (!i ? 'first' : '') + (i==this.e.options.length-1 ? 'last' : '') + ' ' + optClass,
					text: this.e.options[i].text,
					title: this.e.options[i].text,
					styles:
					{
						cursor: 'pointer',
						'white-space': 'nowrap'
					},
					events:
					{
						click: function(arg)
						{
						   this.input.removeClass('default');
							this.label.set('text', this.e.options[arg.i].text);
							if(this.options.icons)
								this.input.getElement('.icon').set('class', 'icon '+this.e.options[arg.i].className);
							this.e.selectedIndex = arg.i;
							this.fxList.toggle();

							if(this.options.valueIsLink && this.e.options[arg.i].value) location.href = this.e.options[arg.i].value;
						}.bind(this,{i: i, li: li})
					}
				});

				if(this.options.icons) li.adopt(new Element('div', {'class': 'icon'}));

				this.list.adopt(li);
			}
			else
			   this.input.addClass('default');
		}

		this.wrapper.adopt(this.list);
		this.capsule.adopt(this.wrapper);
		this.fxList = new Fx.Slide(this.list,
		{
			duration: this.options.dropdownTime,
			transition: 'quad:out',
			wrapper: this.wrapper
		}).hide();

		this.fxList.addEvent('start', function()
		{
			for(var i=0; i<_uiSelect.inst.length; i++)
			{
				if(_uiSelect.inst[i]!=this)
					_uiSelect.inst[i].fxList.hide();
			}

			if(!this.fxList.open)
				this.wrapper.setStyle('z-index',parseInt(this.wrapper.getStyle('z-index'))+5);
		}.bind(this));

		this.fxList.addEvent('complete', function()
		{
			if(!this.fxList.open)
				this.wrapper.setStyle('z-index',parseInt(this.wrapper.getStyle('z-index'))-5);
		}.bind(this));

		this.e.setStyle('visibility', 'hidden');
	},

	setSelected: function(id)
	{
      var len = this.e.options.length;
		for(var i=0; i<len; i++)
		{
		   if(this.e.options[i].id=='opt-'+id)
		   {
			   this.input.removeClass('default');
				this.label.set('text', this.e.options[i].text);

				var eIcon = this.input.getElement('.icon');
				if(eIcon) eIcon.set('class', 'icon '+this.e.options[i].className);

				this.e.selectedIndex = i;
		   }
		}
	}

});




// ---------------------------------------------------------------------------------------------------
// Checkbox
// ---------------------------------------------------------------------------------------------------
var _uiCheckbox = new Class(
{
	orig: null,

	capsule: null,
	box: null,
	check: null,

	inst: null,

	initialize: function(e)
	{
	 	this.e	  = e;
		var parent = e.getParent();
		var size	  = e.getSize();
		
		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		//e.setStyle('display', 'none');
		e.addClass('ui-wrapped');

		if(!_uiCheckbox.inst) _uiCheckbox.inst = new Array();
		_uiCheckbox.inst.push(this);


		this.capsule = new Element('div',
		{
			'class': 'ui-checkox',
			styles:
			{
				position: 'relative',
				width: size.x,
				height: size.y
			}
		});

		this.box = new Element('div',
		{
			'class': 'cbBox',
			styles:
			{
				position: 'absolute',
				cursor: 'pointer'
			},
			events:
			{
				click: function()
				{
					this.toggle();
				}.bind(this)
			}
		});
		this.capsule.adopt(this.box);

		this.check = new Element('div',
		{
			//text: '●',
			'class': 'cbCheck',
			styles:
			{
				position: 'absolute',
				cursor: 'pointer'
			},
			events:
			{
				click: function()
				{
					this.toggle();
				}.bind(this)
			}
		});
		this.capsule.adopt(this.check);

		var label = parent.getElement('label[for="'+this.e.get('id')+'"]');
		
		if(label)
		{
			label.removeProperty('for');
			label.addClass('cbLabel');
			label.setStyle('position', 'absolute');
			label.addEvent('click', function()
			{
				this.toggle();
			}.bind(this));
			
			this.capsule.adopt(label);
		}

		parent.adopt(this.capsule);
		this.capsule.adopt(this.e);
		

		if(this.e.checked) this.check.toggleClass('checked');
	},

	toggle: function()
	{
		this.e.fireEvent('click');
		this.e.checked = !this.e.checked;
		this.check.toggleClass('checked');

		if(this.e.get('onclick'))
		{
			var sid = this.e.get('id');
			var id	= '_uiCheckbox'+_uiCheckbox.inst.length;

			this.e.set('id', id);
			eval(this.e.get('onclick').replace(new RegExp('this+', 'g'), 'document.id(\''+id+'\')'));
			this.e.set('id', sid);
		}
	}

});




// ---------------------------------------------------------------------------------------------------
// Radio
// ---------------------------------------------------------------------------------------------------
var _uiRadio = new Class(
{
	orig: null,

	inst: null,

	initialize: function(e)
	{
	 	this.e	  = e;
		var parent = e.getParent();
		var size	  = e.getSize();
		
		if(!size.x)
		{
		   $('body').adopt(e);
		   size = e.getSize();
		   parent.adopt(e);
		}

		this.setOptions(opts);

		if(!_uiRadio.inst) _uiRadio.inst = new Array();
		_uiRadio.inst.push(this);

		e.addClass('ui-wrapped');
		e.setStyles({position: 'absolute', 'z-index': 4, opacity: 0});

		this.capsule = new Element('div',
		{
			'class': 'ui-select',
			styles:
			{
				position: 'relative',
				width: size.x,
				height: size.y
			}
		});
	}
});



// ---------------------------------------------------------------------------------------------------
// List
// ---------------------------------------------------------------------------------------------------
var _uiList = new Class(
{
	Implements: [Options],

	options:
	{
		checks: false,
		columns: 1,
		width: 250,
		height: 200
	},

	win: null,								// Main window handle
	parent: null,
	list: null,			 				// UL

	initialize: function(parent, opts)
	{
		this.setOptions(opts);
		this.parent = parent;

		this.win = new Element('div',
		{
			'class': 'ui-list',
			styles:
			{
				width: this.options.width,
				height: this.options.height,
				overflow: 'hidden'
			}
		});

		this.list = new Element('ul',
		{
			'class': 'level-0',
			styles:
			{
				margin: 0,
				padding: 0
			}
		});

		this.win.adopt(this.list);
		parent.adopt(this.win);
	},

	// Array of structure [{title: , value: , nodes: [...]}]
	add: function(items)
	{
		var level	= 0;
		var length = items.length;

		if(length)
		{
			for(var i=0; i<length; i++)
			{
				var row = this._insert(this.list, items[i]);
				if(items[i].nodes.length) this._add(row, items[i].nodes, level+1);
			}
		}
	},

	_add: function(parent, items, level)
	{
		var length = items.length;

		var list = new Element('ul',
		{
			'class': 'level-'+level,
			styles:
			{
				margin: 0,
				'padding-left': 2*level
			}
		});

		parent.adopt(list);
		parent.store('fxMorph', new Fx.Morph(list, {duration: 250}));
		parent.store('fxToggle', new Fx.Slide(list, {duration: 250, transition: 'quad:out', resetHeight: true}).hide());

		for(var i=0; i<length; i++)
		{
			var row = this._insert(list, items[i]);
			if(items[i].nodes.length) this._add(row, items[i].nodes, level+1);
		}

	}.protect(),

	_insert: function(parent, item)
	{
		var row = new Element('li',
		{
			styles:
			{
				position: 'relative',
				padding: 0
			},
			events:
			{
				click: function()
				{

				}
			}
		});

		if(this.options.checks)
		{
			row.adopt(new Element('input',
			{
				type: 'checkbox',
				value: item.value,
				events:
				{
					click: function()
					{
						this.getParent().getElements('input[type="checkbox"]').each(function(e)
						{
							if(e!=this) e.checked = this.checked;
						}.bind(this));
					}
				}
			}));

			row.adopt(new Element('a',
			{
				text: '',
				styles:
				{
					position: 'absolute',
					top: 0,
					right: 0,
					'font-size': 9
				},
				events:
				{
					click: function()
					{
						this.getParent().getElements('input[type="checkbox"]').each(function(e)
						{
							e.checked = !e.checked;
						});
					}
				}
			}));
		}

		row.adopt(new Element('label',
		{
			text: item.title,
			styles:
			{
				position: 'absolute',
				top: 0,
				left: 18,
				right: 10

			},
			events:
			{
				click: function()
				{
					this.getParent().retrieve('fxMorph').start({opacity: this.getParent().retrieve('fxToggle').open ? [1,0] : [0,1]});
					this.getParent().retrieve('fxToggle').toggle();
				}
			}
		}));


		parent.adopt(row);
		return row;
	}.protect()
});




// ---------------------------------------------------------------------------------------------------
// Tree
// ---------------------------------------------------------------------------------------------------
var _uiTreeView = new Class(
{
	Implements: [Options],

	options:
	{
	   togglers: true,
		togglersChars: {plus: '+',minus: '-'}
	},

	parent: null,


	initialize: function(parent, opts)
	{
	   this.setOptions(opts);
		parent.addClass('ui-treeView ui-wrapped');

		var list = parent.getChildren('ul');
	 	for(var i=0; i<list.length; i++)
			this.browse(list[i]);
	},

	browse: function(list)
	{
		if(list)
		{
			list.getChildren('li').each(function(item)
			{
				item.setStyle('position', 'relative');


				var active	= item.hasClass('active');
				var childen = item.getChildren('ul');

				for(var i=0; i<childen.length; i++)
	 			{
					var child = childen[i];

					if(child)
					{
						item.setStyle('background', '0');

						wrapper = new Element('div',
						{
							styles:
							{

							}
						});

						toggler = new Element('a',
						{
							text: this.options.togglers ? (active ? this.options.togglersChars.minus : this.options.togglersChars.plus) : '',
							'class': 'toggler' + (item.hasClass('toggled') ? ' toggled' : ''),
							href: '',
							events:
							{
								click: function()
								{
								   var handle = this.retrieve('handle');
									if(handle.options.togglers)
										toggler.set('text', this.retrieve('fxToggle').open ? handle.options.togglersChars.plus : handle.options.togglersChars.minus);
									this.toggleClass('toggled');
									this.retrieve('fxMorph').start({opacity: this.retrieve('fxToggle').open ? [1,0] : [0,1]});
									this.retrieve('fxToggle').toggle();

									return false;
								}
							}
						});

                  toggler.store('handle', this);
						toggler.store('fxMorph', new Fx.Morph(child, {duration: 500}));
						toggler.store('fxToggle', new Fx.Slide(child, {duration: 500, transition: 'quad:out', resetHeight: true, wrapper: wrapper}));

						if(!active) toggler.retrieve('fxToggle').hide();

						// Dont know really why, but with this style IE7 dont gets crazy
						if(Browser.ie7)
							wrapper.setStyle('position', 'relative');

						wrapper.adopt(child);
						item.adopt(wrapper);
						item.adopt(toggler);
						this.browse(child);
					}
				}

			}.bind(this));
		}
	}
});





// ---------------------------------------------------------------------------------------------------
// SlideShow
// ---------------------------------------------------------------------------------------------------
var _uiSlideShow = new Class(
{
	Implements: [Options],

	h: null,
	size: null,

	options:
	{
		images: true,
		delay: 6000,
		random: false,
		adjustSize: false,	 				// Adjust size to boxing element
		clickToFullSize: false,		 // This setting uses mediabox advanced
		description: false,				 // Show title of the image
		menu: false,
		onlyWidescreen: false,
		autoplay: true,

		position: {x: 'center', y: 'center'},
		menu: {enabled: false, title: false, clickable: false},

		effects:
		{
			transition: {enabled: true, els: null, morphs: null},
			slide: {enabled: false},
			move: {enabled: false, zoom: 2},
			stripes: {enabled: false, els: null, morphs: null, count: 5, width: '10%', background: '#fff', opacity: 0.3},
			bricks: {enabled: false, els: null, morphs: null, background: '#fff', opacity: 1, size: {x: 10, y: 10}}
		},

		controls:
		{
			proggress: false,
			timing: false
		},
		loading:
		{
			visible: true,
			delay: 500,
			progress: true,
			bgColor: '#fff'
		}
	},

	eDisplay: null,
	eMenu: null,
	eDescPos: null,
	eDesc: null,
	eDescInner: null,

	// Controls
	controls:
	{
		h: null,		// Controls window
		progress:
		{
			enabled: false,
			h: null,
			hDone: null,
			hCount: null
		},
		timing:
		{
			enabled: false,
			h: null,
			hText: null,
			hGraph: null
		}
	},


	// Images
	images: new Array(),
	loaded: 0,								// Preload status
	count: 0,		 						// Img count
	current: 0,
	timeout: 0,		 					//	Time
	timein: 0,
	dImgCheckLoad: null, 			// Delay before check


	// Loading
	eLoading: null,
	dLoadingStart: null,
	dLoadingStop: null,


	// Slides
	hPeriod: null,

	// Effects
	effects: null,


	initialize: function(e, imgs, opts)
	{
		this.h = e;
		this.h.setStyle('position', 'relative');
		this.h.setStyle('z-index', 0);

		e.addClass('ui-slideShow');

		this.size = this.h.getSize();
		this.setOptions(opts);

		this.options.delay = Math.round(this.options.delay/1000)*1000;	// Makes sure that only whole second were inputed

		this.iniDisplay();
		this.iniControls();
		this.iniEffects();
		this.iniDescription();

		if(this.options.random) imgs.sort(this.aRnd);
		this.count = imgs.length;
		for(var i=0; i<this.count; i++)
			this.options.images ? this.imgLoad(imgs[i]) : this.contentLoad(imgs[i]);

		if(this.options.menu.enabled) this.iniMenu();

		this.loadingStart();
		this.current = 0;
		if(this.options.images) this.display();

		this.timein	 = 0;
		this.timeout = this.options.delay/1000;

		if(this.images.length>1 && this.options.autoplay)
			this.hPeriod = this.autoplay.periodical(1000, this);
	},

	// ------------------------------------------------------------------------------------------------------------------------
	// Slideshow
	display: function()
	{
		if(this.options.menu.enabled)
		{
			for(var i=0; i<this.images.length; i++)
			{
				if(this.current==i) this.images[i].hMenu.addClass('active');
				else this.images[i].hMenu.removeClass('active');
			}
		}

		if(this.dImgCheckLoad)
		{
			clearInterval(this.dImgCheckLoad);
			this.dImgCheckLoad = null;
		}

		clearInterval(this.dLoadingStart);
		if(this.images.length>1)
			this.dLoadingStart = this.loadingStart.delay(this.options.delay-this.options.loading.delay, this);

		if(!this.images[this.current].completed)
		{
			this.eLoading.setStyles(
			{
//				'background-image': 'url("/img/common/loading.gif")',
				'background-position': (this.size.x/2-16)+'px '+(this.size.y/2-16)+'px',
				'background-repeat': 'no-repeat'
			});

			this.dImgCheckLoadProgress = true;
			this.dImgCheckLoad			= this.display.delay(75, this);
			return;
		}

		if(this.options.description && this.images[this.current].title)
		{
		   (function()
		   {
				this.eDescInner.set('text', this.images[this.current].title);
				this.eDesc.retrieve('fxMorph').start({opacity: [0,0.7]});
				this.eDesc.retrieve('fxSlide').slideIn();
			}.delay(600, this));
		}

		this.dLoadingStop = this.loadingStop.delay(this.options.loading.delay*2, this);

		if(!this.options.loading.visible) this.beginEffects();
		else this.eDisplay.empty();


		this.eDisplay.adopt(this.images[this.current].h);
	},


	autoplay: function()
	{
		if(this.timein==this.options.delay/1000)
		{
			this.timein	= 0;
			this.timeout = this.options.delay/1000;

			this.next(false);
		}
		else
		{
			this.timein++;
			this.timeout--;
		}

		this.controlsSetTiming();
	},
	next: function(manual)
	{
		this.endEffects();

		if(this.images.length>1 && this.options.description && this.images[this.current].title)
		{
			this.eDesc.retrieve('fxMorph').start({opacity: [0.7,0]});
			this.eDesc.retrieve('fxSlide').slideOut();
		}

		this.current++;
		if(this.current==this.count)
			this.current = 0;

		if(manual)
		{
			this.timein	= 0;
			this.timeout = this.options.delay/1000;
		}

		this.controlsSetTiming();
		this.display();
	},
	prev: function(manual)
	{
		this.endEffects();

		if(this.images.length>1 && this.options.description && this.images[this.current].title)
		{
			this.eDesc.retrieve('fxMorph').start({opacity: [0.7,0]});
			this.eDesc.retrieve('fxSlide').slideOut();
		}

		this.current--;
		if(this.current<0)
			this.current = this.count-1;

		if(manual)
		{
			this.timein	= 0;
			this.timeout = this.options.delay/1000;
		}

		this.controlsSetTiming();
		this.display();
	},
	setCurrent: function(current)
	{
		this.endEffects();

		if(this.images.length>1 && this.options.description && this.images[this.current].title)
		{
			this.eDesc.retrieve('fxMorph').start({opacity: [0.7,0]});
			this.eDesc.retrieve('fxSlide').slideOut();
		}

		this.current = current;

		this.timein	= 0;
		this.timeout = this.options.delay/1000;


		this.controlsSetTiming();
		this.display();
	},

	// ------------------------------------------------------------------------------------------------------------------------
	// Elements
	iniDisplay: function()
	{
		this.eDisplay = new Element('div',
		{
			'class': 'display',
			styles:
			{
				position: 'absolute',
				top: 0,
				left: 0,
				width: this.size.x+'px',
				height: this.size.y+'px',

				'text-align': 'center',
				overflow: 'hidden'
			},
			events:
			{
				click: function()
				{

				}.bind(this)
			}
		});

		this.h.adopt(this.eDisplay);
	},

	iniMenu: function()
	{
		this.eMenu = new Element('ul',
		{
			'class': 'menu'
		});

		for(var i=0; i<this.count; i++)
		{
			var li = new Element('li');

			var a = new Element('a',
			{
				text: this.options.menu.title ? this.images[i].title : '',
				rel: i
			});

			if(this.options.menu.clickable)
			{
			   a.set('href', '#');
				a.addEvent('click', function(el)
				{
					this.setCurrent(el.get('rel').toInt());

					return false;
				}.bind(this, a));
			}

			li.adopt(a);


			this.images[i].hMenu = li;
			this.eMenu.adopt(li);
		}

		this.h.adopt(this.eMenu);
	},

	iniControls: function()
	{
		this.controls.progress.enabled = this.options.controlsProgress;
		this.controls.timing.enabled	 = this.options.controlsTiming;


		this.controls.h = new Element('div',
		{
			'class': 'controls',
			styles:
			{
				position: 'absolute',
				'z-index': '1000'
			}
		});

		// Progress
		if(this.controls.progress.enabled)
		{
			this.controls.progress.h = new Element('span',
			{
				'class': 'progress'
			});
			this.controls.h.adopt(this.controls.progress.h);
		}

		// Timing
		if(this.controls.timing.enabled)
		{
			this.controls.timing.h = new Element('span', {'class': 'timing'});

			this.controls.timing.hText = new Element('label');
			this.controls.timing.h.adopt(this.controls.timing.hText);

			this.controls.timing.hGraph = new Element('span');
			this.controls.timing.h.adopt(this.controls.timing.hGraph);

			this.controls.h.adopt(this.controls.timing.h);
		}

		this.h.adopt(this.controls.h);
	},

	iniDescription: function()
	{
		if(this.options.description)
		{
			this.eDescPos = new Element('div',
			{
				'class': 'descPos',
				styles:
				{
					position: 'absolute',

					'z-index': 100
				}
			});

			this.eDesc = new Element('div',
			{
				'class': 'desc'
			});

			this.eDescInner = new Element('div',
			{
				'class': 'descInner'
			});

			this.eDesc.adopt(this.eDescInner);
			this.eDescPos.adopt(this.eDesc);
			this.h.adopt(this.eDescPos);

			this.eDesc.store('fxMorph', new Fx.Morph(this.eDesc, {duration: 500}));
			this.eDesc.store('fxSlide', new Fx.Slide(this.eDesc, {duration: 500, mode: 'horizontal', transition: 'quad:out', resetHeight: true}));
			this.eDesc.retrieve('fxMorph').set({opacity: 0});
			this.eDesc.retrieve('fxSlide').hide();
		}
	},


	// ------------------------------------------------------------------------------------------------------------------------
	// Loading
	loadingStart: function()
	{
		if(!this.eLoading)
		{
			this.eLoading = new Element('div',
			{
				styles:
				{
					position: 'absolute',
					top: 0,
					left: 0,
					width: this.size.x,
					height: this.size.y
				}
			});

			if(this.options.loading.progress)
				this.eLoading.setStyle('background', 'url("/img/_uiConstrols/loading.gif") no-repeat '+(this.size.x/2-16)+'px '+(this.size.y/2-16)+'px');
			if(this.options.loading.visible)
				this.eLoading.setStyle('background-color', this.options.loading.bgColor);



			this.fxLoading = new Fx.Morph(this.eLoading, {duration: this.options.loading.delay}).set({opacity: 0});
			this.fxLoading.start({opacity: [0,1]});

			this.h.adopt(this.eLoading);
		}
	},
	loadingStop: function()
	{
		if(this.eLoading)
		{
			this.fxLoading.start({opacity: [1,0]});

			(function()
			{
				if(this.eLoading)
				{
					this.eLoading.dispose();
					this.fxLoading = null;
					this.eLoading	= null;
				}
			}.delay(this.options.loading.delay, this));
		}
	},

	// ------------------------------------------------------------------------------------------------------------------------
	// Effects
	iniEffects: function()
	{
	   this.effects   = new Object();
	   var effectName = '';

		// Transition
		if(this.options.effects.transition.enabled)
		{
		   var efTransition    = this.options.effects.transition;
			efTransition.els    = new Array();
			efTransition.morphs = new Array();

		   effectName = 'transition';
		   this.effects[effectName] = new Object();

			this.effects[effectName].fnB = function()
			{
			   var efTransition = this.options.effects.transition;

				this.images[this.current].h.setStyle('opacity', 0);
				efTransition.morphs[this.current] = new Fx.Morph(this.images[this.current].h, {duration: this.options.loading.delay*3});
				efTransition.morphs[this.current].start({opacity: [0,1]});
			}.bind(this);


			this.effects[effectName].fnE = function()
			{
            var current = this.current;

			   if(this.images.length>1)
			   {
					var efTransition = this.options.effects.transition;

					if(efTransition.morphs.length)
					{
						efTransition.morphs[current].start({opacity: [1,0]});
						//this.images[current].h.setStyle('z-index', this.images[current].h.getStyle('z-index').toInt()+1);

						(function()
						{
							this.dispose();
							//this.setStyle('z-index', 0);
						}.delay(this.options.loading.delay*3, this.images[current].h));
					}
				}

			}.bind(this);
		}


		// Slide
		if(this.options.effects.slide.enabled)
		{
		   effectName = 'slide';
		   this.effects[effectName] = new Object();


			this.effects[effectName].fnB = function()
			{
				// Should prevents from blinking when position changing
				this.images[this.current].h.setStyle('left', this.images[this.current].h.getStyle('width'));

				new Fx.Morph(this.images[this.current].h, {duration: this.options.loading.delay*4}).start(
				{
					left: [this.images[this.current].h.width ? this.images[this.current].h.width: this.images[this.current].width, this.images[this.current].left]
				});

			}.bind(this);
		}


		// Move
		if(this.options.effects.move.enabled)
		{
         effectName = 'move';
		   this.effects[effectName] = new Object();

			this.effects[effectName].fnB = function()
			{
				if(this.images.length>1)
				{
				   var isImgSmallerV = this.images[this.current].h.width<(this.size.x*this.options.effects.move.zoom);
				   var isImgSmallerH = this.images[this.current].h.height<(this.size.y*this.options.effects.move.zoom);

				   var multiply = isImgSmallerV || isImgSmallerH;

					var w = this.images[this.current].h.width*(multiply ? 1 : this.options.effects.move.zoom);
					var h = this.images[this.current].h.height*(multiply ? 1 : this.options.effects.move.zoom);

	 				this.images[this.current].h.setStyles(
					{
						width: w,
						height: h
					});

					var centerV = this.size.x/2-w/2;
					var centerH = this.size.y/2-h/2;

					// check performance on this
					new Fx.Morph(this.images[this.current].h, {duration: this.options.delay+(this.options.loading.delay*5)}).start({
						top: isImgSmallerH ? [centerH, centerH] : [-this.rnd(0,h-this.size.y), -this.rnd(0,h-this.size.y)],
						left: isImgSmallerV ? [centerV, centerV] : [-this.rnd(0,w-this.size.x), -this.rnd(0,w-this.size.x)]
					});
				}
			}.bind(this);
		}

		// Stripes
		if(this.options.effects.stripes.enabled)
		{
		   effectName       = 'stripes';

			var efStripes    = this.options.effects.stripes;
			efStripes.els    = new Array();
			efStripes.morphs = new Array();

			this.effects[effectName] = new Object();

		   for(var i=0; i<efStripes.count; i++)
		   {
		      efStripes.els[i] = new Element('div',
				{
				   styles:
				   {
				      position: 'absolute',
				      top: 0,
				      bottom: 0,
				      width: efStripes.width,
				      left: this.rnd(0,this.size.x),

				      background: efStripes.background,
				      opacity: efStripes.opacity,
				      'z-index': 10
				   }
				});

				this.eDisplay.adopt(efStripes.els[i]);

				efStripes.morphs[i] = new Fx.Morph(efStripes.els[i], {duration: this.options.delay+this.options.loading.delay});
			}

			this.effects[effectName].fnB = function()
			{
			   var efStripes = this.options.effects.stripes;
			   var l         = efStripes.els.length;

			   for(var i=0; i<l; i++)
			   {
					efStripes.morphs[i].start(
					{
						left: [efStripes.els[i].getStyle('left').toInt(), this.rnd(0, this.size.x)]
					});
			   }

			}.bind(this);
		}

		// Bricks
		if(this.options.effects.bricks.enabled)
		{
		   effectName = 'bricks';
		   this.effects[effectName] = new Object();

			var efBricks    = this.options.effects.bricks;
			efBricks.els    = new Array();
			efBricks.morphs = new Array();

			var w = this.size.x/efBricks.size.x;
			var h = this.size.y/efBricks.size.y;

			var i = 0;
			var offset = 0;
		   for(var x=0; x<efBricks.size.x; x++)
		   {
			   for(var y=0; y<efBricks.size.y; y++)
			   {
			      efBricks.els[i] = new Element('div',
					{
					   styles:
					   {
					      position: 'absolute',
					      top: y*w,
					      width: w,
					      height: h,
					      left: x*h,

					      background: 'no-repeat -'+(x*h)+'px -'+(y*w)+'px',
					      opacity: efBricks.opacity,
					      'z-index': 10
					   }
					});

					this.eDisplay.adopt(efBricks.els[i]);

					efBricks.morphs[i] = new Fx.Morph(efBricks.els[i], {duration: this.options.loading.delay+550+(x*this.rnd(0, 100))});

					i++;
				}
			}

			this.effects[effectName].fnB = function()
			{
			   var efBricks = this.options.effects.bricks;
			   var l         = efBricks.els.length;

			   for(var i=0; i<l; i++)
				{
				   efBricks.els[i].setStyle('background-image', 'url(\''+this.images[this.current].h.src+'\')');
					efBricks.morphs[i].start({opacity: [0, efBricks.opacity]});
				}

			}.bind(this);

			this.effects[effectName].fnE = function()
			{

			   var efBricks = this.options.effects.bricks;
			   var l         = efBricks.els.length;

			   for(var i=0; i<l; i++) efBricks.morphs[i].start({opacity: [efBricks.opacity, 0]});
			}.bind(this);
		}
	},

	beginEffects: function()
	{
		for(var i in this.effects)
			if(this.effects[i].fnB) this.effects[i].fnB();
	},

	endEffects: function()
	{
		for(var i in this.effects)
			if(this.effects[i].fnE) this.effects[i].fnE();
	},


	// ------------------------------------------------------------------------------------------------------------------------
	// IMG loading
	imgLoad: function(img)
	{
		if(!img) return false;
		if(img.src==null) return false;

		var data =
		{
			h: null,
			width: 0,
			height: 0,
			top: 0,
			left: 0,
			ratio: 0,
			title: img.title,
			link: img.link,
			hMenu: null,
			completed: false
		};

		data.h = new Element('img',
		{
			src: img.src,
			alt: img.title,
			//morph: {duration: this.options.loading.delay*5},
			styles:
			{
				position: 'absolute',
				top: 0,
				left: 0,

				'z-index': 0
			}
		});

		this.images.push(data);

		data.h.addEvent('load', function(image)
		{
			this.loaded++;
			this.controlsSetProgress();

			//var image = this.images[i];

			if(this.options.onlyWidescreen)
			{
			   if(image.h.width<image.h.height)
			   {
				   image.h.destroy();
				   this.images.erase(image);
				   this.count = this.images.length;

				   return;
			   }
			}


			image.width	= image.h.width;
			image.height = image.h.height;


			// Adjust size to boxing element
			if(this.options.adjustSize)
			{
				image.ratio = image.h.width>image.h.height ? image.h.width/this.size.x : image.h.height/this.size.y;

				image.h.width	/= image.ratio;
				image.h.height /= image.ratio;
			}

			// Center both vertical and horizontal or other
			switch(this.options.position.x)
			{
			   case 'center':	image.left = this.size.x/2-image.h.width/2; break;
			   case 'left':	image.left = 0; break;
			   case 'right':	image.left = this.size.x-image.h.width; break;
			   default:			image.left = this.options.position.x; break;
			}
			switch(this.options.position.y)
			{
			   case 'center':	image.top = this.size.y/2-image.h.height/2; break;
			   case 'top':		image.top = 0; break;
			   case 'bottom':	image.top = this.size.y-image.h.height; break;
			   default:			image.top = this.options.position.y; break;
			}

			image.h.setStyles(
			{
				top: image.top,
				left: image.left
			});

			if(img.link)
			{
				image.h.setStyle('cursor', 'pointer');
				image.h.addEvent('click', function()
				{
					window.location = this;
				}.bind(img.link));
			}
			else if(this.options.clickToFullSize)
			{
				image.h.setStyle('cursor', 'pointer');
				image.h.addEvent('click', function()
				{
					Mediabox.open(this.h.src, this.h.alt, 'mediabox['+this.width+' '+this.height+']');
				}.bind(image));
			}

			//document.id('debug').innerHTML += '<p>'+JSON.encode(image)+'</p>';
			image.completed = true;
		}.bind(this, this.images[this.images.length-1]));

		/*
		data.h.addEvent('mousewheel', function()
		{
			new Request({url: this.src}).send();
		});
		*/
	},


	// ------------------------------------------------------------------------------------------------------------------------
	// Content loading
	contentLoad: function(content)
	{
		var data =
		{
			h: null,
			width: 0,
			height: 0,
			top: 0,
			left: 0,
			ratio: 0,
			title: content.title,
			hMenu: null,
			completed: true
		};

		data.h = content;

		var size = content.getSize();

		data.width  = size.x;
		data.height = size.y;

		content.setStyles(
		{
			position: 'absolute',
			top: 0,
			bottom: 0,
			left: 0,
			right: 0,
			'z-index': 0
		});

		this.images.push(data);
	},


	// Controls functions
	controlsSetProgress: function()
	{
		if(this.controls.progress.enabled)
		{
			this.controls.progress.h.set('text', 'Nahráno '+this.loaded+' z '+this.count+' obrázků');
		}
	},
	controlsSetTiming: function()
	{
		if(this.controls.timing.enabled)
		{
//			this.controls.timing.hText.set('text', 'Další obrázek za '+this.timeout+'s.');
			var fx = new Fx.Morph(this.controls.timing.hGraph, {duration: 700, unit: '%'});


			fx.start({width: (this.timeout/(this.options.delay/1000)*100)+'%'});
		}
	},


	aRnd: function()
	{
		return (Math.floor(Math.random()*5));
	},
	rnd: function(min, max)
	{
		return Math.random()*(max - min);
	}

});



// ---------------------------------------------------------------------------------------------------
// Toggler
// ---------------------------------------------------------------------------------------------------
var _uiToggler = new Class(
{
	Implements: [Options],
	fxm: null,
	fxs: null,
	
	toggled: false,

	linkedTogglers: null,   // static instance of linked sets

	options:
	{
		toggler: null,
		element: null,

		timeout: 100,
		linker: null,  // name of linked set
		opacity: {max: 1, min: 0},
		wrapperName: 'mtWrapper',
		wrapperElement: null,
		
		onMouseHover: false
	},

	initialize: function(opts)
	{
	   this.setOptions(opts);
	   if(!this.options.toggler && !this.options.element) return false;

	   if(this.options.timeout<500) this.options.timeout = 500;

		if(!this.options.wrapperElement)
		{
	      var wrapper = new Element('div', {'class': this.options.wrapperName});
	      this.options.element.getParent().adopt(wrapper);
	      wrapper.adopt(this.options.element);
      }
      else
      {
         wrapper = this.options.wrapperElement;
      }

		this.fxm = new Fx.Morph(this.options.element, {duration: this.options.timeout, link: 'cancel'}).set({opacity: 0});
		this.fxs = new Fx.Slide(this.options.element, {duration: this.options.timeout, mode: 'vertical', transition: 'quad:out', resetHeight: true, wrapper: wrapper, hideOverflow: !false, link: 'cancel'}).hide();


		if(this.options.linker)
		{
		   if(!_uiToggler.linkedTogglers)
    			_uiToggler.linkedTogglers = {};

		   if(_uiToggler.linkedTogglers[this.options.linker])
		   {
		      _uiToggler.linkedTogglers[this.options.linker].push(this);
		   }
		   else
		   {
		      _uiToggler.linkedTogglers[this.options.linker] = new Array();
		      _uiToggler.linkedTogglers[this.options.linker].push(this);
		   }
		}
		
		if(this.options.onMouseHover)
		{
         this.options.toggler.addEvent('mouseenter', function()
			{
				this.toggled = true;
				this.onAction();
			}.bind(this));
         this.options.toggler.addEvent('mouseout', function()
			{
				this.toggled = false;
				this.onAction();
			}.bind(this));
		}
		else
		{
			this.options.toggler.addEvent('mouseup', function()
			{
				this.toggled = !this.toggled;
				this.onAction();
			}.bind(this));
		}
	},
	
	onAction: function()
	{
	   this.fxm.start({opacity: !this.toggled ? [this.options.element.getStyle('opacity'),this.options.opacity.min] : [this.options.element.getStyle('opacity'),this.options.opacity.max]});
      this.toggled ? this.fxs.slideIn() : this.fxs.slideOut();


		this.toggled ? this.options.toggler.addClass('actived') : this.options.toggler.removeClass('actived');
		//this.toggled = !this.toggled;


	   if(this.options.linker)
	   {
		   var length = _uiToggler.linkedTogglers[this.options.linker].length;

		   for(var i=0; i<length; i++)
		   {
		      var toggler = _uiToggler.linkedTogglers[this.options.linker][i];
			   if(toggler.fxs.open && this!=toggler)
				{
					toggler.fxm.start({opacity: [toggler.options.element.getStyle('opacity'), toggler.options.opacity.min]});
			   	toggler.fxs.slideOut();
			   	toggler.toggled = false;
			   	this.options.toggler.removeClass('actived');
			   }
		   }
	   }

	   if(this.options.toggler.get('type')!='checkbox')
	   	return false;
	}
});


var _uiGreyHoverImages = new Class(
{

	initialize: function(scope)
	{
		scope.getElements('img').each(function(e)
		{
		   e.addEvent('load', function()
		   {
			   var container = e.getParent();
			   var eSize     = e.getSize();
			   var cSize     = container.getSize();

			   container.setStyles(
			   {
			      position: 'relative'
			   });

			   e.setStyles(
			   {
			      position: 'absolute',
			      left: cSize.x/2-(eSize.x/2),
			      top: cSize.y/2-(eSize.y/2),
			      'z-index': 1
			   });
			   
			   e.addEvents(
			   {
					mouseenter: function()
		         {
		            this.retrieve('fx').start({opacity: [0,0.8], visibility: ['hidden', 'visible']});
		            return false;
		         },
		         mouseout: function()
		         {
		            this.retrieve('fx').start({opacity: [0.8,0], visibility: ['hidden', 'visible']});
		            return false;
		         }
			   });

			   var greyimg = new Element('img',
			   {
			      alt: e.get('alt')+'-grey',
			      styles:
			      {
			         position: 'absolute',
				      left: cSize.x/2-(eSize.x/2),
				      top: cSize.y/2-(eSize.y/2),
						width: e.get('width'),
						height: e.get('height'),
			      	'z-index': 0,
			      	opacity: 0.6
			      }
				});
				
	   		if(Browser.name=='ie')
				{
				   greyimg.set('src', e.get('src'));
					greyimg.setStyle('filter', 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)');
				}
	   		else greyimg.set('src', this.toGrey(e.get('src')));

			   e.store('fx', new Fx.Morph(e,{link: 'chain'}).set({opacity: 0, visibility: 'visible'}));
			   container.adopt(greyimg);
			   
		   }.bind(this));

		}.bind(this));
	},
	
	toGrey: function(src)
	{
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var imgObj = new Image();
		imgObj.src = src;
		canvas.width = imgObj.width;
		canvas.height = imgObj.height;
		ctx.drawImage(imgObj, 0, 0);
		var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
		for(var y = 0; y < imgPixels.height; y++){
			for(var x = 0; x < imgPixels.width; x++){
				var i = (y * 4) * imgPixels.width + x * 4;
				var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
				imgPixels.data[i] = avg;
				imgPixels.data[i + 1] = avg;
				imgPixels.data[i + 2] = avg;
			}
		}
		ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
		return canvas.toDataURL();
	 }
});


// ---------------------------------------------------------------------------------------------------
// Form Valid
// ---------------------------------------------------------------------------------------------------
var _uiFormValidator = new Class(
{
	orig: null,

	initialize: function(e)
	{
		var formValidator = new Form.Validator(e,
		{
			evaluateFieldsOnBlur: false,
			evaluateFieldsOnChange: true
		});

		formValidator.addEvent('formValidate', function(passed, form, ev)
		{
			if(!passed)
			{
				alert('Formulář není správně vyplňen');
			}
		});

		formValidator.add('cc_atleast1',
		{
				errorMsg: 'Vyplňte toto pole',
				test: function(el)
				{
						if(!el.value.length) return false;
						else return true;
				}
		});
		formValidator.add('cc_atleast4',
		{
				errorMsg: 'Vyplňte aspoň 4 znaky',
				test: function(el)
				{
						if(el.value.length<4) return false;
						else return true;
				}
		});
		formValidator.add('cc_pass',
		{
				errorMsg: 'Hesla nesouhlasí',
				test: function(el)
				{
						if(el.value.length<4) return false;
						else return true;
				}
		});
		formValidator.add('cc_email',
		{
				errorMsg: 'Špatně zadaný formát emailu',
				test: function(el)
				{
						if(el.value.match(new RegExp('^\\w(\\w|-|\\.)*@(\\w|-|\\.)+\\.\\w+$'))==null) return false;
						else return true;
				}
		});
		formValidator.add('cc_phone',
		{
				errorMsg: 'Špatně zadaný formát telefonního čísla',
				test: function(el)
				{
						if(el.value.match(new RegExp('^((\\+|00){0,1}\\d{3} {0,1}){0,1}\\d{3} {0,1}\\d{6}$'))==null) return false;
						else return true;
				}
		});
		formValidator.add('cc_phone_short', //bez predcisli
		{
				errorMsg: 'Špatně zadaný formát telefonního čísla',
				test: function(el)
				{
						if(el.value.match(new RegExp('^\\d{9}$'))==null) return false;
						else return true;
				}
		});
		formValidator.add('cc_postal',
		{
				errorMsg: 'Špatně zadaný formát poštovního čísla',
				test: function(el)
				{
						if(el.value.match(new RegExp('^\\d{3} {0,1}\\d{2,3}$'))==null) return false;
						else return true;
				}
		});
		formValidator.add('cc_login',
		{
				errorMsg: 'Špatně zadaný login',
				test: function(el)
				{
						if(el.value.match(new RegExp('^\\w*$'))==null) return false;
						else return true;
				}
		});
	}
});



