document.observe('dom:loaded', function(){new HP.RSSFeed();});

HP.RSSFeed = Class.create({
	initialize: function(){
		this.element = $("addRssFeed");
		
		this.form = this.element.select('form').first();
		this.messaging = $('messaging');
		this.input = $('feedURL');
		this.addBtn = $('addBtn');
		this.mainMessage = $('mainMessage');
		this.error = $('error');
		this.tips = $('tips');
		this.success = $('success');
		
		this.waitingMsg = '...checking for RSS feed...';
		this.successMsg = 'This feed has been successfully added. Add another?';
		
		Event.observe(this.addBtn, 'click', this.submitFeed.bind(this));
		Event.observe(this.form, 'keypress', this.submitFeed.bindAsEventListener(this));
		
		this.rssFeedDialog = new HP.Dialog('addRssFeed', 
											{openTrigger: 'openRSSFeedDialog', 
											closeTrigger: 'closeRSSFeedDialog',
											onShow: this.setFocus.bind(this), 
											masking: true});
		
		this.whatsthis = new HP.Dialog('whatsThisWindow', 
										{openTrigger: 'openRSSHelpDialog', 
										closeTrigger: 'closeRSSHelpDialog', 
										masking:false});
	},
	setFocus: function(){
		this.form.focusFirstElement();
	},
	submitFeed: function(ev){
		if(ev && ev.type == 'keypress'){
			var keyCode = ev.keyCode || ev.which;
			if(keyCode != Event.KEY_RETURN){
				return;
			}
		} 
		this.wait();
		HP.doAjaxGet('addRSSFeed',{url: $F(this.input)}, this.confirmRSSAdd.bind(this));
	},
	confirmRSSAdd: function(response){
		if(response.responseText == ''){
			this.displayError();
			return;
		}
		var json = response.responseText.evalJSON();		
		if(json.moduleid){
			this.displaySuccess();
			if(HP.Main){
				HP.Main.Container.Grid.addModule(true, response);
			}
		}else{
			this.displayError();
		}
	},
	wait: function(){
		this.mainMessage.update(this.waitingMsg);
		Element.show(this.mainMessage);
		Element.hide(this.error);
		Element.hide(this.tips);
		Element.hide(this.success);
	},
	displayError: function(){
		Element.hide(this.mainMessage);
		Element.show(this.error);
		Element.show(this.tips);
		Element.hide(this.success);
	},
	displaySuccess: function(){
		this.mainMessage.update(this.successMsg);
		this.success.update($F(this.input));
		Element.show(this.mainMessage);
		Element.hide(this.error);
		Element.hide(this.tips);
		Element.show(this.success);
	}
});