var URLPARSER_SERVICE = 'urlparser.php';

function showUrlParser()
{
	new Effect.Appear('urlparser', {duration: 0.5, queue: 'end'});
}

function closeUrlParser()
{
	new Effect.Fade('urlparser', {duration: 0.5, queue: 'end'});
}

var UrlParserPortal = Class.create();

Object.extend(Object.extend(UrlParserPortal.prototype, AsynchConduit.prototype), 
{
	initialize: function (url, panel_id) 
	{	
		this.initConduit((url || URLPARSER_SERVICE), panel_id);
		this.initConduitOptions(arguments[2]);
		
		this.active = false;
		this.attachParseEvents();
	},
	
	attachParseEvents: function ()
	{
		Event.observe($('urlparse_btn'), 'click', 
				this.processUrlHook.bindAsEventListener(this), false);
		Event.observe($('history_btn'), 'click', 
				this.showHideHistoryHook.bindAsEventListener(this), false);
		Event.observe($('clear_btn'), 'click', 
				this.truncateHistoryHook.bindAsEventListener(this), false);
		$('clear_btn').disabled = true;
		$('history_btn').disabled = true;
	},
	
	showHideHistoryHook: function (event)
	{
		if ($F('history_btn') == 'Show')
		{
			$('history_btn').value = 'Hide';
			new Effect.SlideDown('history_panel', {duration: 0.5});
		}
		else
		{
			$('history_btn').value = 'Show';
			new Effect.SlideUp('history_panel', {duration: 0.5});
		}
	},
	
	truncateHistoryHook: function (event)
	{
		if ($('history_btn').value == 'Hide')
		{
			new Effect.Fade('history_panel', {duration: 0.5});
			$('history_btn').value = 'Show';
		}
		
		var historyPanel = $('history_panel');
		while (historyPanel.firstChild)
		{
			historyPanel.removeChild(historyPanel.firstChild);
		}
		
		$('clear_btn').disabled = true;
		$('history_btn').disabled = true;
	},
	
	processUrlHook: function (event)
	{
	//	alert('processUrlHook:' + $F('url_ta'));
		this.processUrl($F('url_ta'));
	},
	
	processUrl: function (url)
	{
		this.sendRequest("url_ta=" + encodeURIComponent(url), { 
			method: 'post',
			captureResponse: this.handleResponse.bind(this)
//			captureResponse: function (element, response)
//			{
//			//	alert('processUrl: ' + response);
//				$(element).innerHTML = response;
//			}
		});
	},
	
	handleResponse: function (element, response)
	{
		if (!$('history_btn').disabled)
		{
			this.moveLinkToHistory($(element).innerHTML);
		}
		else if (this.active)
		{
			this.moveLinkToHistory($(element).innerHTML);
			$('clear_btn').disabled = false;
			$('history_btn').disabled = false;
		}
		
		$(element).innerHTML = response;
		this.active = true;
	},
	
	moveLinkToHistory: function (link)
	{
		var historyPanel = $('history_panel');
		var historyDiv = document.createElement('DIV');
		historyDiv.className = "historyentry";
		historyDiv.innerHTML = this.container.innerHTML;
		historyPanel.insertBefore(historyDiv, historyPanel.firstChild);
	}
});
