var _shortenUrl = window.IPBoard;

_shortenUrl.prototype.shortenUrl = {
	popup: '',
	init: function()
	{
		Debug.write("Initializing ips.shortenUrlPopup.js");
		
		document.observe("dom:loaded", function(){
			ipb.shortenUrl.initEvents();
		});
	},
	
	/* ------------------------------ */
	/**
	 * Initialize events
	*/
	initEvents: function()
	{
		if ( $( 'openShortenUrlPopup' ) )
		{
			$( 'openShortenUrlPopup' ).observe( 'click', ipb.shortenUrl.openPopup );
		}
	},

	openPopup: function(e)
	{
		Event.stop(e);
		
		var _url  = ipb.vars['base_url'] + '&app=core&module=ajax&secure_key=' + ipb.vars['secure_hash'] + '&section=shortenurl&do=getForm';
		
		ipb.shortenUrl.popup = new ipb.Popup( 'shortenUrl', 
		{ 
			type: 'pane',
			ajaxURL: _url,
			stem: true,
			modal: true,
			hideAtStart: false,
			close: '.cancel',
			w: '400px' 
		}, 
		{ 
			'afterAjax': ipb.shortenUrl.callback,
			'afterHide': function(popup) { popup.kill() }
		});
	},
	
	callback: function( e )
	{
		$('doShortenUrl').observe( 'click', ipb.shortenUrl.doShortenUrl );
		
		$( 'urlToShorten' ).observe( 'focus', function()
		{
			if ( $F( 'urlToShorten' ) == 'http://' )
			{
				$( 'urlToShorten' ).value = "";
			}
		});
		
		$( 'doShortenCurrentUrl' ).observe( 'click', function(e)
		{
			$( 'urlToShorten' ).value = document.location.href;
			ipb.shortenUrl.doShortenUrl(e);
		});
	},

	doShortenUrl: function(e)
	{
		Event.stop(e);
		
		new Ajax.Request( ipb.vars['base_url'] + '&app=core&module=ajax&section=shortenurl&do=doShorten',
		{
			method: 'post',
			evalJSON: 'force',
			parameters: {
				'url': 		$F( 'urlToShorten' ).encodeParam(),
				'api': 		$F( 'shortenApi' ).encodeParam(),
				secure_key: ipb.vars['secure_hash']
			},
			onSuccess: function(t)
			{
				/* Check */
				if( t.responseJSON['error'] )
				{
					$( 'shortenedUrl' ).update( '' ).hide();
					$( 'shortenUrlError' ).update( t.responseJSON['error'] ).show();
				}
				else
				{
					$( 'shortenUrlError' ).update( '' ).hide();
					$( 'shortenedUrl' ).update( t.responseJSON['url'] );
					
					if ( $( 'shortenedUrl' ).visible() )
					{
						Effect.Pulsate( $( 'shortenedUrl' ), { pulses: 5, duration: 1.5 } );
					}
					else
					{
						new Effect.Appear( $( 'shortenedUrl' ) );
					}
					
				}
				/* Re-init events */
				ipb.shortenUrl.callback();
				return;
			}
		});
	}
};

ipb.shortenUrl.init();
