/*
* @Author: Paul Visco
* @Version: 1.0 4/17/2008
*/

var app = {
	body : s$('html'),
	entry : s$('#entry'),
	messages: s$('#messages'),
	inputs : {
		name : s$('#name'),
		message : s$('#message'),
		code : s$('#code')
	},
	
	/**
	@Name: app.warn
	@Description: All user warning feedback goes through this function.  
	@todo: Right now it alerts but can be fleshed out to a more extensive alert system in the future.
	*/
	warn : function(message){
		alert(message);
	},
	
	/**
	@Name: app.handleEvents
	@Description: Handles all events for the app module as passed on from the delegateEvents method
	*/
	handleEvents : {
		
		click : function(e){
			var target = sb.events.target(e);
			//alert("You clicked a "+target.nodeName+" node");
			
			switch(target.nodeName){
				
				case 'BUTTON':
					switch(target.id){
						case 'add_entry':
							app.entry.toggle();
							break;
							
						case 'save':
							app.save();
							break;
							
						case 'more':
							app.load();
							break;
					}
					
					break;
					
				case 'IMG':
					if(target.id == 'codeImage'){
						sb.include('math.rand');
						target.src = '/captcha?'+sb.math.rand(0,1000);
					}
			}
		},
		dblclick : function(e){
			
		},
		keyup : function(e){
			
		}
	},
	
	/**
	@Name: app.delegateEvents
	@Description: Delgates all the events for the system to the various other modules which may be loaded.  This prevents having to add many duplicate handlers
	*/
	delegateEvents : function(e){
		
		if(app.handleEvents[e.type]){
			app.handleEvents[e.type](e);
		}
		
	},
	
	/**
	@Name: app.addEvents
	@Description: used to delgate events for all modules based on user/mouse input
	*/
	addEvents : function(){
		
		this.body.events({
			click : app.delegateEvents,
			keyup : app.delegateEvents,
			dblclick : app.delegateEvents,
			mouseover : app.delegateEvents
		});
	
	},
	
	save : function(){
		var aj = new sb.ajax({
			url : '/ajax/save',
			method : 'post',
			data : {
				name : app.inputs.name.value,
				message : app.inputs.message.value,
				code : app.inputs.code.value
			},
			handler: function(r){
				if(r == 1){
					window.location = '/';
				} else {
					alert('error savings, are you sure you typed in the correct code form the picture');
				}
			}
		}).fetch();
	},
	
	start : 0,
	
	load : function(){
		app.start +=10;
		var aj = new sb.ajax({
			url : '/ajax/load/'+app.start,
			method : 'post',
			data : {},
			handler: function(r){
				if(r == ''){
					alert('end of messages');
				} else {
					app.messages.innerHTML +=r;
				}
			}
		}).fetch();
	},
	hideEntry : function(){
		app.entry.toggle();
	},
	/**
	@Name: app.init
	@Description: Initializes the application and initializes additional modules if they are included.
	*/
	init : function(){
		this.hideEntry();
		this.addEvents();
		
	}
};

app.init();