/***************************************************************************
sb.js - Javascript display/logic control library for SB
****************************************************************************
Author:		Phil Ewington (phil.ewington@dlg.co.uk)
			Nuhar Manuel (nuhar.manuel@dlg.co.uk)
Date:		27/09/2007
****************************************************************************
Comments:	This library controls the display of form elements according
			to the logic defined in the XML output from SB. Child objects
			are associated to parents via an array using the parent object's
			ID as the index, acceptable as indexes are to be accessed
			directly and no looping is to be performed. Child objects are 
			made visible upon selecting an answer to the parent object that
			is defined within the answerValues list.
****************************************************************************
History:	n/a
***************************************************************************/

// set array of parent child relationships
parentChildRelationships = new Array();
additionalDataQuestions = new Array();
sAdditionalDataQuestionDiv = false;

// set array to hold validation text

// function to assign child to parent and list answers to 
// use for logic
function assignChild(parentID, childID, answerValues, validationText)
{
	if (!parentChildRelationships[parentID]) parentChildRelationships[parentID] = new Array();
	parentChildRelationships[parentID][childID] = new Array(answerValues, validationText);
}

function assignAdditionalData(parentID,sType)
{
	if(!additionalDataQuestions[parentID]) additionalDataQuestions[parentID] = new Array();
	additionalDataQuestions[parentID].push(sType);
}

// function to handle onchange event
// from an answer field
function processEvent(event)
{
    // get event object (browser specific)
	element = (event == undefined) ? window.event.srcElement : event.target;
	
	// gets id from element name [[id]]_answerid
	a = element.id.split("_");
	parentID = a[0].substr(1);
	
	// call function to handle display
	// and validation assignment of answer
	if(additionalDataQuestions[parentID] != null)
	{
		for(var i = 0; i < additionalDataQuestions[parentID].length; i++)
		{
			switch(additionalDataQuestions[parentID][i])
			{
				case "telephone": 
					showPhoneDiv(); 
					sAdditionalDataQuestionDiv = 'hidePhoneDiv()';
					break;
			}
		}
	}
	
	showHideChildren(parentID);
}

function arraySearch(aArrayToSearch,vSearchItem)
{
	for(var i in aArrayToSearch)
	{
		if(aArrayToSearch[i] == vSearchItem)
		{
			return i;
		}
	}
	return false;
}

function resetFieldValue(oField)
{
	if(oField.length)
	{
		if(oField.type == 'select-one' || oField.type == 'select-multiple')
		{
			resetSelectBox(oField)
		}
		else
		{
			for(var i = 0; i < oField.length; i++)
			{
				oField[i].checked = false;
			}
		}
	}
	else
	{
		switch(oField.type)
		{
			case 'select-one': 
			case 'select-multiple':
				resetSelectBox(oField)
				break;
			case 'text':
				oField.value = '';
				break;

		}
	}
}

function resetSelectBox(oField)
{
	for(var i = 0; i < oField.options.length; i++)
	{
		if(oField.options[i].value == 'null')
		{
			oField.options[i].selected = true;
		}
		else
		{
			oField.options[i].selected = false;			
		}
	}
}

// function to show/hide child elements for given parent object
// and assign/unassign validation for object
function showHideChildren(parentID)
{
	// account for a list of children assigned to given parent
	for (var i=0; i<parentChildRelationships[parentID].length; i++)
	{
		// check relationship exists
		if (parentChildRelationships[parentID][i])
		{
			// an index exists for this parent
			// split the parentvalues for looping through on *
			hide = true;
			answerValues = parentChildRelationships[parentID][i][0].split("*");

            if (document.getElementById("question_"+parentID).style.display != 'none')
            {
                // loop through answerValues to determine action to take
        		for (var j=0; j<answerValues.length; j++)
        		{
        			// check parent value is the same as currently selected answer
        			// set field type accordingly to check
        			if (document.getElementById('q'+parentID+"_answerid"))
        			{
            			if (document.getElementById('q'+parentID+"_answerid").type == "select-one" ||
            			    document.getElementById('q'+parentID+"_answerid").type == "select-multiple")
            			{
            			    if (document.getElementById('q'+parentID+"_answerid")[document.getElementById('q'+parentID+"_answerid").selectedIndex].value == answerValues[j])
                			{
                				// show the child object
                				hide = false;
                			}
            			}
        			}
        			
        			// radio button support
        			if (document.getElementsByName('q'+parentID+"_answerid").length && document.getElementsByName('q'+parentID+"_answerid")[0].type == "radio")
        			{
        			    // loop through radio button array looking for selected
        			    for (var k=0; k<document.getElementsByName('q'+parentID+"_answerid").length; k++)
        			    {
            			    if (document.getElementsByName('q'+parentID+"_answerid")[k].value == answerValues[j] &&
            			        document.getElementsByName('q'+parentID+"_answerid")[k].checked)
                			{
                				// set flag to show the child object
                				// & break from the collection loop
                				hide = false;
                				break;
                			}
               			}
        			}
        		}
    		}

			if (hide) 
			{
			// the field is being hidden; remove it from validation task list
				document.getElementById("question_"+i).style.display = 'none';

				if(arraySearch(aDateFields, i) !== false)
				{
					oForm.removeItem('day_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
					oForm.removeItem('month_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
					oForm.removeItem('year_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
					resetFieldValue(document.getElementById(i+'_day'));
					resetFieldValue(document.getElementById(i+'_month'));
					resetFieldValue(document.getElementById(i+'_year'));
				}
				else
				{
					resetFieldValue(document.getElementById('q'+i+"_answerid"));
					oForm.removeItem('q'+i+"_answerid", "You must specify " + parentChildRelationships[parentID][i][1]);
				}
	
				if(sAdditionalDataQuestionDiv !== false)
				{
					eval(sAdditionalDataQuestionDiv);
					sAdditionalDataQuestionDiv = false;
				}
	
				// check if this child object is a parent itself
				if (parentChildRelationships[i] && parentChildRelationships[i].length) showHideChildren(i);
			}
			else
			{
				// display question
				document.getElementById("question_"+i).style.display = 'block';

				// if validation text is not "Optional" then add to validation list (temp bodge as SB does not allow empty validation text and child question process does not read list of validations 
				if(parentChildRelationships[parentID][i][1] != 'Optional')
				{
					if (document.getElementsByName('q'+i+"_answerid").length && document.getElementsByName('q'+i+"_answerid")[0].type == "checkbox")
					{
						oForm.xOfAddItem('q'+i+"_answerid", 1, 1000, "You must specify " + parentChildRelationships[parentID][i][1]);
					}
					else
					{
						if(arraySearch(aDateFields, i) !== false)
						{
							oForm.addItem('day_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
							oForm.addItem('month_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
							oForm.addItem('year_'+i, "You must specify " + parentChildRelationships[parentID][i][1]);
						}
						else
						{
							oForm.addItem('q'+i+"_answerid", "You must specify " + parentChildRelationships[parentID][i][1]);
						}
					}
				}
			}
		}
	}
	return true;
}