/**
 *  jQuery-plugin which converts a html-based survey to a more user friendly / web2.0 interface
 *  The survey consists of a unordered list (ul) of radiobutton-groups.
 *  See for example ./quickscan/kkl.xml
 *
 */


function getScore(scoreType)
{
  var total = 0;
  $("li." + scoreType + " input[type=radio]:checked").each(function()
  {
    total += parseFloat($(this).val());
  });
  
  // add value passed through url if present
  var urlparam = $(document).getUrlParam(scoreType);
  if (urlparam)
  {
  	 total+=parseFloat(urlparam);
  }

  return total;
}

$.fn.survey = function()
{
	$(this).find('fieldset li:first').show();

	$(this).find("fieldset .fieldItemValue label").click( function()
	{
		// manually set radiobutton, since this handler will submit the form before the default click-handler is fired
		var idRadioButton = $(this).attr('for');
		$("#" + idRadioButton).get(0).checked = true;

		// set label (button) in selected state:
		$(this).addClass('selected');

		var liCurrent = $(this).closest('li');
		var liArray = liCurrent.parent().children();
		var form = $(this).closest('form');

		// hide current li
		liCurrent.toggle();

		// show next li
		liCurrent.next().toggle();

		// update progressbar
		var currentItem = liArray.index(liCurrent)+1;
		var totalItems	= liArray.length;
		var progress = currentItem / totalItems;
		$(".progressbar." + form.attr('id')).progressbar( progress ); //, 'voortgang ' + form.attr('title') + ': ' + currentItem + '/' + totalItems );

		if (progress >= 1.0)
		{
			// calculate and set score-vars
			form.find("input.score").each( function()
			{
				$(this).val( getScore( $(this).attr('name') ) );
			} );

			// remove all radiobuttons to prevent submission of radio-values (only scores are needed)
			form.find("fieldset .fieldItemValue input[type='radio']").remove();

      // set action of form
      form.attr("action",(typeof(_url_prefix) != "undefined" ? _url_prefix : "") + form.attr("action")); 
      
			form.get()[0].submit();
		}


		return true;
	});
};