//Used in the Questions section of GBase
//Suedo Constants
 
//Repeating Row Functions - used to add repeating rows or sections
//    oFormEle is the Formelement triggering the change, oTheTable is the table containg all the section rows, oSecRow is the Row to be added

var nTempID = 999;
var m_oSelect = null;
var m_oDestSelect = null;
var m_oDestinationSelect = null;
var m_TableScroll = false;
var m_ScrollParent = null;
var m_LastTR = null;
var m_PageScrollY = null;
var m_ConfirmSubmit = false;
var m_selectedValue = null;
var m_PageInputFields = null;
var m_TableSortWarnedArray = new Array();
var m_ConfirmOnce = null;
var m_HideRepeatSectionDelete = false;
var m_scroll_pos = 0;

var Ajax = new Object();
Ajax.Variables = new Array();
Ajax.PostUrl = null;
Ajax.ResponseFormat = "text";
Ajax.Response = null;
Ajax.PostProcess = null;
Ajax.Status = 0;
Ajax.OnError = null;
Ajax.Method = "POST";
Ajax.Async = true;
Ajax.Overlay = true;
Ajax.WaitMessage = "";

Ajax.Init = function()
{
	Ajax.Variables = new Array();
	Ajax.PostUrl = null;
	Ajax.ResponseFormat = "text";
	Ajax.Response = null;
	Ajax.PostProcess = function(){ if(Ajax.Status >= 2)alert("Data is returned but PostProcess method is not assigned!"); else{ alert("Data is not returned or PostProcess method is not assigned"); }}
	Ajax.OnError = function(){ alert("Data not found! Please check the URL."); }
	Ajax.Method = "POST";
	Ajax.Status = 1;
	Ajax.Async = true;
	Ajax.Overlay = true;
	Ajax.WaitMessage = "";
}

Ajax.Request = function()
{
	Ajax.oRequest = null;

	if (window.ActiveXObject) 
		Ajax.oRequest = new ActiveXObject("Microsoft.XMLHTTP");
	else
		Ajax.oRequest = new XMLHttpRequest();
	
	
	if(Ajax.oRequest) 
	{
		//when Async is set to false, onreadystatechange is out of context. Because the call is synchronous, the result is ready on the next line.
		//firefox is too strict on this and doesn't like assigning vestigial event handling.
		if(Ajax.Async)
		{
			if(Ajax.Overlay)
			{
				Overlay.innerHTML = Ajax.WaitMessage;
				Overlay.init();
				Overlay.show();
			}
			Ajax.oRequest.onreadystatechange = Ajax.OnReadyStateChange;
		}
		Ajax.oRequest.open(Ajax.Method, Ajax.PostUrl, Ajax.Async);
		Ajax.oRequest.send(null);
		Ajax.Status = 2;
		if(Ajax.Async == false)
		{
			if(Ajax.ResponseFormat == "xml")
				Ajax.Response = Ajax.oRequest.responseXML;
			else
				Ajax.Response = Ajax.oRequest.responseText;
			
			Ajax.PostProcess(Ajax.Response);
			Ajax.Status = 4;
			Overlay.hide();
		}
	}
	else
	{
		Overlay.hide();
		alert("Error processing asyncronous request! XMLHttpRequest is not supported. Please use a compatible browser.");
		return -1;
	}
}

Ajax.OnReadyStateChange = function()
{
	if (Ajax.oRequest.readyState == 4) 
	{
		if (Ajax.oRequest.status == 200) 
		{
			if(Ajax.ResponseFormat == "xml")
				Ajax.Response = Ajax.oRequest.responseXML;
			else
				Ajax.Response = Ajax.oRequest.responseText;
			
			Ajax.Status = 3;
			
			Ajax.PostProcess(Ajax.Response);
			
			Ajax.Status = 4;
			Overlay.hide();
		}
		else
		{
			Overlay.hide();
			eval("Ajax.OnError()");
		}
	}
}

function CallbackForSchoolList(sSelect, sDestSelect, pageID)
{
	m_oSelect = document.getElementById(sSelect);
	m_oDestSelect = document.getElementById(sDestSelect);
	
	//m_oSelect.onchange=null;

	Ajax.Init();
	Ajax.PostProcess = processData;
	Ajax.PostUrl = "DWQuestions.aspx?async=true&orgid="+ m_oSelect.value +"&p=" + pageID;
	Ajax.ResponseFormat = "text";
	Ajax.OnError = function() { alert("Error fetching School data. Please write up a dticket for assistance.")};
	Ajax.Request();
	
	//asyncRequest(m_oSelect.value, pageID, '');
}

document.onreadystatechange = RestoreScrollY;


function RestoreScrollY()
{
	if(document.readyState == "complete")
	{
		try{
		window.onscroll = TrackScrollY;
		m_PageScrollY = document.getElementById("hdnScrollY");
		window.scrollTo(0, m_PageScrollY.value);
		}
		catch(e)
		{
		}
	}
}

function TrackScrollY()
{
	try{
		m_PageScrollY.value = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;;
	}
		catch(e)
		{
		}
}

function AddNewRepeatingRow(oFormEle, oTheTable, oSecRow )
{
	var oRetval = null;
	var nMaxRepeats = oTheTable.MaxRepeats;
	if (nMaxRepeats != null && nMaxRepeats > 0)
	{
		var f = oSecRow;
		oTheTable.MaxRepeats = --nMaxRepeats;
		//RenameFormElementInRow(oSecRow);
		oTheTable.tBodies[0].appendChild(oSecRow); // Add the new row
		RenameFormElementByRow(oTheTable); // Rename Form Names
		oSecRow = oSecRow.cloneNode(true); // get a new copy of the row
		//oFormEle.onchange = null; // remove the trigger
		oRetval = oSecRow; // return the new copy to be assigned to the next new row.		
		//RenameRadios();
	}	//end if nMaxRepeats
	
	return oRetval;
}// end function AddNewRepeatingRow

function RenameFormElementByRow(oTheTable)
{
	var oRows =  oTheTable.rows;
	for(nRow=0; nRow < oRows.length; nRow++)
	{
		var oAllNodes = oRows[nRow].all;
		for(nNode=0; nNode < oAllNodes.length; nNode++)
		{ // Loop through the children
			var oCurAllNode = oAllNodes[nNode];
			if(oCurAllNode.DWRepeat == 1)
			{ // select the form elements that are repeated
				var xName = oCurAllNode.name;
				oCurAllNode.removeAttribute("name");
				
				xName = xName.replace(/_\d+/, "_" + (nRow - 1)) // change their name by adding the new repeatnum
				oCurAllNode.setAttribute("name", xName, 0);
				
				var oAttrib = document.createAttribute("name");
				oAttrib.value = xName;
				
				oCurAllNode.setAttributeNode(oAttrib);
			}
			if(oCurAllNode.DWRepeatID == 1)
			{ // select the RepeatID elements
				oCurAllNode.value = oCurAllNode.value.replace(/_\d+/, "_" + (nRow - 1)) // Change it name also
			}
			if(oCurAllNode.DWPopupRepeatID == 1)
			{ // select the form elements that are repeated
				oCurAllNode.PreQuestion = oCurAllNode.PreQuestion.replace(/_\d+/, "_" + (nRow - 1)) // change their name by adding the new repeatnum
			}
		}	
	}
}
function RenameFormElementInRow(oTheRow){
	var oAllNodes = oTheRow.all;
	nTempID++;
	
	for(nNode=0; nNode < oAllNodes.length; nNode++)
	{ // Loop through the children
		var oCurAllNode = oAllNodes[nNode];
		if(oCurAllNode.DWRepeat == 1)
		{ // select the form elements that are repeated
			var xName  = oCurAllNode.name;
			oCurAllNode.removeAttribute("name");
			
			xName = xName.replace(/_\d+/, "_" + (nNode - 1)) // change their name by adding the new repeatnum
			oCurAllNode.setAttribute("name", xName);
		}
		if(oCurAllNode.DWRepeatID == 1)
		{ // select the RepeatID elements
			oCurAllNode.value = oCurAllNode.value.replace(/_\d+/, "_" + (nNode - 1)); // Change it name also
		}
		if(oCurAllNode.DWPopupRepeat == 1)
		{ // select the form elements that are repeated
			oCurAllNode.PreQuestion = oCurAllNode.PreQuestion.replace(/_\d+/, "_" + (nNode - 1)); // change their name by adding the new repeatnum
		}
	}	
}

// Removes a Repeating Row
function RemoveRepeatingRow(oTBody, iKey)
{
	try{
	var sBorder = oTBody.parentNode.style.border.toString();
	oTBody.parentNode.style.border = "solid #FDCD00 2";

	var bPass = true;
	//subsequent child section deletes are silent
	if(iKey != -999)
		bPass = confirm("This action will permanently remove this record after you save this form.");
	
	if(bPass){
		oTBody.parentNode.style.border = sBorder;
		var oTheTable = oTBody.parentNode;
		for(var x = 0; x < oTBody.childNodes.length; x++)
		{
			var oTR = oTBody.childNodes[x];
			for(var y= 0; y < oTR.childNodes.length; y++)
			{
				var oTD = oTR.childNodes[y];
				for(var z= 0; z < oTD.childNodes.length; z++)
				{
					var oElement = oTD.childNodes[z];
					if(oElement.getAttribute)
					{
						var oEleType = oElement.getAttribute("ElementType");
						if(oEleType == "hidden" && oElement.name == "DWResponseID")
						{	
							oElement.value = "-" + oElement.value;
						}
						if(oEleType == "table")
						{
							//IE specific: getElementsByName
							var oButtons = document.getElementsByName("btnRemove" + iKey);
							for(var i = 0; i < oButtons.length; i++)
							{
								//IE specific: fireEvent
								oButtons[i].fireEvent("onclick");
							}
						}
					}
				}
			}
		}
		
		//hide
		oTheTable.style.display = "none";
		
		//create a container
		var oPlaceHolder = document.createElement("span");
		//create a message holder
		var oMessage = document.createElement("span");
		oMessage.style.backgroundColor = "#FFFFFF";
		oMessage.style.border = "dotted 2px #FF0000";
		oMessage.style.padding = "2";
		//Give option to undo
		oMessage.innerHTML= "Section delete pending - <span style='text-decoration: underline; cursor: pointer' onclick='UnRemoveRepeatingRow(this.parentNode.parentNode.previousSibling.previousSibling.childNodes[0], " + iKey + "); this.parentNode.parentNode.removeNode(true);'>Click here</span> to undelete.";
		oMessage.title = "Save this page to permanently delete this section";
		oPlaceHolder.appendChild(oMessage);
		//create a <br>
		var oBr = document.createElement("br");
		oPlaceHolder.appendChild(oBr);
		//create a <br>
		oBr = document.createElement("br");
		oPlaceHolder.appendChild(oBr);
		
		//append the container next to the table it is refering to.
		oTheTable.parentNode.insertBefore(oPlaceHolder);
	}
	else
	{
		oTBody.parentNode.style.border = sBorder;
	}
	}
	catch(e)
	{}
}

// Undo Removing a Repeating Row
function UnRemoveRepeatingRow(oTBody, iKey)
{
	try{
		var oTheTable = oTBody.parentNode;
		
		for(var x = 0; x < oTBody.childNodes.length; x++)
		{
			var oTR = oTBody.childNodes[x];
			for(var y= 0; y < oTR.childNodes.length; y++)
			{
				var oTD = oTR.childNodes[y];
				for(var z= 0; z < oTD.childNodes.length; z++)
				{
					var oElement = oTD.childNodes[z];
					if(oElement.getAttribute)
					{
						var oEleType = oElement.getAttribute("ElementType");
						if(oEleType == "hidden" && oElement.name == "DWResponseID")
						{
							oElement.value = Math.abs(parseInt(oElement.value));
						}
					}
				}
			}
		}
		
		//visible
		oTheTable.style.display = "";

	}
	catch(e)
	{}
}

// Removes a Repeating Row
function RemoveGenericRepeatingRow(oTR, oThePrimeTable)
{
	try{
	oTR.style.border = "solid #FDCD00 2";
	var bPass = confirm("This action will permanently remove this record after you save this form.");
	if(bPass){
		var oTheTable = oTR.parentNode;
		
			for(var y= 0; y < oTR.childNodes.length; y++)
			{
				var oTD = oTR.childNodes[y];
				for(var z= 0; z < oTD.childNodes.length; z++)
				{
					var oElement = oTD.childNodes[z];
					if(oElement.getAttribute)
					{
						var oEleType = oElement.getAttribute("ElementType");
						if(oEleType == "hidden" && oElement.name == "DWResponseID")
						{
							oElement.value = "-" + oElement.value;
						}
					}
				}
			}
		
		oTR.style.display = "none";
	}
	else
	{
		oTR.parentNode.style.border = "0";
	}
	}
	catch(e)
	{}
}

// Shows a popup window
function ShowPopup(sQuestionID, sResponseSetID, sActionerID, sChoiceID, sChoiceText)
{
	try
	{
		var sChoiceURL = sChoiceText.split(":-")[1];
		var oURLParts = sChoiceURL.split("?");
		var sURL = oURLParts[0] + "?";
		var sQueryParams = oURLParts[1];
		var oParamList = sQueryParams.split("&");
		for(var nIndex = 0; nIndex < oParamList.length; nIndex++)
		{
			if (nIndex > 0)
				sURL += "&";

			var oParts = oParamList[nIndex].split("=");
			switch(oParts[0].toLowerCase())
			{
			case "questionid":
				sURL += oParts[0] + "=" + sQuestionID;
				break;
			case "responsesetid":
				sURL += oParts[0] + "=" + sResponseSetID;
				break;
			case "actionerid":
				sURL += oParts[0] + "=" + sActionerID;
				break;
			default:
				sURL += oParts[0] + "=" + oParts[1];
				break;
			}	//end switch oParts[0]
		}	//end for nIndex
		
		var screenY, screenX, leftvar, topvar, properties;
		
		if(navigator.appName == "Microsoft Internet Explorer") 
		{
			screenY = document.body.offsetHeight;
			screenX = window.screen.availWidth;
		}
		else 
		{
			screenY = window.outerHeight
			screenX = window.outerWidth
		}
		
		leftvar = (screenX - 600) / 2;
		topvar = (screenY - 400) / 2;
		if(navigator.appName != "Microsoft Internet Explorer") 
		{
			leftvar = (leftvar - pageXOffset);
			topvar = (topvar - pageYOffset);
		}
		
		properties = "height=400,width=600,status=no,toolbar=no,menubar=no,location=no, resizable=yes, scrollbars=yes, left="+ leftvar +", top="+ topvar;

		window.open(sURL, null, properties);
	}
	catch(e)
	{}
}	//end ShowPopup

//deprecated.
function ShowPopup2(oFormEle, sChoiceID, sOtherFormEle){
	//alert(oFormEle.parentNode.parentNode.outerHTML);
	//alert(eval("oFormEle.form.all." + sOtherFormEle))
	var oOtherFormEle = GetFormElement(oFormEle.form, sOtherFormEle);
	//alert("Value of Previous Question=" + oOtherFormEle.value);
	oPopupText = oFormEle;
	var sKey2 = oOtherFormEle.value;
	if(sKey2 != ""){
		var sURL = "DWWizardPopup.aspx?obj=" + sChoiceID + "&key2=" + sKey2;
		window.open(sURL,null,"height=300,width=500,status=no,toolbar=no,menubar=no,location=no, scrollbars=yes");
	}
	else{
		alert("Please answer the previous field first.")
	}
}

function fnURLpopup(obj)
{
	var oURL = obj.parentNode.childNodes[0];
	if(oURL.value != '')
	{
		var sURL;
		if(oURL.value.indexOf('://') > 0)
		{
			sURL = oURL.value;
		}
		else
		{
			sURL = "http://" + oURL.value;
		}
		
		properties = "height=400,width=600,status=yes,toolbar=yes,menubar=yes,location=yes, resizable=yes, scrollbars=yes";
		window.open(sURL, null, properties);
	}
}

function OnPopupReturnValue()
{ 
	try{
		var oHdnText = document.getElementById(sRawReturnValue);
		if(oHdnText)
		{
			event.srcElement.detachEvent('onpropertychange', OnPopupReturnValue);
			
			if(oHdnText.value != "")
			{
				var oTextBox = document.getElementById(sPopupText);
				var aValue = oHdnText.value;
				aValue = aValue.split("|");
				
				oTextBox.value =aValue[1];
				document.getElementById(sPopupTextID).value =aValue[0];
				
				oTD = oTextBox.parentNode.parentNode;
				
				for(var x = 2; x < aValue.length; x++)
				{
					var oBR = document.createElement("<br/>");
					var oLink = document.createElement("<a target='_blank' href='" + aValue[x] + "'></a>");
					oLink.innerText = aValue[x];
					oTD.appendChild(oBR);
					oTD.appendChild(oLink);
				}
			}
		}
	}
	catch(e)
	{}
}

function GetFormElement(oTheForm, sTheElementName){
	for(x=0; x<oTheForm.elements.length; x++){
		var oTheElement = oTheForm.elements[x];
		//alert("Looking at: " + oTheElement.name + " for: " + sTheElementName);
		if(oTheElement.name.toString() == sTheElementName){
			//alert("Found it:" + oTheElement.name + " and it value=" + oTheElement.value);
			return oTheElement;
		}
	}
}


function SetValue(oCheckBox, oFormEle, sValue){
	if(!oCheckBox.checked){
		oFormEle.value = sValue;
		oFormEle.RealValue = sValue
		oFormEle.gsonkeydownholder = oFormEle.onkeydown;
		oFormEle.onkeydown = new Function("return false;");	
		oFormEle.style.color = "#999999";
	}
	else{
		oFormEle.onkeydown = oFormEle.GSonKeyDownHolder;	
		oFormEle.style.color = "";
		oFormEle.focus();
	}
}

function ToggleExplain(oFormEle, sQuestionPostfix, bShow){
	//var oDiv = oFormEle.parentNode.getElementById("Explain" + sQuestionPostfix);
	//var oTextArea = oFormEle.parentNode.getElementById("ExplainText" + sQuestionPostfix);
	var oDiv = document.getElementById("Explain" + sQuestionPostfix);
	var oTextArea = document.getElementById("ExplainText" + sQuestionPostfix);	
	var bDisplay = oFormEle.checked && bShow;	
	
	if(document.all)
		sDisplay = bDisplay ? "block" : "none";
	else
		sDisplay = bDisplay ? "" : "none";
	if(bDisplay)
		oTextArea.value="";
	oDiv.style.display = sDisplay;	
}

function asyncRequest(orgID, pageID, response)
{
	if (response != '')
	{ 
		// Response mode
		if (response == '1')
		{
			alert("error");
		}
		else
		{
			alert("hidden");
		} 
	}
	else
	{
		// Input mode
		url = 'DWQuestions.aspx?async=true&orgid='+ orgID +'&p=' + pageID;
		loadXMLDoc(url);
	}

}

function loadXMLDoc(url) 
{
	if (window.ActiveXObject) 
		req = new ActiveXObject("Microsoft.XMLHTTP");
	else
		req = new XMLHttpRequest();
	
		if(req) 
		{
			req.onreadystatechange = processReqChange;
			req.open("POST", url, true);
			req.send();
		}
}

function processReqChange() 
{
	// only if req shows "complete"
	if (req.readyState == 4) 
	{
		// only if "OK"
		if (req.status == 200) 
		{
			processData(req.responseText);
		} 
		else 
		{
			alert("There is a problem fetching the async data:\n" + req.statusText);
		}
	}
}

function processData(sXML)
{
	var xmlDoc;
	
	if(document.all)
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.loadXML("<root>" + sXML + "</root>");
	
		var oNodes = xmlDoc.documentElement.selectNodes("/root/DWExternalData");
		
		m_oDestSelect.options.length = 0;
		var oFOption = new Option("Select a School", "");
		m_oDestSelect.options.add(oFOption);
		
		for(z=0; z < oNodes.length; z++)
		{	
			oCurrentData = oNodes.item(z);
			sSID = oCurrentData.getAttribute("SchoolID");
			sSName = oCurrentData.getAttribute("SchoolName");
			//var sVal = sSID + "|" + sSName;
			var sVal = sSID;
			var oDefOption = new Option(sSName, sVal);
			
			//m_selectedSchoolValue is defined in DWInforms.xslt
			if(m_selectedValue)
			{
				if(sSID == m_selectedValue)
				oDefOption.selected = true;
			}
			else if(m_selectedValue == null && m_selectedSchoolValue != null)
			{
				if(sSID == m_selectedSchoolValue)
				oDefOption.selected = true;
			}
			
			m_oDestSelect.options.add(oDefOption);
		}
	}
	else
	{
		var parser=new DOMParser();
		xmlDoc=parser.parseFromString("<root>" + sXML + "</root>", "text/xml");
		
		m_oDestSelect.options.length = 0;
		var oDefOption = document.createElement("OPTION");
		m_oDestSelect.options.add(oDefOption);
		oDefOption.value = "";
		oDefOption.text = "Select a School";
		
		var oNodes = xmlDoc.documentElement.childNodes;	
		for (var i = 0; i < oNodes.length; i++)
		{							
			if ( (oNodes[i].nodeType != 3) && (oNodes[i].nodeType != 8) )
			{								
				var oDefOption = document.createElement("OPTION");
				m_oDestSelect.options.add(oDefOption);
				
				sSID = oNodes[i].attributes["SchoolID"].value;
				sSName = oNodes[i].attributes["SchoolName"].value;
				var sVal = sSID;
				
				oDefOption.text = sSName;
				oDefOption.value = sVal;
								
				//m_selectedSchoolValue is defined in DWInforms.xslt
				if(m_selectedValue)
				{
					if(sSID == m_selectedValue)
					oDefOption.selected = true;
				}
				else if(m_selectedValue == null && m_selectedSchoolValue != null)
				{
					if(sSID == m_selectedSchoolValue)
					oDefOption.selected = true;
				}
			}
		}	//end for i
	}
}

function IntelliSubmit(evt, sURL, bIsSubmit, bIsApprove, bIsReject, bIsDelete)
{
	var oForm;
	var bContinue = true; 
	
	if(document.all)
		oForm = document.getElementById("QuestionForm");
	else
		oForm = document.forms["QuestionForm"];
		
	if(bIsApprove)
		sURL = sURL + "&ResponseStatus=3";
	else if(bIsSubmit)
	{
		if(m_ConfirmSubmit == true)
		{
			//This function is defined in the Wizard level Custom JavaScript
			if(ConfirmSubmit())
			{
				sURL = sURL + "&ResponseStatus=2";
				bContinue = true;
			}
			else
			{
				bContinue = false;
			}
		}
		else
		{
			sURL = sURL + "&ResponseStatus=2";
		}
	}
	else if(bIsReject)
	{
		var oText = document.getElementById("txtComments");
		if(oText.value.trim() == "")
		{
			alert("Please add comments!");
			oText.focus();
			return 1;
		}
		sURL = sURL + "&ResponseStatus=4";
	}
	else if(bIsDelete)
	{
		if(confirm("This action would permanently delete all responses saved for this survey. Continue?"))
			sURL = sURL + "&deleteobj=1";
		else
			bContinue = false;
	}
	else if(bIsSubmit == false)
	{
		if(m_ConfirmSubmit == true)
		{
			//This function is defined in the Wizard level Custom JavaScript
			if(ConfirmSubmit())
			{
				sURL = sURL + "&ResponseStatus=2";
				bContinue = true;
			}
			else
			{
				bContinue = false;
			}
		}
	}
	
	if(bContinue)
	{
		oForm.action = sURL;
		
		if(document.all)
			evt.srcElement.onclick = null;
		else
			evt.target.onclick = null;
		
		oForm.submit();
	}
	
}

String.prototype.trim = function()
{
    // Use a regular expression to replace leading and trailing 
    // spaces with the empty string
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

function ResolveNavigation(oImg, iDirection, sBaseURL)
{
	var oTD = oImg.parentNode;
	var oSelect = oTD.getElementsByTagName("select")[0];
	var oOptions = oSelect.options;
	var oPrevious;
	var oNext;
	
	for(var x = 0; x < oOptions.length; x++)
	{
		if(oOptions[x].selected)
		{
			try
			{
				oPrevious = oOptions[x-1];
			}
			catch(e)
			{}
			
			try
			{
				oNext = oOptions[x+1];
			}
			catch(e)
			{}
		}
	}
	
	if(iDirection == 0)
	{
		if(oPrevious)
			window.location = sBaseURL + '&p=' + oPrevious.value;

	}
	else if(iDirection == 1)
	{
		if(oNext)
			window.location = sBaseURL + '&p=' + oNext.value;
	}
	
}


/*
document.onclick = fnNotify;

function fnNotify()
{
	var x = event.srcElement;
	if(x.innerHTML)
		alert(x.attributes.join(","));
}
*/

function fnFutureDate(oTxtSource, oTxtDestination, iDays)
{
	var sDate = oTxtSource.value;

	if(sDate != null && sDate != "")
	{
		var aDate = sDate.split("/");
		var sYear = aDate[2].toString();
		aDate[2] = sYear.substring(2,4);
		
		var SixtyDays = new Date(sYear,aDate[0]-1,aDate[1]);
		SixtyDays.setDate(SixtyDays.getDate() + iDays);
		var dYear = SixtyDays.getFullYear().toString();
		var dShortYear = dYear;
		var sMonth = SixtyDays.getMonth()+1;
		var sDay = SixtyDays.getDate();

		oTxtDestination.value = sMonth + "/" + sDay  + "/" + dShortYear;
		oTxtDestination.style.backgroundColor = "red";
	}
	else
	{
		oTxtDestination.value = "";
		oTxtDestination.style.backgroundColor = "white";
	}
	
	oTxtDestination.readOnly = true;
}

function GenerateFileInput(oSpan, oQuestionName, oQuestionID)
{
		var oParent = oSpan.parentNode;
		var objDiv = oParent.getElementsByTagName("div");
		var objSpan = oParent.getElementsByTagName("span");
		var oFile;
		
	if(oSpan.innerHTML == "Change")
	{
		oFile = document.createElement("input");
		oFile.type="file";
		oFile.name = oQuestionName;
		oFile.id = oQuestionID;
		objDiv[0].style.display = "none";
		//oParent.removeChild(objDiv[0]);
		oSpan.innerHTML = "Undo";
		
		oParent.appendChild(oFile);
	}
	else
	{	
		var objFile = oParent.getElementsByTagName("input");
		//alert(objFile.length);
		oParent.removeChild(objFile[objFile.length-1]);
		
		objDiv[0].style.display = "block";
		//oParent.appendChild(objDiv[0]);
		oSpan.innerHTML = "Change";
	}
	
}

function VirtualDelete(obj, bUndo)
{	
	var oTR = obj.parentNode.parentNode;
	var sBool;
	
	if(obj.checked)
	{
		oTR.style.backgroundColor = 'red';
		sBool = true;
	}
	else
	{
		oTR.style.backgroundColor = 'white';
		sBool = false;
	}
	
	for(var x = 0; x < oTR.childNodes.length; x++)
	{
		var oTD = oTR.childNodes[x];
		for(var y = 0; y < oTD.childNodes.length; y++)
		{
			var oInput = oTD.childNodes[y];
			if(oInput.type == "text" || oInput.type == "select-one")
			{
				if(sBool == true)
				{
					oInput.style.textDecoration = 'line-through';
					oInput.setAttribute("disabled", "true");
				}
				else
				{
					oInput.style.textDecoration = 'none';
					oInput.removeAttribute("disabled");
				}
			}
		}
	}
}

function HighlightRow(oTR1, oLastTR)
{
	var oTR = "";
	
	if(oTR1)
		oTR = oTR1
	else
		oTR = event.srcElement.parentNode.parentNode;
	
	
	
	if(oTR.Highlight == "false")
		return;
	
	
	if(!oLastTR)
	{
		oLastTR = m_LastTR;
		m_LastTR = oTR;
	}
		
	if(oLastTR)
	{
		for(var y = 0; y < oLastTR.childNodes.length-1; y++)
		{
			//if(oLastTR.childNodes[y].customColor.toUpperCase()!="RED")
			if(oLastTR.Editable)
				oLastTR.childNodes[y].style.backgroundColor=oLastTR.childNodes[y].customColor;	
		}
	}
	//var oTBody = oTR.parentNode;
	
	/*
	for(var x = 1; x < oTBody.childNodes.length; x++)
	{
		for(var y = 0; y < oTBody.childNodes[x].childNodes.length; y++)
		{
			//if(oTBody.childNodes[x].childNodes[y].customColor == false)); 
				oTBody.childNodes[x].childNodes[y].style.backgroundColor=oTBody.childNodes[x].childNodes[y].customColor;
			
		}
		
		//oTBody.childNodes[x].style.backgroundColor = 'white';
	}
	*/
	//alert(event.srcElement.checked);
	//if(event.srcElement.checked)
	//{
		for(var y = 0; y < oTR.childNodes.length-1; y++)
		{
			oTR.childNodes[y].style.backgroundColor='#5C9BCC';
		}
	//}
	
	
	var spn = document.getElementById("spnActiveRow");
	if(spn)
	{	
		var sBusNum = oTR.childNodes[0].childNodes[3].value;
		spn.innerHTML = "You are editing <b>Bus No.: <font color='red'>" + sBusNum + "</font></b>";	
	}
}

function MarkAsDeleted()
{
	var oTR = event.srcElement.parentNode.parentNode;
	
	if(oTR.Deletable == "false")
		return;
	
	if(event.srcElement.checked == true)
	{
		oTR.Editable = false;
		//oTR.style.backgroundColor = 'red';
		ManipulateDeleteRow(oTR,true);
	}
	else
	{
		oTR.Editable = true;
		//oTR.style.backgroundColor = oTR.HighlightColor;
		ManipulateDeleteRow(oTR,false);	
	}	
}

function TableScrollStart(iDirection)
{
	m_TableScroll = true;
	
	if(m_ScrollParent == null)
		m_ScrollParent = event.srcElement.Parent;
		
	TableScroll(iDirection, m_ScrollParent);
}

function TableScrollStop()
{
	m_TableScroll = false;
	m_ScrollParent = null;
}

function TableScroll(iDirection, sParent)
{
	if(m_TableScroll)
	{
		var tC = document.getElementById(sParent);
		if(tC)
		{
			if(iDirection == 1)
			{
				if(tC.style.posLeft < 1)
				tC.style.left = tC.style.posLeft + 30;
			}
			else if(iDirection == 0)
			{
				tC.style.left = tC.style.posLeft - 30;
			}
			else if(iDirection == 2)
			{
				if(tC.style.posTop < 0)
				tC.style.top = tC.style.posTop + 10;
			}
			else if(iDirection == 3)
			{
				tC.style.top = tC.style.posTop - 10;
			}
			
			setTimeout("TableScroll("+ iDirection +", '"+ sParent +"')", 10);
		}
	}
}

function ManipulateDeleteRow(oDestinationTR,bDelete)
{
	for(var counter = 0; counter < oDestinationTR.childNodes.length-1; counter++)
	{
		var oTD = oDestinationTR.childNodes[counter];
		for(var a = 0; a < oTD.childNodes.length; a++)
		{
			if(oTD.childNodes[a].ElementType=="text" || oTD.childNodes[a].ElementType=="select-one" )
			{
				if(bDelete)
					oTD.childNodes[a].style.textDecoration = "line-through";
				else
					oTD.childNodes[a].style.textDecoration = "none";
				oTD.childNodes[a].disabled=bDelete;
			}
			if(bDelete)
				oTD.style.backgroundColor = 'red';
			else
				oTD.style.backgroundColor = oTD.customColor;
		}
	}	
}

function fnSyncValue(oObj, context)
{
	//if the last element is not "DWOriginalResponse" or "DWParentRepeatNum" 
	//then it is inferred that it is the prime textbox with value that get stored in the DB
	try
	{
		if(oObj.parentNode.lastChild)
			if(oObj.parentNode.lastChild.name.indexOf("Original") < 0 && oObj.parentNode.lastChild.name.indexOf("ParentRepeat") < 0)
				oObj.parentNode.lastChild.value = oObj.value;
	}
	catch(e)
	{}
}

function fnUnsaveCheckBox()
{
		var oCheckBox = event.srcElement;
		var oTD = oCheckBox.parentNode;
		var oHdnDeletedChoiceIDs;		

	if(oCheckBox.checked == false)
	{
		for(var x = 0; x < oTD.childNodes.length; x++)
		{
			var oEleType = oTD.childNodes[x].ElementType;
				if(oEleType == "hidden" &&   oTD.childNodes[x].name == "DWResponseID")
				{
					 oTD.childNodes[x].value = "-" +  oTD.childNodes[x].value;
				}
		}
	}
	else
	{
		for(var x = 0; x < oTD.childNodes.length; x++)
		{
			var oEleType = oTD.childNodes[x].ElementType;
				if(oEleType == "hidden" &&   oTD.childNodes[x].name == "DWResponseID")
				{
					 oTD.childNodes[x].value = Math.abs(oTD.childNodes[x].value);
				}
		}
	}
}


function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
    }

    document.getElementById(id).style.height= (newheight) + "px";
    document.getElementById(id).style.width= (newwidth) + "px";
}

function Navigate(evt, sContext, sUrl, sConfirmMsg, sByPassUrl)
{
	if(sConfirmMsg)
	{
		if(confirm(sConfirmMsg) == true)
		{
			document.getElementById('hdnFormSubmit').value = sContext; 
			IntelliSubmit(evt, sUrl);
		}
		else
		{
			window.location = sByPassUrl;
		}
	}
	else
	{
		document.getElementById('hdnFormSubmit').value = sContext; 
		IntelliSubmit(evt, sUrl);
	}
}

function JumpToUrl(sUrl, sConfirmMsg)
{
	if(sConfirmMsg)
	{
		if(confirm(sConfirmMsg) == true)
		{
			window.location = sUrl;
		}
	}
	else
	{
		window.location = sUrl;
	}
}

function fnShowNewSection(oButton, iSectionID, bShow)
{
	var oNewSection = document.getElementById("NewSec" +iSectionID);
	var sDisplayBlock;
	
	if(document.all)
		sDisplayBlock = "block";
	else
		sDisplayBlock = "table-row";
	
	if(bShow == true)
	{
		oNewSection.style.display = sDisplayBlock;
		oButton.parentNode.parentNode.style.display = "none";
	}
	else
	{
		oNewSection.style.display = "none";
		oButton = document.getElementById("btnAddNew" + iSectionID);
		oButton.parentNode.parentNode.style.display = sDisplayBlock;
	}
}

function fnMovePickerboxItems(sDirection, oButton)
{
	var oListboxLeft = oButton.parentNode.previousSibling.childNodes[0];
	var oListboxRight = oButton.parentNode.nextSibling.childNodes[0];
	
	var oListbox1 = oListboxLeft;
	var oListbox2 = oListboxRight;
	
	var bIsAssigning = false;
	
	switch(sDirection.toUpperCase())
	{
		case "RIGHT":
			oListbox1 = oListboxLeft;
			oListbox2 = oListboxRight;
			bIsAssigning = true;
		break;
		case "LEFT":
			oListbox1 = oListboxRight;
			oListbox2 = oListboxLeft;
		break;
	}
	
	var bAlreadyExists = false;
	if(bIsAssigning)
	{
		if(oListbox2.options.length > 0) 
		{
			for(var nIndex = 0; nIndex < oListbox2.options.length; nIndex++)
			{			
					if(oListbox2.options[nIndex].value == oListbox1.options[oListbox1.selectedIndex].value)
					{
						bAlreadyExists = true;
						break;
					}
			}	
		}
	}

	if(bAlreadyExists == false)
	{
		for(var x = 0; x < oListbox1.options.length; x++)
		{
			var oOption = oListbox1.options[x];
			if(oOption.selected == true)
			{
				var oNewOption = document.createElement("option");
				oNewOption.value = oOption.value;
				oNewOption.text = oOption.text;
				oListbox2.options.add(oNewOption);
				oListbox1.remove(x--);
				
				var oHiddedTextBox = oButton.parentNode.lastChild;
				oHiddedTextBox.value = oHiddedTextBox.value.trim();
				
				if(sDirection.toUpperCase() == "LEFT")
				oHiddedTextBox.value = SpliceCSVValue(oOption.value, oHiddedTextBox.value);
				else
				oHiddedTextBox.value = AddCSVValue(oOption.value, oHiddedTextBox.value);
			}
		}
	}
}

function SpliceCSVValue(iValue, sStr)
{
	var aRawvalues = sStr.split(",");
	var aValues = new Array();
	aValues = aRawvalues;
	
	for(var x = 0; x < aValues.length; x++)
	{
		if(aValues[x] == iValue)
			aValues.splice(x, 1);
	}
	return aValues;
}

function AddCSVValue(iValue, sStr)
{
	var bContinue = true;
	var aValues = new Array();
	if(sStr != "")
	{
		var aRawvalues = sStr.split(",");
		
		aValues = aRawvalues;
		
		for(var x = 0; x < aValues.length; x++)
		{
			if(aValues[x] == iValue)
				bContinue = false
		}
	}
	if(bContinue)
	aValues.push(iValue);
	return aValues;
}

function FillDropDown(sXml, sDropDownName, sXPath, sDDValue, sDDName, bShowDefaultItem)
{
	var xmlDoc;
	var oDropDown = document.getElementById(sDropDownName);
	xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.async=false;
	xmlDoc.loadXML("<root>" + sXml + "</root>");
	var oNodes = xmlDoc.documentElement.selectNodes(sXPath);
	var oSelectedItem = xmlDoc.documentElement.selectSingleNode("/root/SelectedResponse");

	oDropDown.options.length = 0;
	var oFOption = "";
	
	if(bShowDefaultItem)
	{
		oFOption = new Option("Select an item", "-1");
		oDropDown.options.add(oFOption);
	}	

	for(z=0; z < oNodes.length; z++)
	{
		oCurrentData = oNodes.item(z);
		var sVal = oCurrentData.getAttribute(sDDValue);
		var sSName = oCurrentData.getAttribute(sDDName);
		var oDefOption = new Option(sSName, sVal);

		if(oSelectedItem)
			if(parseInt(sVal) == oSelectedItem.getAttribute("ResponseText"))
				oDefOption.selected = true;
		oDropDown.options.add(oDefOption);
	}
}


function fnTogglePageSaveOptions(sMode)
{
	var sDisplay;
	switch(sMode.toUpperCase())
	{
		case "HIDE":
			sDisplay = "none";
			break;
		case "SHOW":
			sDisplay = "";
			break;
	}
	
	var x = 0;
	var y = ""; // to apply on both top and bottom toolbars
	
	do
	{
		var oSpnSave = document.getElementById("spnSave" + y);
		var oSpnSaveNExit = document.getElementById("spnSaveNExit" + y);
		var oSpnPrevious = document.getElementById("spnPrevious" + y);
		var oSpnNext = document.getElementById("spnNext" + y);
		var oSpnJump = document.getElementById("spnJump" + y); //page dropdown
		var oSpnSummary = document.getElementById("spnSummary" + y);
		
		oSpnSave.style.display = sDisplay;
		oSpnSaveNExit.style.display = sDisplay;
		oSpnPrevious.style.display = sDisplay;
		oSpnNext.style.display = sDisplay;
		oSpnJump.style.display = sDisplay;
		oSpnSummary.style.display = sDisplay;
		x++;
		y = "1";
	}
	while(x <2)
	
	if(m_PageInputFields)
	{
		
	}
	else
		m_PageInputFields = document.getElementsByTagName("input");

	for(var z = 0; z < m_PageInputFields.length; z++)
	{
		if(m_PageInputFields[z].type == "button")
		{
			if(m_PageInputFields[z].id)
			{
				if(m_PageInputFields[z].id.indexOf("btnAddNew") > -1)
				{
					m_PageInputFields[z].style.display = sDisplay;
				}
			}
		}
	}
		
}

function fnGetCurrentRepeatNumber(oEle)
{
	var sName = oEle.name;
	if(sName.indexOf("_") > -1)
	{
		var aName = sName.split("_");
		return aName[1];
	}
}

function moveNextPage(sPageURL,  sfp, spageQuerystring)
{
	var sURL = sPageURL+"?"+spageQuerystring+"&Filter="+sfp;																						
	var oFrm = document.getElementById("QuestionForm");
	oFrm.action = sURL;
	oFrm.submit();
	//window.location = sURL;
}

function fnBuildEditor(sTextareaName)
{
	//new instance of FCK editor to replace the textarea placeholder
	var oFCKeditor = new FCKeditor(sTextareaName, '670', '600', 'DWBasic');
	oFCKeditor.BasePath = "fckeditor/";
	oFCKeditor.ReplaceTextarea();
	
	//To override Portal CSS default styling of IFrame
	var oTextarea = document.getElementById(sTextareaName);
	var oIFrame = oTextarea.parentNode.getElementsByTagName("IFRAME");
	if(document.all)
	oIFrame[0].style.display = "block";
	else
	oIFrame[0].style.display = "inline";
	oIFrame[0].style.height="400px";
}

function StripToAlphaNumeric(oTextBox)
{
	var sText = oTextBox.value;
	var sStripped = "";
	var sToLower = sText.toLowerCase();
	
	for(var c = 0; c < sText.length; c++)
	{
		var ch = sToLower.charAt(c);
		var cOk = sText.charAt(c);
		if(ch == "a" || ch == "b" || ch == "c" || ch == "d" || ch == "e" || ch == "f" ||
		   ch == "g" || ch == "h" || ch == "i" || ch == "j" || ch == "k" || ch == "l" ||
		   ch == "m" || ch == "n" || ch == "o" || ch == "p" || ch == "q" || ch == "r" ||
		   ch == "s" || ch == "t" || ch == "u" || ch == "v" || ch == "w" || ch == "x" || ch == "y" || ch == "z" ||
		   ch == "0" || ch == "1" || ch == "2" || ch == "3" || ch == "4" || ch == "5" || ch == "6" || ch == "7" ||
		   ch == "8" || ch == "9" || ch == "-" || ch == "/" || ch == " " || ch == "." || ch == "'")
		{
			sStripped += cOk;
		}
	}
	oTextBox.value = sStripped;
}

function fnToggleVisibility(oDOMElement)
{
	if(oDOMElement.style.display != "none")
		oDOMElement.style.display = "none";
	else
		oDOMElement.style.display = "block";
}

//Used on DWSummary.xslt
//TO warn before sorting table with more than certain number of rows.
function fnWarnOnLargeTableSort(sTableName, sCoumnName, iMaxRowsAllowed)
{
	var bWarnOK = false;
	
	for(var i =0; i< m_TableSortWarnedArray.length; i++)
	{
		if(sColumnName == m_TableSortWarnedArray[i])
		{bWarnOK = true; break;}
		else 
		{m_TableSortWarnedArray.push(sColumnName); bWarnOK = false;}
	}
	
	if(bWarnOK) return true;
	
	var oTable = document.getElementById(sTableName);
	
	if(iMaxRowsAllowed == null) iMaxRowsAllowed = 100;
	
	var oTBody = null;
	for(var i=0; i < oTable.childNodes.length; i++)
	{
		if ( (oTable.childNodes[i].nodeType != 3) && (oTable.childNodes[i].nodeType != 8) )
		if (oTable.childNodes[i].tagName.toUpperCase() == "TBODY")
		{
			oTBody = oTable.childNodes[i];
			break;
		}
	}
	
	var nRowCount = oTBody.childNodes.length;
	if(nRowCount > iMaxRowsAllowed)
	{
		if(confirm('CAUTION:\n\nThis page contains many record and it may take long time to \'Sort\' the records.\n\nPress \'Cancel\' to abort. \n\nAre you sure you want to continue with this option?'))
			bWarnOK = true;
		else
			bWarnOK = false;
	}
	else
		bWarnOK = true;
	
	return bWarnOK;
}

//Used on DWSummary.xslt
//To highlight and indicate sort direction
function PointColumn(oColumn, sTable)
{
	//The 2 in length-2 is for the last 3 columns... Since delete is suppressed, it is 2..when we show delete it will be 3
	var oTR = oColumn.parentNode;
	
	for(var x=0; x < oTR.childNodes.length-3; x++)
	{
		var s = new String(oTR.childNodes[x].innerText);
		s = ReplaceAll(s, m_UpArrow, "");
		s = ReplaceAll(s, m_DownArrow, "");
		oTR.childNodes[x].innerText = s;
		oTR.childNodes[x].style.backgroundColor = m_backgroundColor;
	}
	
	if(oColumn.up == "1")
	{
		oColumn.innerHTML += m_UpArrow;
		oColumn.style.backgroundColor = "#FCDC00";
		oColumn.up = "0";
	}
	else
	{
		oColumn.innerHTML += m_DownArrow;
		oColumn.style.backgroundColor = "#FCDC00";
		oColumn.up = "1";
	}
}

//Used on DWSummary.xslt
//A find & replace function
function ReplaceAll( str, from, to ) 
{
	var idx = str.indexOf( from );


	while ( idx > -1 ) {
		str = str.replace( from, to ); 
		idx = str.indexOf( from );
	}

	return str;
}


var Overlay = {
	click_on_overlay_hide: true,
	show_loading_image: true,
	loading_image: "images/loading.gif",
	innerHTML: "",
	$: function(id){
		return document.getElementById(id);},
	init: function(){
		m_scroll_pos = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
		window.scrollTo(0, 0);
		document.body.style.overflow="hidden";
		var ol_div = document.createElement("div");
		ol_div.id = "overlay";
		ol_div.style.display = "none";
		ol_div.onclick = (this.click_on_overlay_hide)? Overlay.hide : null;
		if(this.show_loading_image){
			var l_text;
			if(document.getElementById("OverlayBox"))
				l_text = document.getElementById("OverlayBox");
			else
				l_text = document.createElement("span");
				
			if(this.innerHTML == "")
				this.innerHTML = "Please wait...";
			l_text.innerHTML = "<div style='background-color:white; padding:15px; height:100%; overflow:auto'>" + this.innerHTML + "</div>";
			l_text.id = "OverlayBox";
			l_text.style.position = "absolute";

			l_text.style.top = ((((window.innerHeight)? window.innerHeight : document.body.clientHeight) - (100)) / 2) + "px";
			l_text.style.left = ((((window.innerWidth)? window.innerWidth : document.body.clientWidth) - (400)) / 2) + "px";
			
			document.body.appendChild(l_text);
			}
		document.body.appendChild(ol_div);
		},
	show: function(){
		if(this.$("overlay")){
			this.$("overlay").style.display = "";
			document.getElementById("OverlayBox").style.display = "";
			}
		},
	hide: function(){
		if(Overlay.$("overlay")){
			document.body.style.overflow="";
			window.scrollTo(0, m_scroll_pos);
			Overlay.$("overlay").style.display = "none";
			document.getElementById("OverlayBox").style.display = "none";
			Overlay.OnHide();
			}
		},
	OnHide: function(){}
	};