/* -------------------------------------------------------------------
One Click Enquete
Require jquery.js
See also /enquete/oneclick/oneclick.cgi
Written by Makoto Ogawa <ogawa@nun.co.jp> in NATURAL Inc.
------------------------------------------------------------------- */

function OneClickEnq( datafile, target, form  ) {
	this.target = target;
	this.form = form || '#onclickenqform';
	this.datafile = datafile;

	this.formid = this.form.replace( /^#/, "" );
}

OneClickEnq.prototype = {

	run : function() {
		var _this = this;
		$(_this.target).load(
			'/enquete/oneclick/oneclick.cgi?datafile='
				+ encodeURIComponent( _this.datafile )
				+ '&formid=' + encodeURIComponent( _this.formid ),
			function() {
			//	$(_this.target).slideDown();
				_this.attach();
			}
		);
		return this;
	},

	attach: function() {
		var _this = this;
		$(_this.form).submit( function() {
			var res = _this.getFormData( this );
			if ( ! res ) { return false; }
			$(_this.target).find("input").each( function() {
				if ( this.type == 'submit' ) {
					$(this).attr("disabled", "disabled");
				}
			} );
		//	$(_this.target).find("input[type='submit']").attr("disabled", "disabled");
		//	$(_this.target).slideUp( function() {
				$(_this.target).load(
					'/enquete/oneclick/oneclick.cgi?datafile='
						+ encodeURIComponent( _this.datafile )
						+ '&formid=' + encodeURIComponent( _this.formid ),
					res,
					function() {
					//	$(_this.target).slideDown();
						_this.attach();
					}
				);
			// } );
			return false;
		} );
		return this;
	},

	getFormData: function( form ) {
		var res = {};
		for(var i=0; i<form.elements.length; i++) {
			var elm = form.elements[i];
			if ( elm.name ) {
				if ( elm.type == 'checkbox' || elm.type == 'radio' ) {
					if ( elm.checked ) {
						res[elm.name] = elm.value;
					}
				} else {
					res[elm.name] = elm.value;
				}
			}
		}
		return res;
	}
}
