var URPopup = new Class( {
	Implements: [Options, Events], 
		options: {
			type			: 	'alert',
			validation_text	: 	'OK',
			prompt_default	:   false,
			focus			:   'button.validate',
			morphDuration	: 	275,
			morphTransition :   'back:out',
			chainable		: 	false,
			displayButtons	: 	true,
			onValidate		: 	false,
			onCancel		: 	false
		},

	initialize: function(content, options) {		
		this.defaultOptions = this.options;
		this.values = false;
		this.showPopup();
		this.refresh(content, options);
		
		this.loadingElement = new Element('div');
		this.loadingElement
		    .adopt( new Element('img', {
		    'src':  staticsHost + '/img/loading_negative.gif'
		}) ).adopt( new Element('span', {
		    'html':  _("Loading...")
		}) ).addClass('loading');
		
	},
	
	resetOptions: function()
	{
		this.options = this.defaultOptions;
	},
	
    refresh: function(content, options) {
		this.oldWidth = this.options.width;
		this.oldHeight = this.options.height;

		this.removeEvents();
		this.resetOptions();
		
		this.setOptions(options);		
			
		if( $('divContent') )
		{	
			$('divContent').dispose();
		}
		
		this.content = new Element( 'div', {
			'id'	: 'divContent',
			'styles': {
				'position'			: 	'absolute',
				'display'		: 	'none'
			}
		} );
		
		switch( typeof( content ) )
		{
			case 'number':
				content = new String(content);
			case 'string':
				if( !content.match(/>/i) )
				{
					content = content.replace(/\n/gi, '<br />');
					
					new Element('p', {
						'html': content,
						'styles': {
							'max-width': '500px'
						}
					}).inject( this.content );
				}
				else
				{
					this.content.set( 'html', content );
				}
				break;
			default:
				this.content.adopt( content );
				break;
		}
		
		if(this.options.type == 'prompt' )
		{
			this.content.adopt( new Element('input', {
				'id'		: 'prompt_value',
				'name'		: 'prompt_value',
				'value'		: ( this.options.prompt_default ? this.options.prompt_default : null ),
				'styles'	: {
					'margin-top' : '10px'
				}
			}) );
		}

		document.getElement('body').adopt( this.content );
		
		if(this.options.type == 'prompt' )
		{
			this.options.focus = '#prompt_value';
		}

		if( this.options.width )
		{
			$('divContent').setStyle( 'width', this.options.width );
		}

		if( this.options.height )
		{
			$('divContent').setStyle( 'height', this.options.height );
		}
		
		if ( this.options.displayButtons )
		{
			this.buttons = new Object();
			this.setButtons();
		}
		
		this.padding = 30;
		
		var tmpThis = this;
		this.content.measure( function() {
			if( !tmpThis.options.width )
			{
				tmpThis.options.width = this.getSize().x;
			}

			if( !tmpThis.options.height )
			{
				tmpThis.options.height = this.getSize().y;
			}
			
		} );
		this.setContainer();
	},
	
	loading: function()
	{
	    this.options.chainable = true;
	    this.refresh( this.loadingElement, {
	        chainable: true,
			displayButtons: false
		} );
	},

	showPopup: function(callBack, minHeight, anOpacity, aColor) {
		var opacity = $chk(anOpacity) ? anOpacity : 0.5;
		var color = $chk(aColor) ? aColor : '#000';

		if( !$chk( $('darkPopup') ) )
		{
			var mask = new Element('div').setProperty('id', 'darkPopup').setStyles({
				'position': 'fixed',
				'display': 'none',
				'z-index': 999,
				'top': '0px',
				'left': '0px',
				'right': '0px',
				'bottom': '0px',
				'text-align': 'center'
			}).injectInside( document.getElement('body') );

			$('darkPopup').removeEvents().addEvent('click', function() {
				this.fireEvent('backgroundclick');
			}.bindWithEvent(this));

			if( Browser.Engine.trident4 )
			{
				mask.setStyles({
					'position': 'absolute'
				});
			}
		}

		window.fireEvent('darkPopupWillShow');
		var myFx = new Fx.Tween("darkPopup", {
			duration: 200,
			fps: 15,
			onStart: function()
			{
				$('darkPopup').setStyles(
					{
						display: "block",
						opacity: 0,
						backgroundColor: color,
						padding: 0,
						margin: 0
					}
				);
			},
			onComplete: function()
			{
				window.fireEvent('darkPopupHasShown');
				if ( $chk(callBack) )
				{
					callBack();
				}
				window.fireEvent('darkPopupCallbackCalled');
			}
		});
		myFx.start( "opacity", 0, opacity );
	},

	hidePopup: function( force ) {
		this.fetchValues();
		
		if ( this.options.chainable )
		{
			this.stop_event = true;
		}
		
		if( !this.stop_event || force )
		{
			$('divContainer').dispose();
			$('darkPopup').setStyle('display', 'none');
		}
		this.stop_event = false;
	},
	
	stop: function()
	{
		this.stop_event = true;
	},
	
	stopPropagation: function()
	{
		this.stop();
	},

	setContainer: function() {
		var tmpLeft, tmpTop;
		if( !$('divContainer') )
		{
			tmpLeft = window.getScrollLeft() + ( window.getWidth() - this.options.width ) / 2;
			tmpTop = window.getScrollTop() + ( window.getHeight() - this.options.height ) / 2;

			var divContainer = new Element('div', {
				'id': 'divContainer',
				'styles': {
					'padding'			: 	this.padding/2 + 'px',
					'padding-bottom'	:   0,
					'top'				: 	tmpTop + this.options.height/2 + 'px',
					'left'				: 	tmpLeft + this.options.width/2 + 'px',
					'overflow'			: 	'hidden'
				}
			}).adopt( new Element( 'div', {
				'id'	: 	'divBrush',
				'styles' : {
					'opacity': 0,
					'width': (this.options.width + this.padding),
					'height': (this.options.height + this.padding / 2)
				}
			} ) );

			$('darkPopup').getParent().adopt( divContainer );
		}
		
		$('divContainer').set('morph', { "duration": this.options.morphDuration, "transition": this.options.morphTransition });
		
		$('divContainer').get('morph').addEvent('complete', function(){
			this.setContent( this.content );
			$('divBrush').setStyle('opacity', 0.26);
			$('divBrush').setStyles( { 'width': this.options.width + this.padding, 'height': this.options.height + this.padding / 2 } );
			switch(this.options.type )
			{
				case 'prompt':
					$E(this.options.focus).select();
					break;
				default:
					if( this.options.displayButtons )
					{
						$E(this.options.focus).focus();
					}
					break;
			}
		}.bind(this));
		
		tmpTop = window.getScrollTop() + ( window.getHeight() - this.options.height ) / 2;
		tmpLeft = window.getScrollLeft() + ( window.getWidth() - this.options.width ) / 2;
		
		var newSize = {
			'width'	: 	this.options.width,
			'height': 	this.options.height,
			'top'	: 	tmpTop,
			'left'	: 	tmpLeft
		};

		$('divContainer').morph( newSize );
		
		$('divContainer').removeEvents().addEvent( 'keyup', function(evt) {
			switch( evt.key )
			{
				case 'enter':
					if( evt.target.get('tag') != 'textarea' )
					{
						this.hidePopup();
						this.fireEvent('validate', [this, this.getValue('prompt_value')]);
					}
					break;

				case 'esc':
					this.fireEvent('cancel', [this]);
					this.hidePopup(true);
					break;
			}
		}.bindWithEvent(this) );
	},

	getValue: function(name) {
		return this.getValues()[name];
	},

	getValues: function() {
		if( !this.values )
		{
			this.fetchValues();
		}
		
		return this.values;
	},
	
	fetchValues: function() {
		this.values = new Object();
		
		$('divContainer').getElements('input').forEach( function(item, index) {
			switch( item.getProperty('type') )
			{
			 	case 'checkbox': 	
					if( item.getProperty('checked') )
					{
						if( !this.values[item.getProperty('name')] )
						{
							this.values[item.getProperty('name')] = new Array();
						}
						this.values[item.getProperty('name')].push(item.get('value')) ;
					}
					break;
				case 'text':
				case 'radio':
				case 'hidden':
				case 'password':
				default:
					this.values[item.getProperty('name')] = item.get('value');
			}
		}.bind(this));
		
		$('divContainer').getElements('select').forEach( function(item, index) {
			this.values[item.getProperty('name')] = item.get('value');
		}.bind(this));
		
		$('divContainer').getElements('textarea').forEach( function(item, index) {
			this.values[item.getProperty('name')] = item.get('value');
		}.bind(this));
			
		return this.values;
	},

	setContent: function(content) {
		content.setStyles({
			'display': 	'block',
			'width'		: 	this.options.width + 1 + 'px',
			'height'	: 	this.options.height + 'px'
		});
		
		// Hack IE
		if( Browser.Engine.trident )
		{
			content.setStyles({
				'top'	: 	this.padding/2,
				'left'	: 	this.padding/2
			});
		}

		$('divContainer').adopt( content );

		if ( this.options.displayButtons )
		{
			$E('.formButtons').setStyles({
				'position'	: 	'absolute',
				'width'		: 	this.options.width + 'px'
			});
		
			if( Browser.Engine.trident )
			{
				$E('.formButtons').setStyles({
					'left'	: 	0
				});
			}
		}
	},

	setButtons: function() {
		var divButtons = new Element('div', {
			'class'	: 'formButtons'
		});

		if( this.options.type == 'confirm' || this.options.type == 'prompt' )
		{
			this.buttons.cancel = new Element('button', {
				'type'	: 	'button',
				'class'	: 	'urBtn iepng small smallBlack cancel'
			}).adopt(
				new Element('span', {
					'class'	: 	'iepng urBtnLabel',
					'html'	: 	_("Cancel")
				})).addEvent( 'click', function(){
					this.fireEvent('cancel', [this]);
					this.hidePopup(true);
				}.bindWithEvent( this)  );

			divButtons.adopt( this.buttons.cancel );
		}

		this.buttons.validate = new Element('button', {
			'type'	: 	'button',
			'class'	: 	'urBtn iepng green validate'
		}).adopt(
			new Element('span', {
				'class'	: 	'iepng urBtnLabel',
				'html'	: 	this.options.validation_text
			}));

		divButtons.adopt( this.buttons.validate ).inject( this.content );

		this.buttons.validate.removeEvents().addEvent('click', function() {
			this.hidePopup();
			this.fireEvent('validate', [this, this.getValue('prompt_value')]);
		}.bindWithEvent( this ) );
	}
});

uralert = function(text, callback)
{
	return new URPopup(text, {"onValidate": callback});
};

urconfirm = function(text, callback)
{
	if( !callback )
	{
		throw new Error('Callback is mandatory');
	}
	return new URPopup(text, {'type': 'confirm', 'onValidate': callback});
};

urprompt = function(text, default_text, callback)
{
	if( !callback )
	{
		throw new Error('Callback is mandatory');
	}
	return new URPopup(text, {'type': 'prompt', 'prompt_default' : default_text, 'onValidate': callback});
};