/*!
 * reCaptcha
 * 
 * A Node.JS module that handles calling reCAPTCHA.
 * 
 * Copyright(c) 2011 Felix Gertz <nihil.baxter.dev@gmail.com>
 * 
 * MIT Licensed
 */

/*
 * reCaptcha server settings
 */
var settings = {
	api_server: 'http://www.google.com/recaptcha/api',
	api_secure_server: 'https://www.google.com/recaptcha/api',
	verify_server: 'www.google.com',
	verify_path: '/recaptcha/api/verify'
}

/*
 * Module exports
 */
var exports = module.exports;
exports.version = '0.0.4';
exports.reCaptcha = reCaptcha;

/*
 * Module dependencies
 */
var http = require('http');
var EventEmitter = require('events').EventEmitter;

/**
 * Creates a new reCaptcha-object with the new keyword. 
 */
function reCaptcha()
{
	EventEmitter.call(this);
	// Default recaptcha response data
	this._recaptcha_response = { 'is_valid': false, 'error': 'incorrect-captcha-sol' };
	return this;
}
reCaptcha.prototype = new EventEmitter();

/**
 * Makes a HTTP POST request to the reCaptcha server to verify if the user's guess was correct.
 * 
 * When finished reCaptcha() emits an 'data'-event
 * with the treated reCaptcha server response.
 * 
 * reCaptcha server response examples:
 * \code
 * { 'is_valid': true, 'error': 'success' }
 * { 'is_valid': false, 'error': 'incorrect-captcha-sol' }
 * \endcode
 * 
 * The error value could be passed to the getHtml-Function.
 * 
 * @param string privatekey Your private key
 * @param string remoteip The IP address of the captcha user
 * @param string challenge Challenges generated by the captcha field
 * @param string response Response entered by the user
 */
reCaptcha.prototype.checkAnswer = function (privatekey, remoteip, challenge, response) {
	if(!privatekey)
		throw new Error('To use reCAPTCHA you must get an API key from https://www.google.com/recaptcha/admin/create .');
	if(!remoteip)
		throw new Error('For security reasons, you must pass the remote ip to reCAPTCHA.');

	// Default recaptcha response data gets emitted if challenge or user answer is faulty.
	if(!challenge || !response)
	{
		this.emit('data', this._recaptcha_response);
		return;
	}

	this._httpPostRequest(encodeURI('privatekey=' + privatekey + 
										'&remoteip=' + remoteip + 
										'&challenge=' + challenge + 
										'&response=' + response
										));		
}

/**
 * Gets the challenge HTML (javascript and non-javascript version).
 * The resulting reCAPTCHA HTML widget is embedded within the HTML form it was called from.
 * 
 * @param string pubkey A public key for reCAPTCHA
 * @param string error The error given by reCaptcha response (optional)
 * @param boolean use_ssl Should the request be made over ssl? (optional)
 * @return string - The HTML to be embedded in the user's form.
 */
reCaptcha.prototype.getCaptchaHtml = function(pubkey, error, use_ssl) {
	if(!pubkey)
		throw new Error("To use reCAPTCHA you must get an API key from <a href='https://www.google.com/recaptcha/admin/create'>https://www.google.com/recaptcha/admin/create</a>");

	var server = settings.api_server;
	if(use_ssl) server = settings.api_secure_server;

    if(error) pubkey += '&amp;error=' + error;

	return '<script type="text/javascript" src="' + server + '/challenge?k=' + pubkey + '"></script>\n\n' +
	'<noscript>\n' +
  	'\t<iframe src="' + server + '/noscript?k=' + pubkey + '" height="300" width="500" frameborder="0"></iframe><br/>\n' +
  	'\t<textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>\n' +
  	'\t<input type="hidden" name="recaptcha_response_field" value="manual_challenge"/>\n' +
	'</noscript>\n';	
}

reCaptcha.prototype._httpPostRequest = function (postdata) {
	var that = this;
	
	var options = {
	  host: settings.verify_server,
	  port: 80,
	  path: settings.verify_path,
	  method: 'POST',
	  headers: { 'Content-Type': 'application/x-www-form-urlencoded',
    			 'Content-Length': Buffer.byteLength(postdata),
    			 'User-Agent': 'reCAPTCHA/Node.JS ' + exports.version
  		}
  	};

	var req = http.request(options, function(res) {
	  res.setEncoding('utf8');
	  res.on('data', function(chunk) {
	  	var lines = chunk.split("\n");
	  	if(lines.length >= 2) {
	  		if(lines[0] == 'true')
	  			that._recaptcha_response.is_valid = true;
	  		that._recaptcha_response.error = lines[1];
	  	}
	  	that.emit('data', that._recaptcha_response);
	  });
	});
	
	// Default recaptcha response data gets emitted if there is an connection error.
	req.on('error', function(e) {
	  console.log('Problem with reCAPTCHA request: ' + e.message);
	  that.emit('data', that._recaptcha_response);
	});
	
	req.write(postdata);
	req.end();
}

@@ -895,14 +895,20 @@
 type
- = new
+.__proto__ =
  Eve
@@ -916,18 +916,26 @@
 tEmitter
-()
+.prototype
 ;%0A%0A/**%0A 

Tweak prototype declaration so objects don't share an instance.