/*****************/
/*CONSTANTS BEGIN*/
/*****************/
window.SHANA=0;
window.TUSHAV=1;
window.MATZAV=2;
window.TAARLEIDA=3;
window.GILISHA=4;
window.TAARYELED=5;
window.MYYELED=6;
window.MEZONOTYELED=7;
window.MEZONOTISHA=8;
window.BENZUG=9;
window.HACHNASA=10;
window.RASHUM=11;
window.YESHUV=12;
window.TAARALIA=13;
window.TAARSHERUT=14;
window.TAARGIUS=15;
window.END=Infinity;
/***************/
/*CONSTANTS END*/
/***************/

//Collects form data from the page and sends it to the server via C.A CallBack
function updateTable(e)
{
	var evt,currentIdx,count,params,i,segmentsLength,currentSegment,
		inputsLength,j,inputs,currentInput,
		tagName,name,k,options,optionsLength,tmp,
		tushavElement,tushavValue,shanaElement,shanaValue,trueIsFalse;//Used to handle the 2003 through 2006 tushav value switching
	evt=new CommonEvent(e);
	params=[];
	currentIdx=evt.sender.parentNode.idx;
	segmentsLength=window.segments.length;
	count=Math.min(currentIdx+1,segmentsLength);
	trueIsFalse=false;
	if(false===hasClass('Hidden',window.segments[window.TUSHAV].div))
	{
		tushavElement=document.getElementById(IDPREFIX+'Tushav');
		tushavValue=tushavElement.options[tushavElement.selectedIndex].value;
		if('false'===tushavValue)
		{
			shanaElement=document.getElementById(IDPREFIX+'Shana');
			shanaValue=Number(shanaElement.options[shanaElement.selectedIndex].value);
			if((2003<=shanaValue)&&(2006>=shanaValue))
			{
				tushavElement.options[tushavElement.selectedIndex].value='true';
				trueIsFalse=true;
			}
		}
	}
	for(i=0;i<count;i++)
	{
		currentSegment=window.segments[i];
		if(!hasClass('Hidden',currentSegment.div))
		{
			inputs=getAllInputs(currentSegment.div);
			inputsLength=inputs.length;
			for(j=0;j<inputsLength;j++)
			{
				currentInput=inputs[j];
				if(-1===currentSegment.untouchables.indexOf(inputs[j]))
				{
					name=currentInput.name.replace(NAMEPREFIX,'');
					tagName=currentInput.tagName.toLowerCase();
					switch(tagName)//No default value.
					{
						case 'button':break;
						case 'select'://Fallthrough
						case 'textarea'://Fallthrough
						case 'input':
							inputType=currentInput.type;
							switch(inputType)//No default value.
							{
								case 'button'://Fallthrough
								case 'image'://Fallthrough
								case 'reset'://Fallthrough
								case 'submit'://Fallthrough
								case 'file':break;
								case 'checkbox':
									params.push([name,currentInput.checked]);
									break;
								case 'radio':
									if(currentInput===getCheckedRadio(document.forms[0][input.name]))
									{
										params.push([name,true]);
									}
									break;
								case 'select-multiple':
									options=currentInput.options;
									optionsLength=options.length;
									tmp=[];
									for(k=0;k<optionsLength;k++)
									{
										tmp.push([options[k].value,options[k].selected]);
									}
									params.push([name,tmp]);
									break;
								case 'select-one'://Fallthrough
								case 'textarea'://Fallthrough
								case 'hidden'://Fallthrough
								case 'text'://Fallthrough
								case 'password'://Fallthrough
									params.push([name,currentInput.value]);
								break;
							}
							break;
					}
				}
			}
		}
	}
	if(true===trueIsFalse)
	{
		//This is weird...between 2003 and 2006 when tushav is false it actually means it is treated as true.
		tushavElement.options[tushavElement.selectedIndex].value='false';
	}
	window[IDPREFIX+'MusbarCallBack'].Callback(params);
}

//Gecko workaround
//Gecko renders disabled select elements with left alignment
//This function sets the focus away from the sending element if it appears to be disabled.
//Note: Some minor display issues arise...
function preventGeckoFromFocusingOnSelectElements(e)
{
	var evt=new CommonEvent(e);
	if(hasClass('Disabled',evt.sender)){evt.sender.blur();}
}

//The questionnaire is divided into segments.
//Each segment object is composed of a div element and a few other html controls.
//Some of those controls are common to all segments and may be accessed via the Segment prototype;
function Segment(node)
{
	var inputs,inputsLength,i,input;
	this.untouchables=[];
	this.onEnable=[];
	this.onDisable=[];
	inputs=node.getElementsByTagName('input');
	inputsLength=inputs.length;
	this.div=node;
	this.nextSegmentIndex=this.div.idx+1;//Default, continue to the adjacent segment
	for(i=0;i<inputsLength;i++)
	{
		input=inputs[i];
		if(hasClass('Continue',input))
		{
			this.nextButton=input;
			this.untouchables.push(input);
			attachEventListener('click',input,updateTable);
		}
		else if(hasClass('Update',input))
		{
			this.updateButton=input;
			this.untouchables.push(input);
			attachEventListener('click',input,updateTable);
		}
	}
}

//The div element and two inputs (next/update buttons) common to all segments
Segment.prototype.div=null;
Segment.prototype.nextButton=null;
Segment.prototype.updateButton=null;
//Each segments defines a set of input/select/textarea/button which should not be touched when it is toggled
Segment.prototype.untouchables=null;
//These are primitive event-handlers call lists.
//The members are actually arrays of function which are called whenever the segment is toggled.
Segment.prototype.onEnable=null;
Segment.prototype.onDisable=null;
//The next segment array index (within window.segments)
Segment.prototype.nextSegmentIndex=null;//Note, this is not always this.div.idx+1 since some segments get skipped on occasion
//A segment gets toggled into an enabled/disabled state.
//An enabled segment's form-fields are accessible.
//A disabled segment's form-fields are not.
Segment.prototype.toggle=function(enable)
{
	var inputs,inputsLength,input,
		functions,functionsLength,
		i,tagName,inputType;
	if('boolean'!==typeof enable){return;}
	if(enable)
	{
		addClass('Hidden',this.updateButton,false);
		removeClass('Hidden',this.nextButton,true);
		removeClass('Hidden',this.div,true);
		addClass('Hidden',document.getElementById('Done'),false);
		functions=this.onEnable;
	}
	else
	{
		addClass('Hidden',this.nextButton,false);
		removeClass('Hidden',this.updateButton,true);
		functions=this.onDisable;
	}
	functionsLength=functions.length;
	for(i=0;i<functionsLength;i++)
	{
		functions[i].call(this);
	}
	inputs=getAllInputs(this.div);
	inputsLength=inputs.length;
	for(i=0;i<inputsLength;i++)
	{
		input=inputs[i];
		if(-1===this.untouchables.indexOf(input))
		{
			tagName=input.tagName.toLowerCase();
			if(true===enable){removeClass('Disabled',input,true);}
			else{addClass('Disabled',input,false);}
			switch(tagName)//No default value.
			{
				case 'button':
					input.disabled=!enable;
					break;
				case 'textarea'://Fallthrough
				case 'input':
					inputType=input.type;
					switch(inputType)//No default value.
					{
						case 'image':
							break;//Not much can be done here...
						case 'button'://Fallthrough
						case 'checkbox'://Fallthrough
						case 'file'://Fallthrough
						case 'hidden'://Fallthrough
						case 'radio'://Fallthrough
						case 'reset'://Fallthrough
						case 'submit':
							input.disabled=!enable;
							break;
						case 'textarea'://Fallthrough
						case 'text'://Fallthrough
						case 'password':
							input.readOnly=!enable;
							break;
					}
					break;
				case 'select':
					if(true===window.IE)
					{//Trident alone ventures here...
						input.disabled=!enable;
					}
					break;
			}
		}
	}
};

//Get all input, select, textarea and button tags that are a direct or indirect children of the provided node.
function getAllInputs(node)
{
	var formTags,i,formTagsLength,allInputs,inputs,inputsLength,j;
	formTags=['input','select','textarea','button'];
	formTagsLength=formTags.length;
	allInputs=[];
	for(i=0;i<formTagsLength;i++)
	{
		inputs=node.getElementsByTagName(formTags[i]);
		inputsLength=inputs.length;
		for(j=0;j<inputsLength;j++)
		{
			allInputs.push(inputs[j]);
		}
	}
	return allInputs;
}

//Switches from the initial view to the questionnaire
function toggleNextView(e)
{
	var initialView,calculationView;
	initialView=document.getElementById('InitialView');
	calculationView=document.getElementById('CalculationView');
	addClass('Hidden',initialView,false);
	removeClass('Hidden',calculationView,true);
}

//A disabled segment is enabled once the user desires to update that segment's data. this disables and hides the segments that follow.
function updateSegment(e)
{
	var evt,i;
	evt=new CommonEvent(e);
	for(i=window.segments.length-1;i>evt.sender.parentNode.idx;i--)
	{
		window.segments[i].toggle(false);
		addClass('Hidden',window.segments[i].div,false);
	}
	window.segments[i].toggle(true);
	addClass('Hidden',window.segments[i].updateButton,false);
	removeClass('Hidden',window.segments[i].nextButton,true);
}

//A segment becomes disabled and 'passes the torch' to the next one here.
function toggleNextSegment(e)
{
	var evt,idx,segment,nextIdx;
	evt=new CommonEvent(e);
	idx=evt.sender.parentNode.idx;
	segment=window.segments[idx];
	segment.toggle(false);
	nextIdx=segment.nextSegmentIndex;
	if(Infinity===nextIdx)
	{
		removeClass('Hidden',document.getElementById('Done'),true);
	}
	else
	{
		window.segments[nextIdx].toggle(true);
	}
}

//Whenever the gender is changed all gender-specific text is toggled and the pre-set Rashum value is changed
function updateGender(e)
{
	var evt,male,rashum;
	evt=new CommonEvent(e);
	male=(evt.sender.selectedIndex<4);
	window.femaleRule.style.display=male?window.FEMALE:window.MALE;
	window.maleRule.style.display=male?window.MALE:window.FEMALE;
	rashum=document.getElementById(IDPREFIX+'Rashum');
	rashum.selectedIndex=male?0:1;
}

//xButtons click handler, removes a date entry from the list
function removeYeled(e)
{
	var evt;
	evt=new CommonEvent(e);
	evt.sender.parentNode.parentNode.removeChild(evt.sender.parentNode);
}

//Date field change handler - ensures that only valid dates are stored in field.value
function checkDate(e)
{
	var evt;
	evt=new CommonEvent(e);
	evt.sender.value=normalizeDate(evt.sender.value,normalizeDate.defaultRX);
}

//Adds another list item with a textbox and a button.
function addYeled(e)
{
	var taarYeleds,taarYeled,xButton,li,template,count,name;
	taarYeleds=document.getElementById('TaarYeleds');
	template=document.getElementById('TaarYeledTemplate');
	xButton=document.getElementById('XButtonTemplate').firstChild.cloneNode(false);
	taarYeled=template.firstChild.cloneNode(false);
	name=taarYeled.name.replace(NAMEPREFIX,'');
	if(null===e)//Called from initTaarYeleds, the first input cannot be removed so no 'X' button.
	{
		xButton.style.visibility='hidden';//Ugly...
		//Remove the first option, it was placed there in order to conform with xhtml and is no longer needed
		taarYeleds.removeChild(taarYeleds.firstChild);
		count=0;
	}
	else
	{
		count=1+Number(taarYeleds.lastChild.lastChild.previousSibling.name.replace(name,''));
	}
	
	taarYeled.name=name+count;
	taarYeled.id='';
	taarYeled.removeAttribute('id');
	attachEventListener('change',taarYeled,checkDate);
	attachEventListener('click',xButton,removeYeled);
	li=document.createElement('li');
	li.appendChild(xButton);
	li.appendChild(taarYeled);
	li.appendChild(template.firstChild.nextSibling.cloneNode(false));
	taarYeleds.appendChild(li);
}

//Inits TaarYeleds list by placing the first input in it.
function initTaarYeleds()
{
	addYeled(null);
}

//Checks for children under the age of 18
function hasValidChildren()
{
	var i,taarYeleds,taarYeledsLength,
		dateObj,dateStr,shanaElement,shanaValue;
	taarYeleds=getAllInputs(document.getElementById('TaarYeleds'));
	taarYeledsLength=taarYeleds.length;
	shanaElement=document.getElementById(IDPREFIX+'Shana');
	shanaValue=Number(shanaElement.options[shanaElement.selectedIndex].value);
	for(i=0;i<taarYeledsLength;i++)
	{
		if('text'!==taarYeleds[i].type){continue;}
		dateObj={};
		dateStr=normalizeDate(taarYeleds[i].value,normalizeDate.defaultRX,dateObj);
		if(''!==dateStr)
		{
			if(((shanaValue-18)<=dateObj.year)&&(shanaValue>=dateObj.year))
			{
				return true;
			}
		}
	}
	return false;
}

//Requests an updated yeshuv list from the sever whenever the selected year changes.
function fillYeshuv()
{
	var yeshuv,shana;
	yeshuv=document.getElementById('Yeshuv');
	shana=Number(document.getElementById(IDPREFIX+'Shana').value);
	if((isNaN(yeshuv.year))||(yeshuv.year!==shana))
	{
		addClass('CallBackInProgress',document.body,true);//Adds one 'hourglass' cursor
		window[IDPREFIX+'YeshuvCallBack'].Callback(shana);
	}
}

//Asks for TaarGius only if TaarSherut was specified.
function checkTaarSherut()
{
	var taarSherut;
	taarSherut=document.getElementById(IDPREFIX+'TaarSherut');
	if(''===taarSherut.value)
	{
		this.nextSegmentIndex=window.END;
	}
	else
	{
		this.nextSegmentIndex=window.TAARGIUS;
	}
}
//Calls the server to get the value of NekudatZikui for the selected year.
function getErekhNekudatZikui()
{
	var shana,shanaValue;
	shana=document.getElementById(IDPREFIX+'Shana');
	shanaValue=shana.options[shana.selectedIndex].value;
	window[IDPREFIX+'HachnasaShnatiCallBack'].Callback(shanaValue);
}

//This makes sure that non-tushav users skip the rest of the segments.
function checkTushav()
{
	var tushav,shana,shanaValue;
	tushav=document.getElementById(IDPREFIX+'Tushav');
	shana=document.getElementById(IDPREFIX+'Shana');
	shanaValue=Number(shana.options[shana.selectedIndex].value);
	if((1===tushav.selectedIndex)&&(!((2003<=shanaValue)&&(2006>=shanaValue))))
	{
		this.nextSegmentIndex=window.END;
	}
	else
	{
		this.nextSegmentIndex=this.div.idx+1;//Re-apply the default value
	}
}

function checkMatzav()
{
	var tushav;
	tushav=document.getElementById(IDPREFIX+'Tushav');
	if(1===tushav.selectedIndex)
	{
		this.nextSegmentIndex=window.END;
	}
	else
	{
		this.nextSegmentIndex=this.div.idx+1;//Re-apply the default value
	}
}

//A married user is asked for the date-of-birth of his/her spouse, everybody else are simply asked of their own.
function checkTaarLeida()
{
	var matzav;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	if((1===matzav)||(5===matzav))
	{//Married
		this.nextSegmentIndex=this.div.idx+1;
	}
	else
	{//Not married
		this.nextSegmentIndex=window.TAARYELED;
	}
}

//Updates the year displayed on this segment.
function updateTaarYeledShana()
{
	var shana;
	shana=document.getElementById(IDPREFIX+'Shana');
	document.getElementById('TaarYeledShana').firstChild.nodeValue=(Number(shana.options[shana.selectedIndex].value)-18).toFixed(0);
}

//Makes sure that:
//	only users with valid children (under 18 years of age) get MyYeled
//	only childless married men get MezonotIsha
//	only childless married women get BenZug
//	...everybody else get Yeshuv...
function checkTaarYeleds()
{
	var found,matzav;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	found=hasValidChildren();
	if(true===found)
	{
		this.nextSegmentIndex=window.MYYELED;
	}
	else switch(matzav)
	{
		case 1://Nasui
			this.nextSegmentIndex=window.MEZONOTISHA;
			break;
		case 5://Nesua
			this.nextSegmentIndex=window.BENZUG;
			break;
		default://Everybody else
			this.nextSegmentIndex=window.YESHUV;
			break;
	}
}

//Not exactyl toggles the button - just shows/hides it according to the containing segment's state.
function toggleMoreButton()
{
	var more;
	more=document.getElementById('More');
	if(hasClass('Hidden',window.segments[more.parentNode.idx].nextButton))
	{
		addClass('Hidden',more,false);
	}
	else
	{
		removeClass('Hidden',more,true);
	}
}

//Fills MyYeleds with all yeled items from taarYeleds and allows the user to uncheck any of these items.
function fillMyYeleds()
{
	var i,j,taarYeleds,taarYeledsLength,
		myYeleds,template,templateLength,li,
		child,myYeledsCount,validYeleds,
		dateObj,dateStr,shanaElement,shanaValue;
	shanaElement=document.getElementById(IDPREFIX+'Shana');
	shanaValue=Number(shanaElement.options[shanaElement.selectedIndex].value);
	taarYeleds=getAllInputs(document.getElementById('TaarYeleds'));
	taarYeledsLength=taarYeleds.length;
	myYeleds=document.getElementById('MyYeleds');
	template=document.getElementById('MyYeledTemplate').childNodes;
	myYeledsCount=document.getElementById('MyYeledsCount');
	templateLength=template.length;
	while(myYeleds.hasChildNodes())
	{
		myYeleds.removeChild(myYeleds.firstChild);
	}
	validYeleds=0;
	for(i=0;i<taarYeledsLength;i++)
	{
		if('text'!==taarYeleds[i].type){continue;}
		dateObj={};
		dateStr=normalizeDate(taarYeleds[i].value,normalizeDate.defaultRX,dateObj);
		if(''===dateStr){continue;}
		if(((shanaValue-18)>dateObj.year)||(dateObj.year>shanaValue)){continue;}//Yeled is over 18 years of age OR not even born for the given year.
		validYeleds++;
		li=document.createElement('li');
		for(j=0;j<templateLength;j++)
		{
			li.appendChild(child=template[j].cloneNode(true));
			if('label'===child.tagName.toLowerCase())
			{
				child.setAttribute('for',child.htmlFor+='MyYeled'+taarYeleds[i].name.replace('TaarYeled',''));
				child.firstChild.nodeValue=taarYeleds[i].value;
			}
			if('input'===child.tagName.toLowerCase())
			{
				child.id='';
				child.removeAttribute('id');
				child.name='';
				child.removeAttribute('name');
				child.setAttribute('name',child.name=template[j].name.replace(NAMEPREFIX,'')+taarYeleds[i].name.replace('TaarYeled',''));
				child.setAttribute('id',child.id=child.name);
			}
		}
		myYeleds.appendChild(li);
	}
	myYeledsCount.firstChild.nodeValue=validYeleds;
	if(1===validYeleds)
	{
		window.multipleYeledsRule.style.display='none';
		window.singleYeledRule.style.display='inline';
	}
	else
	{
		window.multipleYeledsRule.style.display='inline';
		window.singleYeledRule.style.display='none';
	}
}

//The segment which follows MyYeled is determined according to the existance of valid children and the marital status
function checkMyYeleds()
{
	var matzav,found,myYeleds,myYeledsLength,i;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	myYeleds=document.getElementById('MyYeleds').getElementsByTagName('input');
	myYeledsLength=myYeleds.length;
	found=false;
	for(i=0;i<myYeledsLength;i++)
	{
		if(false===myYeleds[i].checked)
		{
			found=true;
			break;
		}
	}
	switch(matzav)
	{
		case 0://Fallthrough
		case 2://Fallthrough
		case 3:
			if(true===found)
			{
				this.nextSegmentIndex=window.MEZONOTYELED;
			}
			else
			{
				this.nextSegmentIndex=window.YESHUV;
			}
			break;
		case 1:
			if(true===found)
			{
				this.nextSegmentIndex=window.MEZONOTYELED;
			}
			else
			{
				this.nextSegmentIndex=window.MEZONOTISHA;
			}
			break;
		case 5:
			this.nextSegmentIndex=window.BENZUG;
			break;
		case 4://Fallthrough
		case 6://Fallthrough
		case 7:
			this.nextSegmentIndex=window.YESHUV;
			break;
	}
}

//MezonotYeled calls this to set the correct next segment
function checkMezonotYeled()
{
	var matzav;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	if(1===matzav)
	{
		this.nextSegmentIndex=window.MEZONOTISHA;
	}
	else
	{
		this.nextSegmentIndex=window.YESHUV;
	}
}

//Makes sure that married users get the to BenZug segment
function checkMezonotIsha()
{
	var matzav;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	//  Married man|| Married woman
	if((1===matzav)||(4===matzav))
	{
		this.nextSegmentIndex=window.BENZUG;
	}
	else
	{
		this.nextSegmentIndex=window.YESHUV;
	}
}

//Checks BenZug and decides whether or not we shall skip the Hachnasa segment
function checkBenZug()
{
	var benZug;
	benZug=document.getElementById(IDPREFIX+'BenZug').selectedIndex;
	if(0===benZug)
	{
		this.nextSegmentIndex=this.div.idx+1;
	}
	else
	{
		this.nextSegmentIndex=window.YESHUV;
	}
}

//Inits the page
function body_Load()
{
	var go,incomeTaxDiv,
		incomeTaxDivChildNodes,incomeTaxDivChildNodesLength,i,
		node,segment,idx,
		matzav,rules,more,
		taarLeida,taarAlia,taarSherut,taarGius,
		taarYeled,gilIsha,
		exampleCB,yeshuv,shana,selects,selectsLength;

	updateHelpAnchors();

	go=document.getElementById('Go');
	incomeTaxDiv=document.getElementById('IncomeTaxDiv');
	matzav=document.getElementById(IDPREFIX+'Matzav');
	more=document.getElementById('More');
	incomeTaxDivChildNodes=incomeTaxDiv.childNodes;
	incomeTaxDivChildNodesLength=incomeTaxDivChildNodes.length;
	taarLeida=document.getElementById(IDPREFIX+'TaarLeida');
	taarAlia=document.getElementById(IDPREFIX+'TaarAlia');
	taarSherut=document.getElementById(IDPREFIX+'TaarSherut');
	taarGius=document.getElementById(IDPREFIX+'TaarGius');
	gilIsha=document.getElementById(IDPREFIX+'GilIsha');
	taarYeled=document.getElementById('TaarYeled');
	exampleCB=document.getElementById('ExampleCB');
	yeshuv=document.getElementById('Yeshuv');
	shana=document.getElementById(IDPREFIX+'Shana');

	if(true!==window.IE)
	{//Gecko goes in here...
		//This allow preventGeckoFromFocusingOnSelectElements to drive the focus away from a disabled-looking select element
		selects=document.getElementsByTagName('select');
		selectsLength=selects.length;
		for(i=0;i<selectsLength;i++)
		{
			attachEventListener('focus',selects[i],preventGeckoFromFocusingOnSelectElements);
		}
		
	}
	else
	{//MSIE goes in here
		fixTridentSelectWidths();
	}

	//These lines allow us to switch between male/female and single child/multiple children states with greater ease later on.
	rules=document.styleSheets[0].cssRules||document.styleSheets[0].rules;//DOM level 2 / DOM level 1.
	window.femaleRule=null;
	window.maleRule=null;
	window.multipleYeledsRule=null;
	window.singleYeledRule=null;
	for(i=rules.length-1;i!==0;i--)
	{
		if('.Female'===rules[i].selectorText)
		{
			window.femaleRule=rules[i];
		}
		else if('.Male'===rules[i].selectorText)
		{
			window.maleRule=rules[i];
		}else if('.MultipleYeleds'===rules[i].selectorText)
		{
			window.multipleYeledsRule=rules[i];
		}
		else if('.SingleYeled'===rules[i].selectorText)
		{
			window.singleYeledRule=rules[i];
		}
		if((null!==window.femaleRule)&&(null!==window.maleRule)&&(null!==window.multipleYeledsRule)&&(null!==window.singleYeledRule))
		{
			break;
		}
	}
	window.MALE=window.maleRule.style.display;
	window.FEMALE=window.femaleRule.style.display;

	yeshuv.year=NaN;//The date for which the current list was loaded, at this point - the list is empty so the year is NaN

	//Generate Segment instances by trudging through the main div's child nodes.
	window.segments=[];
	idx=0;
	for(i=0;i<incomeTaxDivChildNodesLength;i++)
	{
		node=incomeTaxDivChildNodes[i];
		if((1===node.nodeType)&&('div'===node.tagName.toLowerCase()))
		{
			node.idx=idx++;
			window.segments.push(segment=new Segment(node));
			attachEventListener('click',segment.nextButton,toggleNextSegment);
			attachEventListener('click',segment.updateButton,updateSegment);
		}
	}

	if(true===window.IE)
	{
		for(i=0;i<3;i++)
		{
			addClass('TridentMarginedIncomeTaxWizardButton',window.segments[i].nextButton,false);
			addClass('TridentMarginedIncomeTaxWizardButton',window.segments[i].updateButton,false);
		}
	}

	//These two lines allow us to have a checkbox that never switches states
	attachEventListener('change',exampleCB,function(e){var evt;evt=new CommonEvent(e);evt.cancel();evt.sender.checked=true;return false;});//GECKO
	attachEventListener('click',exampleCB,function(e){var evt;evt=new CommonEvent(e);evt.cancel();return false;});//MSIE

	window.segments[window.TUSHAV].onDisable.push(checkTushav);//Tushav checks itself, non 'Tushav' users get no points here only between 2003 and 2006.
	window.segments[window.MATZAV].onDisable.push(checkMatzav);//Matzav checks Tushav, non 'Tushav' users will come to a halt here...
	window.segments[window.TAARLEIDA].onDisable.push(checkTaarLeida);//TaarLeida checks itself, all married users are asked for the date-of birth of their spouse
	window.segments[window.TAARYELED].onEnable.push(updateTaarYeledShana);//TaarYeleds checks Shana to determine the correct year it displays.
	window.segments[window.TAARYELED].onEnable.push(toggleMoreButton);//TaarYeleds makes sure 'More' button is displayed
	window.segments[window.TAARYELED].onDisable.push(checkTaarYeleds);//TaarYeleds checks itself to determine if MyYeleds should become active
	window.segments[window.TAARYELED].onDisable.push(toggleMoreButton);//TaarYeleds makes sure 'More' button is not displayed
	window.segments[window.MYYELED].untouchables.push(exampleCB);//The example checkbox should never be disabled
	window.segments[window.MYYELED].onEnable.push(fillMyYeleds);//MyYeleds fills itself according to TaarYeleds contents
	window.segments[window.MYYELED].onDisable.push(checkMyYeleds);//MyYeleds checks itself to determine which segment comes next.
	window.segments[window.MEZONOTYELED].onDisable.push(checkMezonotYeled);//Only unmarried man are asked regarding their former spouse.
	window.segments[window.MEZONOTISHA].onDisable.push(checkMezonotIsha);//Only married users are asked regarding their current spouse.
	window.segments[window.BENZUG].onDisable.push(checkBenZug);//BenZug checks to see if Hachnasa should be next
	window.segments[window.HACHNASA].onEnable.push(getErekhNekudatZikui);//Hachnasa updates itself according to MyYeleds and Shana
	window.segments[window.YESHUV].onEnable.push(fillYeshuv);//Yeshuv fills itself according to Shana contents
	window.segments[window.TAARSHERUT].onDisable.push(checkTaarSherut);//TaarSherut checks itself to determine if TaarGius should become active
	window.segments[window.TAARGIUS].nextSegmentIndex=window.END;

	initTaarYeleds();//TaarYeleds ensures at least one yeled is contained within it.
	updateGender({target:matzav});

	attachEventListener('change',taarLeida,checkDate);
	attachEventListener('change',gilIsha,checkDate);
	attachEventListener('change',taarAlia,checkDate);
	attachEventListener('change',taarSherut,checkDate);
	attachEventListener('change',taarGius,checkDate);
	attachEventListener('change',matzav,updateGender);
	attachEventListener('click',more,addYeled);
	attachEventListener('click',go,toggleNextView);
}
//Populates the real yeshuv select/options with values from the server. The called-back results are removed from the document.
function populateYeshuv()
{
	var yeshuv,hiddenYeshuv,tmp,container,
		i,oldSelectedValue,hiddenYeshuvOptions,
		hiddenYeshuvOptionsLength,option;
	removeClass('CallBackInProgress',document.body,false);//Removes one 'hourglass' cursor
	yeshuv=document.getElementById('Yeshuv');
	oldSelectedValue=yeshuv.options[yeshuv.selectedIndex].value;
	tmp=yeshuv.cloneNode(false);
	hiddenYeshuv=document.getElementById(IDPREFIX+'YeshuvHiddenDropDownList');
	hiddenYeshuvOptions=hiddenYeshuv.options;
	hiddenYeshuvOptionsLength=hiddenYeshuvOptions.length;
	for(i=0;i<hiddenYeshuvOptionsLength;i++)
	{
		option=document.createElement('option');
		option.appendChild(document.createTextNode(hiddenYeshuvOptions[i].text));
		option.value=hiddenYeshuvOptions[i].value;
		tmp.appendChild(option);
		if(option.value===oldSelectedValue)
		{
			tmp.selectedIndex=i;
		}
	}
	tmp.year=Number(document.getElementById(IDPREFIX+'Shana').value);
	container=yeshuv.parentNode;
	container.removeChild(yeshuv);
	if(true===window.IE)
	{//MSIE goes in here
		fixTridentSelectWidths();
	}
	else
	{//Gecko goes in here...
		attachEventListener('focus',tmp,preventGeckoFromFocusingOnSelectElements);
	}
	container.appendChild(tmp);
	hiddenYeshuv.parentNode.removeChild(hiddenYeshuv);
}

function updateHachnasaShnati()
{
	var value,nkd38,myYeleds,myYeledsRadios,myYeledsRadiosLength,i;
	nkd38=1+0.25+1.5;
	myYeleds=document.getElementById('MyYeleds');
	myYeledsRadios=myYeleds.getElementsByTagName('input');
	myYeledsRadiosLength=myYeledsRadios.length;
	for(i=0;i<myYeledsRadiosLength;i++)
	{
		if(true===myYeledsRadios[i].checked)
		{
			nkd38+=0.25;
			break;
		}
	}
	value=Number(document.getElementById(IDPREFIX+'HachnasaShnatiCallBack_div').firstChild.nodeValue);
	document.getElementById('HachnasaShnati').firstChild.nodeValue=Number.beautify(nkd38*value*5*12);
}
//Collects form data and passes it to the NetWizard
function redirectToNetWizard(e)
{
	var shana,yyNow,matzav,benZug,myYeleds,myYeledsLength,i,children,
		taars,taarsLength,location,value,
		yeshuv,yeshuvValue,benZug;
	shana=document.getElementById(IDPREFIX+'Shana');
	yyNow=shana.options[shana.selectedIndex].value;
	matzav=document.getElementById(IDPREFIX+'Matzav').selectedIndex;
	location='NetWizard.aspx?YyNow='+yyNow+'&Matzav='+matzav;
	if(false===hasClass('Hidden',window.segments[window.BENZUG].div))
	{
		benZug=document.getElementById(IDPREFIX+'BenZug');
		value=benZug.options[benZug.selectedIndex].value;
		location+='&BenZug='+value;
	}
	if(false===hasClass('Hidden',window.segments[window.MYYELED].div))
	{
		myYeleds=document.getElementById('MyYeleds').getElementsByTagName('input');
		myYeledsLength=myYeleds.length;
		children=0;
		for(i=0;i<myYeledsLength;i++)
		{
			if(true===myYeleds[i].checked)
			{
				children++;
			}
		}
		if(0!==children)
		{
			location+='&Children='+children;
		}
	}
	taars=['TaarLeida','TaarAlia','TaarGius','TaarSherut'];
	taarsLength=taars.length;
	for(i=0;i<taarsLength;i++)
	{
		value=document.getElementById(IDPREFIX+taars[i]).value;
		if((''!==value)&&(false===hasClass('Hidden',window.segments[window[taars[i].toUpperCase()]].div)))
		{
			location+='&'+taars[i]+'='+value;
		}
	}
	location=location.replace('TaarSherut','TaarShichrur');
	yeshuv=document.getElementById('Yeshuv');
	if(0!==yeshuv.selectedIndex)
	{
		yeshuvValue=yeshuv.options[yeshuv.selectedIndex].value;
		location+='&Yeshuv='+yeshuvValue;
	}
	location=appendLogo(location);
	document.location.assign(location);
}
//Adds margin-top as required to push the results table into the viewport.(Only when no further questions remain)
function musbarCallBack_Complete()
{
	var tables,table,done,scroll,top;
	attachEventListener('click',document.getElementById('NetWizardButton'),redirectToNetWizard);
	tables=document.getElementById(IDPREFIX+'MusbarCallBack_div').getElementsByTagName('table');
	done=document.getElementById('Done');
	if
	(	(1===tables.length)&&
		('object'===typeof(table=tables[0])))
	{
		if(50>=table.offsetLeft)//800X600
		{
			removeClass('PossiblyMargined',table,true);
		}
		if
		(	(false===hasClass('Hidden',done))&&
			(table.offsetTop<(scroll=document.body.parentNode.scrollTop))&&
			(0<(top=scroll-table.offsetTop)))
		{
			table.style.marginTop=top+'px';
		}
	}
}
//Ugly as hell - MSIE renders select elements badly, this iterates over the elements and sets their width to slightly more than the template textbox.
function fixTridentSelectWidths()
{
	var template,selects,selectsLength,i,width;
	template=document.getElementById('TaarYeledTemplate');
	template.style.visibility='hidden';
	template.parentNode.style.visibility='';
	template.parentNode.removeAttribute('style');
	removeClass('Hidden',template.parentNode,true);
	width=template.firstChild.clientWidth+4+'px'
	addClass('Hidden',template.parentNode,false);
	selects=document.getElementsByTagName('select');
	selectsLength=selects.length;
	for(i=0;i<selectsLength;i++)
	{
		selects[i].style.width=width;
	}
}