/**
 * @author pete
 */

document.observe('dom:loaded', function(){
	$$('.status_update').each(function(f){
		var s = f.down('select');
		if( s ){
			var cps = $H();
			s.select('option').each(function(o){
				try {
					var elm = f.down('.crosspost'+o.value);
					if( elm ){
						cps.set(o.value, elm)
					}
				}catch(ex){}
			});
			function toggleCrossPostContainers(){
				cps.values().invoke('hide');
				try {
					cps.get(s.options[s.selectedIndex].value).show();
				}catch(ex){}
			}
			s.observe('change', toggleCrossPostContainers);
			toggleCrossPostContainers();
		}
	}).invoke('observe', 'submit', function(e){
		e.stop();
		var form = e.findElement('form');
		if( form ){
			new Ajax.Request('/status/add', {
				method: 'post',
				parameters: form.serialize(),
				onComplete: function(r){
					if( r.responseJSON && r.responseJSON.status ){
						/*
						 * replace the status list with the updated list
						 */
						$('status_list').replace(r.responseJSON.response);
						form.enable();
						form.select('.loading').invoke('hide');
						if( form.hasClassName('update_others')){
							/*
							 * try updating the affected input in the individual business drawer
							 */
							try {
								$('status' + form.down('[name=business]').getValue()).setValue(form.down('[name=text]').getValue());
							}catch(ex){}
						}
						if (form.hasClassName('reset_after_update')) {
							form.reset();
						}
					}else{
						form.enable();
						form.select('.loading').invoke('hide');
						alert('Woops! something went wrong. Please try again later.');
					}
				}
			});
			form.disable();
			form.select('.loading').invoke('show');
		}
	});
});

