var change_detected = 0;

/* Error Messages in English and Spanish */
var blank_message_english = "You must answer all questions on this page to continue.\n\nClick the OK button to go to the first empty field.\n\nIf you do not have the information you need, please save & exit. You may resume\nyour session at a later time by entering your password.";
var blank_message_spanish = "Para continuar tiene que contestar todas las preguntas en esta página.\n\nHaga click en la tecla OK para llegar al primer campo vacío.\n\nSi no tiene la información que necesita, favor de almacenar y salir. Puede reanudar la sesión en otro momento al introducir su contraseña.";
var date_message_english = "The date information that you entered is not in the correct format.  Please enter \n the date in the following format.  e.g. Enter 02/04/2007 for February 4, 2007 \n\n Click the OK button to go to the date field.";			
var date_message_spanish = "Introdujo la información de la fecha usando un formato incorrecto. Favor de introducir la fecha usando el siguiente formato: p. ej., introduzca 02/04/2007 por 4 de febrero de 2007.\n\nHaga click en la tecla OK para ir al campo de la fecha.";
var length_message_english = "The information that you provided exceeded allowed length for the field.\n\nClick the OK button to go to the field. Please provide a shorter response.";
var length_message_spanish = "La información que suministró rebasó la capacidad del campo.\n\nHaga click en la tecla OK para ir al campo. Favor de responder con más brevedad.";

function changed()
{
	change_detected=0;
}
			

// Faq javascript
function faq()
{
	var user = document.frm1.user.value;
	var lang_id = document.frm1.languageId.value;
	var appl_id = document.frm1.applicationId.value;
	var appl_name = document.frm1.appl_name.value;
	window.open('html/faq/'+appl_name+lang_id+'.html','faq','toolbar=yes,scrollbars=yes,resizable=no,width=600,height=500');
}

function getObjectById(objectId) {
  if (document.getElementById && document.getElementById(objectId)) {
    return document.getElementById(objectId);
  } else if (document.all && document.all(objectId)) {
    return document.all(objectId);
  } else {
    return false;
  }
}

function isVisible(qno)
{

     if (question_visibility[qno]==undefined)
     {
		  return true;
     }
     else if (question_visibility[qno])
     {
          return true;
     }
     else
     {
          return false;
     }
}


function isVisibleCheck(depend_qno, depend_cno)
{

    var f = eval("document.frm1."+"q"+depend_qno);
	if (f==undefined)
	{
		//It may be a radio or select, which have "_" in them
       	f = eval("document.frm1."+"q_"+depend_qno);
	}

	if (f==undefined)
    {
		alert("Element for "+depend_qno+" is undefined.");
        return true;
    }
	var checked = false;
	if (f.type == undefined) //radio input
	{
		 for (j=0;j<f.length;j++)			
		 {
			if (f[j].value == depend_cno&&f[j].checked)
			{
				checked = true;
			}
         }
    }
    else
    {
		 if (f.type=='checkbox')
         {
			checked = f.checked;
         }
 		 else if (f.value == depend_cno)
		 {
			checked = true;
		 }
    }
	//If it's not checked, then return false, as the element isn't visible
	return checked;
}


//This is where we will store the visibility settings
var question_visibility = new Array();

function updateVisibility()
{
   if(document.getElementsByTagName||document.all)
   {
      var table = getObjectById("question_table");  
	  if (!table) return;

      //So we can determine the hierarchy of hidden items
	  var qdepend_xref = new Array();

      var rows = table.getElementsByTagName("tr");  
      for(i = 0; i < rows.length; i++)
      {          
          var table_row = rows[i];
          var id = table_row.id;
          if (id.indexOf("conditional_question_")==-1) continue;

 	      var qcno = id.substring(21).split("|");
		  var qno = qcno[0];
          var depend_qno = qcno[1];
          var depend_cno = qcno[2];
		  
          var f = eval("document.frm1."+"q"+depend_qno);
	      if (f==undefined)
	      {
		      //It may be a radio or select, which have "_" in them
       	      f = eval("document.frm1."+"q_"+depend_qno);
	      }
          
		  //If the parent element is hidden, then this one is too
          if (question_visibility[depend_qno]!=undefined&&question_visibility[depend_qno]==false)
          {
			  question_visibility[qno] = false;
          }
		  else //Check it normally
          {
		  	  question_visibility[qno] = isVisibleCheck(depend_qno, depend_cno);
          }
 	


	      if (!table_row.style) continue;
          if (question_visibility==undefined) continue;

		  if (isVisible(qno))
          {
         	  table_row.style.display = "";    
          }
		  else
          {
         	  table_row.style.display = "none";    
          }
      }
   }
}






//Generic Open Window function
function OpWin(url,width,height)
{
	window.open(url,'',"width=" + width + ",height=" + height + ",location=yes,scrollbars=yes,scrollbars=1,menubar=yes,toolbar=yes,resizable=yes,status=yes,top=0,left=1");
}
			
//Info Window Function
function infoWindow(id)
{
	var width=640;
	var height=500;
	var user = document.frm1.user.value;
	var lang_id = document.frm1.languageId.value;
	var appl_id = document.frm1.applicationId.value;
	window.open('Interview?user='+user+'&func=info_page&id='+id+'&languageId='+lang_id,'info'+id,"width=" + width + ",height=" + height + ",location=yes,scrollbars=yes,scrollbars=1,menubar=yes,toolbar=yes,resizable=yes,status=yes,top=0,left=1");
}
			
			
//Linkscript javascript
function linkscript(i)
{
	var file_root = "";
	var lang_id = document.frm1.languageId.value;
	switch(i)
	{
		case 0: file_root="parent_time/under_three";break;
		case 1: file_root="parent_time/three_to_five";break;
		case 2: file_root="parent_time/five_to_eighteen";break;
		case 3: file_root="parent_time/guidelines";break;
	}
	window.open("html/"+file_root+lang_id+".html","linkscript"+i,'toolbar=yes,scrollbars=yes,resizable=no,width=600,height=400')
}


// Handle the forward button
function Continue()
{
	document.frm1.directioncheck.value ='forward';
	if (main())
	{
		//document.frm1.show_section_review.value="true";
		document.frm1.method='post';
		document.frm1.action='Interview';
		document.frm1.submit();
	}
}

			
//Handle Jumps (random access with tabs)
function Jump2Page(i_no)
{
	if ((i_no+first_image-1)<=current_index)
	{
		document.frm1.directioncheck.value ='back';
	}
	else
	{
		document.frm1.directioncheck.value ='forward';
		if (!main()) return;
	}
	//document.frm1.show_section_review.value="false";
	document.frm1.jump.value = links[i_no+(first_image-1)];
	document.frm1.method='post';
	document.frm1.action='Interview';
	document.frm1.submit();
}


function jumpToPage(page_key, direction)
{
	document.frm1.directioncheck.value = direction;

	if (direction == "forward")
	{
		if (!main()){return;}
	}
	//document.frm1.show_section_review.value="false";
	document.frm1.jump.value = page_key;
	document.frm1.method='post';
	document.frm1.action='Interview';
	document.frm1.submit();
}


function sJump()
{
    var checkpoint_seq = 1*document.frm1.checkpoint_seq.value;
	var i_no = document.sjform.jumpselect.selectedIndex;

	if (i_no<=checkpoint_seq)
	{

		document.frm1.directioncheck.value ='back';
	}
	else
	{
		document.frm1.directioncheck.value ='forward';
		if (!main()) return false;
	}
	//document.frm1.show_section_review.value="false";
	document.frm1.jump.value = links[i_no+1];document.frm1.method='post';document.frm1.action='Interview';document.frm1.submit();
}
			
// Handle the Back button
function Back(review_page) 
{
	document.frm1.directioncheck.value ='back';
	//document.frm1.show_section_review.value="false";
	document.frm1.method='post';
	document.frm1.action='Interview';
	document.frm1.submit();
}



//Logout
function saveExit()
{
	document.frm1.directioncheck.value ='save';

	//if (main())
	//{
		document.frm1.method='post';
		document.frm1.action='Interview';
		document.frm1.submit();
	//}
}

			
// Date check Function
function CheckDate(field)
{
    field.value = field.value.replace(/\s/g,""); //trim whitespace
	if (field.value == "") return true;
    if (!isDate(field.value))
    {
		if (document.frm1.languageId.value == '1')
		{
        	alert(date_message_english);
		}
		else if (document.frm1.languageId.value == '2')
		{
        	alert(date_message_spanish);
		}
        field.focus();
        return false;
    }
    return true;
}

// Length check Function
function CheckLength(field,max_length)
{
	if (field.value == "") return true;

    if (field.value.length>max_length)
    {
		if (document.frm1.languageId.value == '1')
		{
        	alert(length_message_english);
		}
		else if (document.frm1.languageId.value == '2')
		{
        	alert(length_message_spanish);
		}
        field.focus();
        return false;
    }
    return true;
}

// Blank check Function
function CheckBlank(field)
{
    if (field.value == '')
    {
		if (document.frm1.languageId.value == '1')
		{
        	alert(blank_message_english);
		}
		else if (document.frm1.languageId.value == '2')
		{
        	alert(blank_message_spanish);
		}
        field.focus();
        return false;
    }
    return true;
}


//Blank radio box check
function CheckBlankRadio(field)
{
	var i;
	for (i=0;i<field.length;i++)
	{
		if (field[i].checked) return true; 
	}
	if (document.frm1.languageId.value == '1')
	{
        alert(blank_message_english);
	}
	else if (document.frm1.languageId.value == '2')
	{
        alert(blank_message_spanish);
	}
	field[0].focus();
	return false;
}

// Blank Select Box Check
function CheckBlankSelect(field)
{
	if (field.selectedIndex==0)
	{
		if (document.frm1.languageId.value == '1')
		{
        	alert(blank_message_english);
		}
		else if (document.frm1.languageId.value == '2')
		{
        	alert(blank_message_spanish);
		}
		field.focus();
		return false;
	}
	return true;
}


// Save and Exit
function saveexit()
{
	var user=document.frm1.user.value;
	var lang=document.frm1.languageId.value;
	document.location="Interview?func=logout&user="+user;
}


// Advance to next tab
function TabNext(obj,event,len,next_field) 
{
	var field_length=0;
	if (event == "down") 
	{
		field_length=obj.value.length;
	}
	else if (event == "up") 
	{
		if (obj.value.length != field_length) 
		{
			field_length=obj.value.length;
			if (field_length == len) 
			{
				eval("document.frm1."+next_field+".focus();");
			}
		}
	}
}


// Date validation Javascript
function isDate(date)
{
	x1 = date.indexOf("/");
	len1 = date.length;
	if(x1 == -1){return false;}
	
	month = date.substring(0,x1);
	if(isNaN(month)||(month <=0)||(month >12)){return false;}
	if(month.length == 1){month = "0"+ month;}
	dayx = date.substring(x1+1,len1);
	x2 = dayx.indexOf("/");
	len2 = dayx.length;
	day = dayx.substring(0,x2);
	tenday = day*10;
	day = tenday/10;
	if((day.length < 1)||(day.length > 2)||(isNaN(day))||(day <= 0)){return false;}
	year = dayx.substring(x2+1,len2);
	if ((year.length != 4 )){return false;}
	if((isNaN(year))||(year <= 0)||(year >9999)){return false;}
	if(year%100 == 0 )
	{
		if(year%400 != 0 )
		{
			if((day >28)&&(month == 2)) return false;
		}
	}
			
	switch (month) 
	{
		case "01" : if(day >31) return false;
							else break;
		case "02" :  if((year%4 == 0)||(year%100 == 0)){
							if(day >29)return false;
							else break;
							}
							else{
							if(day >28)return false;
							else break;
							}
		case "03" :if(day >31)return false;
							else break;
		case "04" :if(day >30)return false;
							else break;
		case "05" :if(day >31)return false;
							else break;
		case "06" :if(day >30)return false;
							else break;
		case "07" :if(day >31)return false;
							else break;
		case "08" :if(day >31)return false;
							else break;
		case "09" :if(day >30)return false;
							else break;
		case "10" :if(day >31)return false;
							else break;
		case "11": if(day >30)return false;
							else break;
		case "12" :if(day >31)return false;
							else break;
		default : return false;
	}
	return true
} 








//Money functions
function moneyString(num) 
{
   num = numVal(""+num);
   num = num.toString().replace(/\$|\,/g,'');

   if(isNaN(num)) num = "0";
  

   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
   cents = "0" + cents;
   for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
   num = num.substring(0,num.length-(4*i+3))+','+
   num.substring(num.length-(4*i+3));
   return (((sign)?'':'-') + num + '.' + cents);
}



function round2places(n)
{
  return Math.round(n*100)/100;
}

function numReplace(f)
{
   var val = round2places(numVal(f.value));
   if (val==0) 
   {
      f.value = "";
   }
   else
   {
      f.value = val;
   }
   return val;
}

function numVal(nstring)
{
  
  var n="";
  //Make sure there are no E/e characters
  for (var i=0;i<nstring.length;i++)
  {
     if (nstring.charAt(i) != "e"&&nstring.charAt(i) != "E") n+=nstring.charAt(i);
  }
  if (!isNaN(n)) return 1*n;

  //Break the number on the first decimal point into
  //a int part and a float part    
  var intpart = "";
  var floatpart = "";
  if (n.indexOf('.')!=-1)
  {
     for (var i=0;i<n.indexOf('.');i++) intpart+=n.charAt(i);
     if ((n.length-1)>n.indexOf('.'))
     {
         for (var i=(n.indexOf('.')+1); i<n.length;i++) floatpart+=n.charAt(i);
     }
  }
  else
  {
	 intpart = n;
  }

  //remove all non integer characters
  var newintpart="";
  for (var i=0;i<intpart.length;i++) 
  {
     if (!isNaN(intpart.charAt(i)))
	 {
        if (intpart.toString().charAt(i) == 'e'||intpart.toString().charAt(i) == 'e') alert("E");
		newintpart+=(intpart.charAt(i));
     }
  }
  var newfloatpart="";
  for (var i=0;i<floatpart.length;i++) 
  {
     if (!isNaN(floatpart.charAt(i))) newfloatpart+=(floatpart.charAt(i));
  }

  //Merge the intpart and floatpart
  var newnum = newintpart;
  if (newfloatpart.length>0) newnum+="."+newfloatpart;

  return (1*newnum);
}

//Used so that negative numbers convert to numbers in ()
function debitCreditDesignateString(s)
{
    if (s.indexOf("-")==0)
    {
 	   return "("+s+")";	
    }
    else
    {
       return s;
    }
}



/********
Functions for talking to the server
*********/
function divDynamicGetRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
  




























