/**
 * 247webmonitoring.com
 * @author Saikat Podder
 * This script is for adjusting the necessary fields, as the type of the monitor changes
 */

var phraseContent = "";

/**
 * @param typeFieldName Name of the 'select' input field whose change invokes this function
 * @param phraseFieldName Name of the input text field which has ot be added or removed as a result of the change in the type of the monitor
 * @param position The index of position at which the row is to be inserted into the target table
 */
function targetTypeChanged(formName, typeFieldName, phraseFieldName, position)
{
	form = document.getElementById(formName);
	if (!form)
	{
		return;
	}
		
	if (form.elements[typeFieldName] && form.elements[typeFieldName].value != null)
	{
		//if the selected type is a content type
		if (form.elements[typeFieldName].value.indexOf("content") > 0)
		{
			if (!form.elements[phraseFieldName])
			{
				addInputField(form.elements[typeFieldName].parentNode.parentNode.parentNode, "Phrase:", phraseFieldName, phraseContent, position, true);
			}
		}
		//the selected type is not a content type
		else
		{
			//try to remove the field if only it is already present
			if (form.elements[phraseFieldName])
			{
				//first save whatever value was there in the phrase text area
				if (form.elements[phraseFieldName].value != null)
				{
					phraseContent = form.elements[phraseFieldName].value;
				}
				//now remove
				removeField(form.elements[phraseFieldName]);
			}
		}
	}
}

function addInputField(table, fieldLabel, fieldName, fieldValue, position, required)
{
	lastRow = table.rows.length;
	//if the specified position is negative or greater than the last position
	if (position > lastRow || position < 0)
	{
		position = lastRow > 0 ? lastRow - 1 : lastRow;
	}
	
	newTr = table.insertRow(position);
	
	labelTd = newTr.insertCell(0);
	setElementClass(labelTd, "tdLabel");
	labelText = document.createTextNode(fieldLabel)
	labelTd.appendChild(labelText);
    if (required)
    {
    	requiredSpan = document.createElement("span");
    	requiredText = document.createTextNode("*")
		setElementClass(requiredSpan, "required");
		requiredSpan.appendChild(requiredText);
		labelTd.appendChild(requiredSpan);
    }
    
	fieldTd = newTr.insertCell(1);
	inputField = document.createElement('textarea');
	inputField.name = fieldName;
	inputField.id = fieldName.replace(/[.\-]/, "-");
	inputField.value = fieldValue;
	fieldTd.appendChild(inputField);
}

function removeField(field)
{
	targetRow = field.parentNode.parentNode;
	targetTable = targetRow.parentNode;
	try
	{
		targetTable.removeChild(targetRow);
	}
	catch(e)
	{
		alert(e);
	}
}

function setElementClass(element, className)
{
	element.setAttribute("class", className);
    element.setAttribute("className", className); //ie hack cause ie does not support setAttribute
}