var $j = jQuery.noConflict();

$j(document).ready(function() {
	var tooltipConfig = {
		position: 'bottom right',
		offset: [-20, 10],
		delay: 0,
		layout: '<div><h3>INFO</h3></div>'
	};
	$j('img.info[title]').tooltip(tooltipConfig);
	$j('img.info.withTip').tooltip(tooltipConfig);
	$j('#accordion').accordion();
	$j('#accordion :radio[name=week1], #accordion :radio[name=week2], #accordion :radio[name=week3], #accordion :radio[name=week4], #accordion :radio[name=week5], #accordion :radio[name=week6]').click(gotoNextAccordion);
	if ($('weekselector'))
	{
		$('next_button').style.display = 'none';
		$('next_grey').style.display = 'inline';
		if (!$('accordion'))
		{
			$j('#weekselector :radio[name=week1]').click(checkOneWeek);
		}
	}
});

function gotoNextAccordion() {
	var parent = $j(this).parent();
	var nr = $j(':radio', parent).length - $j('#' + $j(this).attr('id') + ' ~ :radio', parent).length - 1;
	var name = $j('.menuplan div a:eq(' + nr + ')', parent.parent()).text();
	var index = $j('#accordion').accordion('option', 'active');
	var header = $j('#accordion h3:eq(' + index + ')');
	$j('span.selection', header).text(name);
	header.addClass('chosen');
	var headercount = $j('#accordion h3').length;
	if ((index + 1) < headercount) {
		$j('#accordion').accordion('activate', index + 1);
	}
	
	if (validateOrderForm(headercount))
	{
		$('next_button').style.display = 'inline';
		$('next_grey').style.display = 'none';
	}
}

function checkOneWeek()
{
	if (validateOrderForm(1))
	{
		$('next_button').style.display = 'inline';
		$('next_grey').style.display = 'none';
	}
}

//return the value of the radio button that is checked
//return an empty string if none are checked, or
//there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

//set the radio button with the given value as being checked
//do nothing if there are no radio buttons
//if the given value does not exist, all the radio buttons
//are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


function validateOrderForm(weeks)
{
	var sel = '';
	for (var i=1; i<=weeks; i++)
	{
		sel = getCheckedValue(document.forms['orderForm'].elements['week'+i]);
		if (sel == '')
		{
			return false;
		}
	}

	return true;
}