
var Tips = function() {
	
	this.ERR_MESS = "Please enter a link and a comment!";
	this.SUCCESS_MESS = "Your tip has been submitted. Thanks!";
	this.ERR_500 = "Our apologies: there was a technical glitch and we couldn&rsquo;t submit your tip. Please try again later.";
		
	this.init = function() {
		if( $('tips_form') ) {
			$('tips_form').observe('submit', 		
				function(event) {
					event.stop();
					BF_Tips.submit();
				}
			);
			$('tips_link').observe('keydown', function() { $('suggest_details').show(); }); 
		}		
	}

	this.submit = function() {
		$('tips_message').className = '';
		$('tips_message').innerHTML = '';			
		$('tips_message').hide();
		$('tips_submit').disabled = true;
		if(this.validate()) {
			var params = {};
			params.link = $F('tips_link').strip();
			params.email = $F('tips_bfem').strip();
			params.name = $F('tips_name').strip();
			params.note = $F('tips_note').strip();
			var tips_res = function(resp) {
				BF_Tips.tipResponse(resp);
			} 
			var tips_fail = function(resp) {
				BF_Tips.tipFail(resp);
			} 
			new Ajax.Request('/buzzfeed/suggest_tip', {method: 'post', parameters: params, onSuccess: tips_res, onFailure: tips_fail});
		} 
	}

	this.tipResponse = function(resp) {
		$('tips_submit').disabled = false;		
		var obj = eval('(' + resp.responseText + ')');
		if(obj && obj.submitted && obj.submitted == true) {
			$('tips_message').className = 'message success';
			$('tips_message').innerHTML = this.SUCCESS_MESS;			
			$('tips_message').show();
			$('tips_link').value = '';
			$('tips_bfem').value = '';
			$('tips_name').value = '';
			$('tips_note').value = '';				
		}
	}

	this.tipFail = function(resp) {
		$('tips_submit').disabled = false;		
		$('tips_message').className = 'message error';
		$('tips_message').innerHTML = this.ERR_500;			
		$('tips_message').show();
		//console.dir({res: resp});
	}

	
	this.validate = function() {
		var status = true;
		if($F('tips_link').strip() == '' || $F('tips_note').strip() == '') {
			$('tips_message').className = 'message error';
			$('tips_message').innerHTML = this.ERR_MESS;			
			$('tips_message').show();
			var status = false;
			$('tips_submit').disabled = false;	
		}
		return status;
	}
}

var BF_Tips = new Tips();
BuzzLoader.register(
	function() {
		BF_Tips.init();		
	}, 1
);
