(function() {
	var glow;
	
	gloader.load(
		["glow", "1", "glow.dom", "glow.events"],
		{
			async: false,
			onLoad: function(fetchedGlow) {
				glow = fetchedGlow;
				glow.ready(init);
			}
		}
	);
	
	var quizclosure,
		submit_btn,
		selectors,
		result_div,
		score = 0; // default is 0

function init() {
	// variable initialization
	quizclosure = glow.dom.get("div#genderquiz");
	submit_btn = quizclosure.get("input#gq_submit");
	selectors = quizclosure.get("div.gq-question_group input");
	result_div = quizclosure.get("div#gq-result");
	
	glow.events.addListener(
		submit_btn,
		"click",
		function() {
			collect_data();
			return false;
		},
		quizclosure);
}

function collect_data() {
	// reset score
	score = 0;
	var checkdata = {},
		accumul = {};
	selectors.each(function(i) {
		if (typeof(checkdata[this.id.split("_")[1]]) == 'undefined') {
			checkdata[this.id.split("_")[1]] = {};
		}
		checkdata[this.id.split("_")[1]][this.id.split("_")[2]] = this.checked;
	});
	selectors.each(function(i) {
		if (this.checked) {
			accumul[this.name] = (glow.lang.trim(this.value) == "f") ? 1 : -1;
		}
	});
	process_data(checkdata, accumul);
}

function process_data(checkdata, accumul) {
	for (var question in checkdata) {
		if (checkdata[question]["yes"] === false && checkdata[question]["no"] === false) {
			output_result("ERR");
			return;
		}
	}
	// if we get here, user has filled all data so can score
	for (var question in accumul) {
		score = score + accumul[question];
	}
	output_result(score);
}

function output_result(msg) {
	var the_one_we_want;
	if (msg === "ERR") {
		result_div.get("p.gq-errmsg").show();
		result_div.get("p.gq-endmsg").each(function(i) {
			glow.dom.get(this).hide();
		});
		result_div.get("p.gq-addmsg").hide();
	} else {
		if (msg == 0) { // neutral
			the_one_we_want = "p#gq-neutral";
		} else if (msg < 0) { // male
			the_one_we_want = "p#gq-male";
		} else { // female
			the_one_we_want = "p#gq-female";
		}
		result_div.get("p.gq-errmsg").hide();
		result_div.get("p.gq-endmsg").each(function(i) {
			if (glow.dom.get(this).is(the_one_we_want)) {
				glow.dom.get(this).show();
			} else {
				glow.dom.get(this).hide();
			}
		});
		result_div.get("p.gq-addmsg").show();
	}
	finalize();
}

function finalize() {
	result_div.show();
}

})();