var Polls = {
	/**
	 * gets nette ajax response for "view" poll action
	 * e.g. gets HTML with poll result of vote options
	 * @param {Object} anchor anchor DOM object
	 */
	updateForAction : function(anchor) {
		//ajax request, result is json for nette component
		$.getJSON(this.removeFragment(anchor.href), null, $.nette.success);
		return false;
	},

	/**
	 * Removes the fragment part from url when is presented
	 * @param {string} url original url
	 * @return {string}
	 */
	removeFragment: function(url) {
		var hashPos = url.indexOf('#');
		return hashPos == -1
			? url
			: url.substring(0, hashPos);
	}
};

$(function() {
	/**
	 * Handle submitting for poll form.
	 * We need to use .live method, because ".poll-form" elements can be added
	 * dynamically.
	 */
	$('.poll-form').live("submit",function() {

		var postData = "";

		// iterate the elements within the form in 'this' is our form
		for (var i=0;i<this.elements.length;i++) {
			var e = this.elements[i];
			if (e.disabled) {
				continue;
			}
			if (this.multi.value == 1) {
				if ( (/^answer-[0-9]+$/).test(e.name) && (e.type=='checkbox') && (e.checked == true)) {
					if (postData != "") {
						postData += '&';
					}
					postData += e.name + '=' + escape(e.value);
					continue;
				}
			} else if (this.multi.value == 0) {
				if ( (e.name == "answer") && (e.type=='radio') && (e.checked == true)) {
					postData += e.name + '=' + escape(e.value);
					break;
				}
			}
		}

		if (postData == "") {
			alert("Nen\u00ED vybr\u00E1na \u017E\u00E1dn\u00E1 mo\u017Enost.");
			return false;
		}

		//add pollId
		if (this.pollId.value) {
			postData += '&pollId=' + escape(this.pollId.value);
		} else {
			return false;
		}

		//add info about multi poll (1/0 values)
		postData += '&multi=' + escape(this.multi.value);

		$.ajax({
			type: "POST",
			url: Polls.removeFragment(this.action),
			data: postData,
			dataType: "json",
			success: function(data) {
				$.nette.success(data);
				return false;
			}
		});

		return false;
	});
})

