var curQ = 0;
var lastQ = 0;
var prevQ = 0;
var skipQ = new Array();
var qListString = [];
var isAddHistory = true;

var hideSchoolLogoDesc = false;
var useInlineErrorMessages = false;
var useSeperateMatchAndPII = false;
var errors =[];
var messages = [];
window.formFamily = "DegreesInfo";

var checkQueryString = window.location.search;
var areaOfStudyToSelect ='';
var warnedUserAboutProgram = false;
var ajaxFormSubmitted = false;
var templateStyle = '001';
var enableOCC = false;
var isAskEnterDayPhone = false;
var isAskEnterEvePhone = true; // set to true so that the dialog box requesting eve phone doesn't show up

var noSchoolSelectionBlock = false;

//Question field and value array use to resolve issue with browser reloading.
var defaultFieldNameValueArray = new Array();
var isSubmitFired = false;
var isEmailRemarketing = false;

//window.dhtmlHistoryDisabled = true; don't need to define, can be defined in the form or in the html

window.v12CommonQuestions = ["DDI_TITLE", "FIRSTNAME_01", "LASTNAME_01"];
window.v12PostQuestions = ["ADDRESS1_01", "CITY_01", "STATE_01", "ZIP_01"];
window.v12EmailQuestion = "EMAIL_01";

var selectedProgramNames = {};

function resizeDisplayWindow(){
  var screenWidth = screen.availWidth;
  var screenHeight = screen.availHeight;
  if(screenWidth <=0) {
      screenWidth = 800;
  }
  if(screenHeight <=0) {
      screenHeight = 600;
  }
  window.moveTo(0,0);
  window.resizeTo(screenWidth-10,screenHeight-10);
  if(window.focus) {
    window.focus();
  }
}

if(checkQueryString.indexOf("resizeDisplay=true")>=0) {
  resizeDisplayWindow();
}

//show q=shownQ or such group, hide q=hiddenQ or such group
function showHideQ(shownQ, hiddenQ) {
  if (window.qListGroups) {
    var qListStringGroup = window.qListGroups[hiddenQ];
    if (qListStringGroup) {
      for (var j=0;j<qListStringGroup.length;++j) {
        //alert("hide: " + qListStringGroup[j]);
        hide(qListStringGroup[j]);
      }
    }
    qListStringGroup = window.qListGroups[shownQ];
    if (qListStringGroup) {
      for (var j=0;j<qListStringGroup.length;++j) {
        //alert("show: " + qListStringGroup[j]);
    	show(qListStringGroup[j]);
      }
    }
    
  } 
  else {
     var hiddenField = qListString[hiddenQ];
     if (hiddenField) {
       hide(hiddenField);
     }
     var shownField = qListString[shownQ];
     if (shownField) {
       show(shownField);
     }
  }
}
function showNextQ(field) {
   var isSubmitPage = true;
  
   if (window.qListGroups) {
      if (curQ < window.qListGroups.length) {
        var qListStringGroup = window.qListGroups[curQ];
        if (qListStringGroup) { 
          for (var i=0;i<qListStringGroup.length;++i) {
//            field = window.document.form1.elements[qListStringGroup[i]];
            //alert("check field: " + field.name + " for: " + qListStringGroup[i]);
              if(!validateGroupElement(qListStringGroup[i])) {
                return false;  
              }
           }
           if (curQ < window.qListGroups.length - 1) {
        	   prevQ = curQ;
        	   lastQ = curQ;
        	   curQ = curQ + 1;
        	   showHideQ(curQ, lastQ);
        	   addHistory(curQ);
        	   isSubmitPage = false;
           }
        }
        else {
          isSubmitPage = false;
        }
      }
    }
    else {
      if(field && !validate(field)) {
        return;
      }
      
      prevQ = curQ;
      lastQ = curQ;
      curQ++;

      if(curQ<qListString.length) {
        showHideQ(curQ, lastQ); 
 
        addHistory(curQ);
        isSubmitPage = false;
      }
    }
    
    if (isSubmitPage) {
      finalize();
      submitForm();
    }
}

function validateGroupElement(groupElement) {
    var fieldsInDiv = getFieldsWithinDiv(groupElement);
    if(fieldsInDiv && fieldsInDiv.length > 0) {
        var field = getFormField(fieldsInDiv[0].name);
        if(field && !validate(field)) {
          return false;
         }
    }
    return true;
}

function finalize() {
    var highestEd = window.document.form1.DDI_EDUCATION_01;
    if(highestEd != undefined && highestEd != null && highestEd.options[highestEd.selectedIndex].value == 'none') {
        highestEd.options[highestEd.selectedIndex].disabled = false;
    }
}

function adchemyBack() {
  if (!window.dhtmlHistoryDisabled) {
    history.back();
  } else {
    displayPreviousQ();
  }
}

function adchemyForward() {
  if (!window.dhtmlHistoryDisabled) {
    history.forward();
  } else if (curQ < prevQ) {// It can only support single forward
    displayNextQ();
  }
}

function showPreviousQ(field) {
    if(curQ == 0) {
    alert("Already at beginning of form");
        return;
    }

    showHideQ(lastQ, curQ);
    
    prevQ = curQ;
    curQ = lastQ;
    lastQ = lastQ - 1;
    
    addHistory(curQ);
    
    //Reset if: 1 - we don't deal with grouped questions
    // 2 - we have a group consisting of a single question
    if (!window.qListGroups || window.qListGroups[curQ].length == 1) {
      resetFieldValue();
    }
}

function validate(field) {
    if (formSubmitted == true) {
        //don't validate fields if we submit a form by form1.submit() method
        return true;
    }
    if(compareFields(field, window.document.form1.DDI_AOS_01)) {
        return validate_DDI_AOS_01();
    } else if(compareFields(field, window.document.form1.DDI_SUB_AOS_01)) {
    	return validate_DDI_SUB_AOS_01();
    } else if(field==window.document.form1.DDI_AGE_01) {
        return validate_DDI_AGE_01();
    } else if(field==window.document.form1.DDI_GRADYEAR_01) {
        return validate_DDI_GRADYEAR_01();
    } else if(field==window.document.form1.DDI_EDUCATION_01) {
        return validate_DDI_EDUCATION_01();
    } else if(field==window.document.form1.DDI_START_PERIOD_01) {
        return validate_DDI_START_PERIOD_01();
    } else if(field==window.document.form1.COUNTRY_01) {
        return validate_DDI_COUNTRY_01();
    } else if(field==window.document.form1.USCITIZEN_01) {
        return validate_DDI_USCITIZEN_01();
    } else if(field==window.document.form1.DDI_MILITARYAFFILIATE_01) {
        return validate_DDI_MILITARYAFFILIATE_01();
    } else if(field==window.document.form1.DDI_MILITARYBRANCH_01) {
        return validate_DDI_MILITARYBRANCH_01();
    } else if (compareFields(field, window.document.form1.ZIP_01)) {
        return validate_ZIP_01(window.document.form1);
    } else if(compareFields(field, window.document.form1.EMAIL_01) && isEmailVisible()) {
        var isValid = true;
        if (!window.qListGroups) {
          isValid = validate_ZIP_01(window.document.form1);
        }
        if (isValid) {
          isValid = validate_EMAIL_01(window.document.form1);
        }
        return isValid;
    } else if(field==window.document.form1.DDI_EARN_YEARLY_01) {
        return validate_DDI_EARN_YEARLY_01();
    } else if(compareFields(field, window.document.form1.DDI_DEGREELEVEL_01)) {
        return validate_DDI_DEGREELEVEL_01();
    } else if(field==window.document.form1.DDI_CREDIT_01) {
        return validate_DDI_CREDIT_01();
    } else if(field==window.document.form1.DDI_MOTIVATIONAL_01) {
        return validate_DDI_MOTIVATIONAL_01();
    }

    return true;
}

function compareFields(givenField, expectedField) {
	if((givenField == expectedField) || 
			((givenField && expectedField && givenField.length == expectedField.length) && 
			(givenField[0] && expectedField[0] && givenField[0].name == expectedField[0].name))){
		return true;
	}
	return false;
}

function hideAll() {
    i=0;
    while(i<qListString.length) {
        hide(qListString[i]);
        i++;
    }
}

function associatesOrGreater() {
  if(window.document.form1 && window.document.form1.DDI_ASSOCIATESORGREATER && window.document.form1.DDI_ASSOCIATESORGREATER.value == 'true') {
    return true;
  } else {
    return false;
  }
}

function filterAlreadySelected() {
  if(window.document.form1.MATCH_FILTERS_SELECTED) {
    if(window.document.form1.MATCH_FILTERS_SELECTED.value == 'true') {
      return true;
    }
  }
  return false;
}

function isKeiserBSN(school,field) {
    if(school == 'keiser') {
      if(field.selectedIndex >=0 && field.options[field.selectedIndex].text == 'Registered Nurse to BS in Nursing') {
        return true;
      }
    }
    return false;
}

function isPhoenixOnlineBSN(school,field) {
    if(school == 'phoenixonline') {
      if(field.selectedIndex >=0 && field.options[field.selectedIndex].text == 'RN to B.S. in Nursing') {
        return true;
      }
    }
    return false;
}

function isSouthUniversityBSN(school,field) {
    if(school == 'southuniversity') {
      if(field.selectedIndex >=0 && field.options[field.selectedIndex].text == 'B.S. Degree Completion Program (RN to BSN)') {
        return true;
      }
    }
    return false;
}

function isAIUSounthFloridaBSN(school,field) {
    if(school == 'aiucampus-southflorida') {
      if(field.selectedIndex >=0 && field.options[field.selectedIndex].text == 'Bachelor of Science in Nursing Management (BSNM)') {
        return true;
      }
    }
    return false;
}

function filterSelected(school) {
    var field = document.getElementById("element_MATCH_"+school);
    var value = getFieldValueLB(field)
    displaySchools(school);
    showOptionalQuestions();
    
    setSelectedProgramNames(field);
}

function setSelectedProgramNames(field) {
	var key1 = getFieldValueLB(field);
	var value = getFieldTextLB(field);
	
	if (isNotEmpty(key1) && isNotEmpty(value)) {

		selectedProgramNames[key1] = value;
		selectedProgramsField = document.getElementById("SELECTED_PROGRAM_NAMES");

		if (selectedProgramsField) {
			var values = "";
			
			for (var key2 in selectedProgramNames) {
				if (values.length == 0) {
					values = key2 + "|" + selectedProgramNames[key2];
				} else {
					values += "||" + key2 + "|" + selectedProgramNames[key2];
				} 
			}
			
			setFieldValue(selectedProgramsField, values);
		}
	}
}

function showAccreditation() {
    if(document.getElementById("AIU_ACCREDITATION") == null) {
        return;
    }
    hide("AIU_ACCREDITATION");
    var schoolList = readSchoolList();
    for(i=0;i<schoolList.length;i++) {
        var school = schoolList[i];
        if(school != null && school.length >= 3 && (school == 'aiu' || school.substring(0, 3) == 'aiu')) {
            show("AIU_ACCREDITATION");
            return;
        }
    }
}

function showOptionalQuestions() {
    hideAllOptional();
    var schoolList = readSchoolList();
    for(i=0;i<schoolList.length;i++) {
      field = document.getElementById("element_MATCH_"+schoolList[i]);
      if (field) {
        value = getFieldValueLB(field)
        if(validateIsRequired(value)) {
            showOptionalQuestionsForSchool(schoolList[i]);
            showOptionalQuestionsForProgram(schoolList[i],field);
            showOptionalQuestionsForAreaCode(schoolList[i],field);
        }
      }
    }
}

// Server-side maps use '<school>:<program-hash>', whereas the
// client-side uses '<school>:<field>' where field is the option.value for
// the program.
function showOptionalQuestionsForProgram(school,field) {
  
  if(school != null && field != null) {
      var value = getFieldValueLB(field);
      var key = school+":"+value;
      var questions = typeof(programMap)!='undefined' ? programMap[key] : null;
      if(questions != null && questions.length > 0) {
        for(var index=0;index<questions.length;index++) {
            show("optQ_"+questions[index]);
        }
      }
  }
}

function showOptionalQuestionsForAreaCode(school,field) {
  if(typeof(school)!='undefined' && typeof(areaCodeMap)!='undefined') {
	var questions = areaCodeMap[school];
	if(questions != null && questions.length > 0) {
	  for(var index=0;index<questions.length;index++) {
	    show("optQ_"+questions[index]);
	  }
    }
  }
}

function showOptionalQuestionsForSchool(school) {
  if(typeof(school)!='undefined' && typeof(schoolMap)!='undefined') {
    var questions = schoolMap[school];
    if(questions != null && questions.length > 0) {
      for(var index=0;index<questions.length;index++) {
        show("optQ_"+questions[index]);
      }
    }
    highlightSchool(school);
  }
}

function highlightSchool(school) {
  var foundSchool = false;
  var foundNextSchool = false;
  var schoolList = readSchoolList();
  for(i=0;i<schoolList.length;i++) {
    if(schoolList[i] == school) {
      foundSchool = true;
      field = document.getElementById("element_MATCH_"+schoolList[i]);
      value = getFieldValueLB(field);
      if(!validateIsRequired(value)) {
        document.getElementById('cell_'+schoolList[i]).className = "rowOn";
        foundNextSchool = true;
        field.focus();
      } else {
        document.getElementById('cell_'+schoolList[i]).className = "rowOff";
        for(var z=i;z<schoolList.length;z++) {
          field2 = document.getElementById("element_MATCH_"+schoolList[z]);
          value2 = getFieldValueLB(field2);
          if(!validateIsRequired(value2) && !foundNextSchool) {
            document.getElementById('cell_'+schoolList[z]).className = "rowOn";
            foundNextSchool=true;
            field2.focus();
          } else {
            document.getElementById('cell_'+schoolList[z]).className = "rowOff";
          }
        }
        for(var z=0;z<i;z++) {
          field2 = document.getElementById("element_MATCH_"+schoolList[z]);
          value2 = getFieldValueLB(field2);
          if(!validateIsRequired(value2) && !foundNextSchool) {
            document.getElementById('cell_'+schoolList[z]).className = "rowOn";
            foundNextSchool=true;
            field2.focus();
          } else {
            document.getElementById('cell_'+schoolList[z]).className = "rowOff";
          }
        }
      }
    return;
    }
  }
}

function displaySchools(school) {
    var schoolList = readSchoolList();
    if (schoolList) {
      for (i = 0; i < schoolList.length; i++) {
        var schoolSection = document.getElementById("tr_"+schoolList[i]);
        if (schoolSection) {
          if (!noSchoolSelectionBlock) {
            schoolSection.style.display = "block";
          }
          if (schoolList[i] == school) {
            var nextSchoolIdx = i + 1;
            if (nextSchoolIdx < schoolList.length) {
                var nextSchoolSection = document.getElementById("tr_"+schoolList[nextSchoolIdx]);
                if (!noSchoolSelectionBlock) {
                    nextSchoolSection.style.display = "block";
                }
            }
            return;
          }
        }
      }
    }
}

function displayAllSchools() {
    var schoolList = readSchoolList();
    if (schoolList) {
      for (i = 0; i < schoolList.length; i++) {
        var schoolSection = document.getElementById("tr_"+schoolList[i]);
        if (schoolSection) {
          if (!noSchoolSelectionBlock) {
            schoolSection.style.display = "block";
          }
        }
      }
    }
}

function validate_DDI_USCITIZEN_01() {
    optField = window.document.form1.USCITIZEN_01;
    optValue = getFieldValueRB(optField);
    if(!validateIsRequired(optValue)) {
      return alertError(window.document.form1.USCITIZEN_01[0], "You must indicate whether you are a U.S. Citizen.");
    } else {
      return validate_DDI_COUNTRY_01();
    }
}


function validate_DDI_MILITARYAFFILIATE_01() {
    var optField = window.document.form1.DDI_MILITARYAFFILIATE_01;
    var optValue = getFieldValueRB(optField);
    if(!validateIsRequired(optValue)) {
      return alertError(window.document.form1.DDI_MILITARYAFFILIATE_01[0], "Please indicate if you are affiliated with the US Military.");
    }
    return true;
}


function isRematchPage() {
    if (document.getElementById('Rematch') && document.getElementById("Rematch").value == 'true') {
        return true;
    }
    
    return false;
}

function isCallCenterPage() {
    if(document.getElementById("callCenter") && document.getElementById("callCenter").value == 'true') {
        return true;
    }
    
    return false;
}

function initRematch() {

  if (isRematchPage()) {
    var piiTable = document.getElementById("PIITable");
    if (piiTable) {
      piiTable.style.display="none";
    }
    var matchImageObj = document.getElementById("matchImage");
    if (matchImageObj) {
      matchImageObj.style.display = "none";
    }
    matchImageObj = document.getElementById("match");
    if (matchImageObj) {
      matchImageObj.style.display = "none";
    }
    matchImageObj = document.getElementById("match-img");
    if (matchImageObj) {
      matchImageObj.style.display = "none";
    }
  }
  
}

function initDefaults() {
    if(associatesOrGreater()) {
        var field = window.document.form1.DDI_NURSEORASSOCIATES_01;
        if(field != undefined && field != null)
            selectValueRB(field,'YES');
    }
    if (window.document.form1.Rematch) {
      initRematch();
    }
}

function initHistory() {
  try {
    //initialize our DHTML history
    dhtmlHistory.initialize();

    //subscribe to DHTML history change events
    dhtmlHistory.addListener(historyChange);
    //alert("isSafari: " + dhtmlHistory.isSafari + " isIe: " + dhtmlHistory.isIE + " isOP: " + dhtmlHistory.isOpera + " isKOnq: " + dhtmlHistory.isKonquerer + " isGecko: " + dhtmlHistory.isGecko);

    if (dhtmlHistory.isSafari) {
      window.dhtmlHistoryDisabled = true;
    } else {
      if (dhtmlHistory.isFirstLoad()) {
        dhtmlHistory.add("HQ0", "0");
      }
    }
  } catch(e) {
    //alert("exception while init");
    window.dhtmlHistoryDisabled = true;
    try {
         var reasonMes = "reason: " + reason + "problem: " + e.name + ": ";
         if (e.message) {
           reasonMes += " message: " + e.message;
         }
         if (e.description) {
           reasonMes += " desc: " + e.description;
         }
         if (e.lineNumber) {
           reasonMes += " line number: " + e.lineNumber;
         }

         reasonMes = "can't initialize dhtmlHistory: " + ", " + reasonMes;
         
         params = "type=jsProblem&field=dhtmlHistory" + "&reason=" + encodeURIComponent(reasonMes);
         
         AjaxObject.getReq().open("POST", ValidationTracker.reportedUrl, false); 
         AjaxObject.getReq().setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
         AjaxObject.getReq().setRequestHeader("Cache-Control", "no-cache"); 
    
         AjaxObject.getReq().send(params);
         
       } catch(e) {}
  }
}

function addHistory(addQ) {
    if (!window.dhtmlHistoryDisabled && isAddHistory) {
        dhtmlHistory.add("HQ" + addQ, addQ);
    }
}

function historyChange(newLocation,historyData) {
  if (window.dhtmlHistoryDisabled) {
    return;
  }
  
  //alert("history change: " + newLocation + " historyData: " + historyData + " curQ: " + curQ);
  var newL = null;
  if(historyData && newLocation && newLocation!=""){
    newL=parseInt(newLocation.substring(2));
    if(!isNaN(newL)) {
      if (newL > curQ) { //going forward, doesn't do anything
          //alert("going forward");
          if (window.inReset) {//reset function was called
            var length4CurQ = qListString.length;
            if (window.qListGroups) {
              length4CurQ = window.qListGroups.length;
            }
            var tempCurQ = curQ;
            while (curQ < newL && curQ < length4CurQ) {
              displayNextQ(window.document.form1.Submit);
              if (curQ <= tempCurQ) { //if for some reason we don't increase curQ
                tempCurQ = curQ;
                curQ++;
              }
            }
            window.inReset = false;
          }
          else {
            dhtmlHistory.add("HQ"+ curQ, (curQ+1)); 
            history.back();
          }
      } 
      else {//going back
        //alert("going back");
        while (curQ > newL && curQ >0) {
          displayPreviousQ();
        }
      }
    }
  }
  if (null == newL || isNaN(newL)) {
    while (curQ > 0) {
      displayPreviousQ();
    }
  }

}

function removeCountryQuestionFromSeamlessAndGroupArray() {
	if(qListString) {
	  for(var i=0; i<qListString.length;i++ )
      { 
        if(qListString[i]=="div_COUNTRY_01") {
            qListString.splice(i,1);
        }
      }
	}
	if(window.qListGroups) {
	  for(var i=0; i<window.qListGroups.length;i++ )
      {
      	var questionsInGroup = window.qListGroups[i];
      	for(var z=0;z<questionsInGroup.length;z++) {
      		if(questionsInGroup[z]=="div_COUNTRY_01") {
      			if(questionsInGroup.length==1) {
      				qListGroups.splice(i,1);
      			} else {
                	questionsInGroup.splice(z,1);
      			}
            }
      	}
      }	
	}
}

function initFirstPage() {
  removeCountryQuestionFromSeamlessAndGroupArray();
  initHistory();
  
  initFunctionWasCalled();

  initializeGroups(window.qListGroups);  
  
  var areaOfStudy = queryString("_AOS");
  if(validateIsRequired(areaOfStudy)) {
    selectValueRB(window.document.form1.DDI_AOS_01,areaOfStudy);
    return true;
  } else {
    var occupation = queryString("_OCC");
    if(validateIsRequired(occupation)) {
      areaOfStudy = getAreaOfStudyByOccupation(occupation);
      if(validateIsRequired(areaOfStudy)) {
        selectValueRB(window.document.form1.DDI_AOS_01,areaOfStudy);
        return true;
      }
    }
    if(validateIsRequired(areaOfStudyToSelect)) {
      selectValueRB(window.document.form1.DDI_AOS_01,areaOfStudyToSelect);
      return true;
    }
  }
}

function initSecondPage() {
    hideEmailField("2");
    hideZipCodeField();
  initFunctionWasCalled();
}

var _initFunctionWasCalled=false;
function initFunctionWasCalled() {
  _initFunctionWasCalled=true;
}

function getAreaOfStudyByOccupation(occupation) {
  if(occupation == "accountant") {
      return "business";
  } else if (occupation == "bounty hunter") {
      return "criminal justice";
  } else if (occupation == "chef") {
      return "culinary arts";
  } else if (occupation == "counselor") {
      return "health and human services";
  } else if (occupation == "cpa") {
      return "business";
  } else if (occupation == "criminal investigator") {
      return "criminal justice";
  } else if (occupation == "database administrator") {
      return "computer science";
  } else if (occupation == "detective") {
      return "criminal justice";
  } else if (occupation == "developer") {
      return "computer science";
  } else if (occupation == "engineer") {
      return "computer science";
  } else if (occupation == "financier") {
      return "business";
  } else if (occupation == "graphic designer") {
      return "graphic design";
  } else if (occupation == "healthcare manager") {
      return "health and human services";
  } else if (occupation == "HR officer") {
      return "business";
  } else if (occupation == "manager") {
      return "business";
  } else if (occupation == "marketer") {
      return "business";
  } else if (occupation == "network specialist") {
      return "computer science";
  } else if (occupation == "paralegal") {
      return "criminal justice";
  } else if (occupation == "patient advocate") {
      return "health and human services";
  } else if (occupation == "police") {
      return "criminal justice";
  } else if (occupation == "project manager") {
      return "business";
  } else if (occupation == "psychologist") {
      return "psychology";
  } else if (occupation == "sales person") {
      return "business";
  } else if (occupation == "social worker") {
      return "health and human services";
  } else if (occupation == "software professional") {
      return "computer science";
  } else if (occupation == "teacher") {
      return "education";
  } else if (occupation == "therapist") {
      return "health and human services";
  } else if (occupation == "pr specialist") {
      return "general studies and communication";
  } else if (occupation == "author") {
      return "general studies and communication";
  } else if (occupation == "hotel manager") {
      return "hotel hospitality";
  } else {
      return "";
  }
}

function hideAllOptional() {
  try {//when optionalQuestionDivs is not declared
    for(var i=0;i<optionalQuestionDivs.length;i++) {
        hide(optionalQuestionDivs[i]);
    }
  } catch (e) {}
}

function writeInsideMatchImage() {
    var schoolList = readSchoolList();
    if(document.getElementById("matchImage") != null) {
        document.getElementById("matchImage").src = matchImageBase + schoolList.length+".gif";
    }
}

function readSchoolList() {
    if(window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS != undefined &&
      window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS != null)
        return window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS.value.split(",");
    else
        return new Array();
}

function resetSchoolList(schoolList) {
    if(window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS != undefined &&
      window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS != null) {
        return window.document.form1.DEGREES_INFO_MATCHED_SCHOOLS.value = schoolList;
    }
}

function warnSelectMorePrograms(fieldToShow, school, message) {
   warnedUserAboutProgram = true;
       
       alert(message);
       highlightSchool(school);
       
       try {
           DdiTracker.trackLink('ddiReminder');
       } catch(e) {}
       
       var sendingUrl = "/forms/form.jsp";
       try {
         AjaxObject.getReq().open("POST", sendingUrl, false); 
         AjaxObject.getReq().setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
         AjaxObject.getReq().setRequestHeader("Cache-Control", "no-cache"); 
        
         AjaxObject.getReq().send("AJAX_REMINDER=true&" + AjaxObject.getParams(window.document.form1));
       } catch(e) {}
   
   return false;
}

function validateOptInput(optInput) {
    if(optInput[0].type == 'radio') {
        var value = getFieldValueRB(optInput);
        return validateIsRequired(value);
    }
    else if(optInput[0].type == 'text') {
        var value = getFieldValueTF(optInput[0]);
        return validateIsRequired(value);
    }
    else if(optInput[0].type == 'select-one') {
        var value = getFieldValueLB(optInput[0]);
        return validateIsRequired(value);
    }
    else {
        return true;
    }
}

function validate_OPT_QUESTIONS() {
    var schoolList = readSchoolList();
    var verifiedSchoolList = null;
    var alertField = null;
    var alertMessage = null;
    for(var i=0;i<schoolList.length;i++) {
        var school = schoolList[i];
        var validationFailed = false;
        var field = document.getElementById("element_MATCH_"+school);
        var program = getFieldValueLB(field);
        if(validateIsRequired(program)) {
            // this school has a program selected.
            var schoolQuestions = typeof(schoolMap)!='undefined' ? schoolMap[school] : null;
            var schoolQCount = schoolQuestions == null?0:schoolQuestions.length;
            var areaCodeQuestions = typeof(areaCodeMap)!='undefined' ? areaCodeMap[school] : null;
            var areaCodeQCount = areaCodeQuestions == null?0:areaCodeQuestions.length;
            var key = school+":"+program;
            var programQuestions = typeof(programMap)!='undefined' ? programMap[key] : null;
            var programQCount = programQuestions==null?0:programQuestions.length;
            for(var j=0;j<schoolQCount;j++){
                var optInput = window.document.getElementsByName(schoolQuestions[j]);
                if(!validateOptInput(optInput)) {
                    if (alertField == null) {
                        alertField = field;
                        alertMessage = optQuestionIsRequired[schoolQuestions[j]];
                    }
                    validationFailed = true;
                }
            }
            for(var j=0;j<areaCodeQCount;j++){
                var optInput = window.document.getElementsByName(areaCodeQuestions[j]);
                if(!validateOptInput(optInput)) {
                    if (alertField == null) {
                        alertField = field;
                        alertMessage = optQuestionIsRequired[areaCodeQuestions[j]];
                    }
                    validationFailed = true;
                }
            }            
            for(var k=0;k<programQCount;k++){
                var optInput = window.document.getElementsByName(programQuestions[k]);
                if(!validateOptInput(optInput)) {
                     if (alertField == null) {
                        alertField = field;
                        alertMessage = optQuestionIsRequired[programQuestions[k]];
                    }
                    validationFailed = true;
                }
            }
        }
       
        if (!validationFailed) {
            if (verifiedSchoolList == null) {
                verifiedSchoolList = school;
            } else {
                verifiedSchoolList += "," + school;
            }
        }
    }

    if (alertField != null && alertMessage != null) {
        alertError(alertField, alertMessage);
        ajaxFormSubmit(schoolList, verifiedSchoolList);
        return false;
    }

    return true;
}

function ajaxFormSubmit(schoolList, verifiedSchoolList) {
   if (ajaxFormSubmitted || verifiedSchoolList == null) {
     return;
   }

  resetSchoolList(verifiedSchoolList);      

   var sendingUrl = "/forms/form.jsp";
   try {
     AjaxObject.getReq().open("POST", sendingUrl, false); 
     AjaxObject.getReq().setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     AjaxObject.getReq().setRequestHeader("Cache-Control", "no-cache"); 
    
     AjaxObject.getReq().send("AJAX_FORM_SUBMIT=true&" + AjaxObject.getParams(window.document.form1));
   } catch(e) {}

   resetSchoolList(schoolList);   

   ajaxFormSubmitted = true;
}

function validate_FILTERMATCHLIST() {
    var selectedProgramCount=0;
    if(filterAlreadySelected()) {
      return true;
    }
    var schoolList = readSchoolList();
    var fieldToShow = 0;
    for(i=0;i<schoolList.length;i++) {
        field = document.getElementById("element_MATCH_"+schoolList[i]);
        value = getFieldValueLB(field)
        if(validateIsRequired(value)) {
            selectedProgramCount++;
        } else if(fieldToShow == 0) {
            fieldToShow = i;
        }
    }
    
    var locationField = window.document.form1.PROGRAM_LOCATION_01;
    if(locationField) {
    	if(locationField.selectedIndex == 0) {
    		alertError("PROGRAM_LOCATION_01", "Please select Preferred Location.");
    		return false;
    	}
    }
    
    var isRematch = isRematchPage();
    if(selectedProgramCount == 0 && (!isRematch || (isRematch && isCallCenterPage()))) {
      warnedUserAboutProgram = true;
      var isValid = alertError(document.getElementById("element_MATCH_"+schoolList[0]), "Please select at least 1 Program." );
      highlightSchool(schoolList[0]);
      return isValid;
    } else {
      return true;
    }
}

function validate_FILTERMATCHLISTWarn() {
    var selectedProgramCount=0;
    if(filterAlreadySelected()) {
      return true;
    }
   // if we have seperate Match & PII, then reminder is not needed as it could appear on the wrong page
   if(typeof(setSeperateMatchAndPII) != 'undefined' && setSeperateMatchAndPII==true){
      return true;
   }
    var schoolList = readSchoolList();
    var fieldToShow = 0;
    for(i=0;i<schoolList.length;i++) {
        field = document.getElementById("element_MATCH_"+schoolList[i]);
        value = getFieldValueLB(field)
        if(validateIsRequired(value)) {
            selectedProgramCount++;
        } else if(fieldToShow == 0) {
            fieldToShow = i;
        }
    } 
    
    if(warnedUserAboutProgram != true && ((selectedProgramCount == 1 && schoolList.length > 1) || (selectedProgramCount == 2 && schoolList.length >= 4))) {
      return warnSelectMorePrograms(document.getElementById("element_MATCH_"+schoolList[fieldToShow]), schoolList[fieldToShow], 
        "You have more options available and can select a program for each matching school.");
    } else {
      return true;
    }
}

function validate_DDI_CREDIT_01() {
    field = window.document.form1.DDI_CREDIT_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
      return alertError(field, "Please select your credit profile." );
    }
    return true;
}

function validate_DDI_MOTIVATIONAL_01() {
    field = window.document.form1.DDI_MOTIVATIONAL_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
      return alertError(field, "Please select why you want your degree." );
    }
    return true;
}

function validate_DDI_DEGREELEVEL_01() {
    var cbField = window.document.form1.DDI_DEGREELEVEL_01;
    var isFind = false;
    for(var i=0;i<cbField.length;i++) {
        if(cbField[i].checked) {
            isFind = true;
        }
    }
    if (!isFind) {
        alertError(window.document.form1.DDI_DEGREELEVEL_01[0], "Please select a degree level you are interested in");
        return false;
    }
    return true;

}

function validate_DDI_AOS_01() {
	
	var formRef = window.document.form1;
	var isFind = false;
	
	if(formRef.DDI_AOS_01_DISPLAY) {
		
		var aosDisplay = getAosDisplayType(false);
		
		if(aosDisplay == "RADIO") {
			isFind = validate_DDI_AOS_FIELD_RADIO(formRef.DDI_AOS_01_RADIO);
		} else if(aosDisplay == "DROPDOWN") {
			isFind = validate_DDI_AOS_FIELD_DROPDOWN(formRef.DDI_AOS_01_DROPDOWN);
		} else {
			isFind = validate_DDI_AOS_FIELD_CHECKBOX(formRef.DDI_AOS_01);
		}	
	} else {
		isFind = validate_DDI_AOS_FIELD_CHECKBOX(formRef.DDI_AOS_01);
	}
	
	if (!isFind) {
      if(formRef.career_display_for_aos){
        alertError(formRef.career_display_for_aos, "Please select a Career of Interest"); // Added for LDG-65
      }else{
        alertError(formRef.DDI_AOS_01[0], "Please Select an Area of Study");
      }
      return false;
    }
    else {
     return true;
    }
}

function validate_DDI_SUB_AOS_01() {
	
	var formRef = window.document.form1;
	
	if(formRef.DDI_SUB_AOS_01_DISPLAY) {
		
		var subAosDisplayType = getSubAosDisplayType(false);
		
		if(subAosDisplayType == "HIDE") {
    		return true;
    	} else {
    		
    		var isFind = false;
    		
    		if(subAosDisplayType == "RADIO") {
    			isFind = validate_DDI_SUB_AOS_FIELD_RADIO(formRef.DDI_SUB_AOS_01_RADIO);
    		} else if(subAosDisplayType == "DROPDOWN") {
    			isFind = validate_DDI_SUB_AOS_FIELD_DROPDOWN(formRef.DDI_SUB_AOS_01_DROPDOWN);
    		} else if(subAosDisplayType == "CHECKBOX"){
    			isFind = validate_DDI_SUB_AOS_FIELD_CHECKBOX(formRef.DDI_SUB_AOS_01)
    		}
    		
    		if (!isFind) {
    			if(formRef.career_display_for_sub_aos){
    				alertError(formRef.career_display_for_sub_aos, "Please select a Sub-Career of Interest");
    			} else {
    				if(formRef.DDI_SUB_AOS_01) {
    					alertError(formRef.DDI_SUB_AOS_01, "Please Select a Concentration for each Subject Area");
    				} else {
    					alert("Please Select a Concentration for each Subject Area");
    				}
    			}
    			return false;
    	    } else {
    	    	return true;
    	    }
    	}
	}
	return true;
}

function validate_DDI_AOS_FIELD_CHECKBOX(cbField) {
	var isFind = false;
	if(cbField.value) {
		isFind = cbField.checked;
	} else {
		for(var i=0;i<cbField.length;i++) {
	        if(cbField[i].checked) {
	            isFind = true;
	            break;
	        }
	    }
	}
	return isFind;
}

function validate_DDI_AOS_FIELD_RADIO(radioField) {
	return isCBChecked(radioField);
}

function validate_DDI_AOS_FIELD_DROPDOWN(dropdownField) {
	var isFind = false;
	var aos = getFieldValueLB(dropdownField);
	return validateIsRequired(aos);
}

function validate_DDI_SUB_AOS_FIELD_CHECKBOX(cbField) {
	if (isHidden("div_DDI_SUB_AOS_CHECKBOX_innerdiv")) {
		return true;
	}
	
	var selectedAosValues = getAosFieldValue();	
	
	if (selectedAosValues && (selectedAosValues != "")) {
		var aosValues = selectedAosValues.split(",");
		
		for (var i = 0; i < aosValues.length; i++) {
			var singleSubAosCbField = document.getElementsByName("DDI_SUB_AOS_01_" + aosValues[i].replace(/ /g, "_"));
			
			if (singleSubAosCbField && (singleSubAosCbField.length > 0)) {
				if (!validate_DDI_AOS_FIELD_CHECKBOX(singleSubAosCbField)) {
					return false;
				}
			}
		}
	} else {
		return false;
	}
	
	collectSubAosValuesCheckbox();
	
	return true;
}
function validate_DDI_SUB_AOS_FIELD_RADIO(radioField) {
	if(isHidden("div_DDI_SUB_AOS_RADIO_innerdiv")) {
		return true;
	}
	var selectedAos = getAosFieldValue();
	var isValid = true;
	if(selectedAos && selectedAos != "") {
		var aosList = selectedAos.split(",");
		for(var i = 0; i < aosList.length; i++) {
			var singleSubAosRadioField = document.getElementsByName("DDI_SUB_AOS_01_RADIO_" + aosList[i].replace(/ /g,"_"));
			if(singleSubAosRadioField && singleSubAosRadioField.length > 0) {
				isValid = isValid && validate_DDI_AOS_FIELD_RADIO(singleSubAosRadioField);
			}
		}
	} else {
		isValid = false;
	}
	if(isValid) {
		collectSubAosValuesRadio();
	}
	return isValid;
}

function validate_DDI_SUB_AOS_FIELD_DROPDOWN(dropdownField) {
	if (isHidden("div_DDI_SUB_AOS_DROPDOWN_innerdiv")) {
		return true;
	}
	
	var selectedAosValues = getAosFieldValue();	
	
	if (selectedAosValues && (selectedAosValues != "")) {
		var aosValues = selectedAosValues.split(",");
		
		for (var i = 0; i < aosValues.length; i++) {
			var singleSubAosDropdownField = document.getElementsByName("DDI_SUB_AOS_01_DROPDOWN_" + aosValues[i].replace(/ /g, "_"));
			
			if (singleSubAosDropdownField && (singleSubAosDropdownField.length > 0)) {
				if (!validate_DDI_AOS_FIELD_DROPDOWN(singleSubAosDropdownField[0])) {
					return false;
				}
			}
		}
	} else {
		return false;
	}
	
	collectSubAosValuesDropdown();
	
	return true;
}


function getAosFieldValue(useSelectedValues) {
	
	var ddi_aos_field = null;
	var aosFieldValue = "";
	
	if(window.document.form1.DDI_AOS_01_DISPLAY) {
		
		var aosDisplayType = getAosDisplayType(useSelectedValues);
		
		if(aosDisplayType == "RADIO") {
			ddi_aos_field = window.document.form1.DDI_AOS_01_RADIO;
			aosFieldValue = getFieldValue(ddi_aos_field);
		} else if(aosDisplayType == "DROPDOWN") {
			ddi_aos_field = window.document.form1.DDI_AOS_01_DROPDOWN;
			aosFieldValue = getFieldValue(ddi_aos_field);
		} else { // checkbox
			ddi_aos_field = window.document.form1.DDI_AOS_01;
			aosFieldValue = getFieldValueCBWithSeparator(ddi_aos_field);
		}
	} else {
		ddi_aos_field = window.document.form1.DDI_AOS_01;
		aosFieldValue = getFieldValueCBWithSeparator(ddi_aos_field);
	}
	return aosFieldValue;
}

function collectSubAosValuesDropdown(useSelectedValues) {
	
	var selectedAosValues = getAosFieldValue(useSelectedValues);
	
	if (selectedAosValues && (selectedAosValues != "")) {
		var aosValues = selectedAosValues.split(",");
		var collectedSubAosValues = "";
		
		for (var i = 0; i < aosValues.length; i++) {
			var singleSubAosDropdownField = document.getElementsByName("DDI_SUB_AOS_01_DROPDOWN_" + aosValues[i].replace(/ /g, "_"));
		
			if (singleSubAosDropdownField && (singleSubAosDropdownField.length > 0)) {
				if (collectedSubAosValues != "") {
					collectedSubAosValues += ",";
				}
								
				collectedSubAosValues += getFieldValueLB(singleSubAosDropdownField[0]);
			}
		}
		
		setFieldValue(window.document.form1.DDI_SUB_AOS_01_DROPDOWN, collectedSubAosValues);
	}
}

function collectSubAosValuesRadio(useSelectedValues) {
	
	var selectedAos = getAosFieldValue(useSelectedValues);
	
	if(selectedAos && selectedAos != "") {
		var aosList = selectedAos.split(",");
		var collectedSubAosValues = "";
		for(var i = 0; i < aosList.length; i++) {
			var singleSubAosRadioField = document.getElementsByName("DDI_SUB_AOS_01_RADIO_" + aosList[i].replace(/ /g,"_"));
			if(singleSubAosRadioField && singleSubAosRadioField.length > 0) {
				if(collectedSubAosValues != "") {
					collectedSubAosValues += ",";
				}
				collectedSubAosValues += getFieldValueRB(singleSubAosRadioField);
			}
		}
		setFieldValue(window.document.form1.DDI_SUB_AOS_01_RADIO, collectedSubAosValues);
	}
}

function collectSubAosValuesCheckbox(useSelectedValues) {
	
	var selectedAosValues = getAosFieldValue(useSelectedValues);
	
	if (selectedAosValues && (selectedAosValues != "")) {
		var aosValues = selectedAosValues.split(",");
		var collectedSubAosValues = "";
		
		for (var i = 0; i < aosValues.length; i++) {
			var singleSubAosCheckboxField = document.getElementsByName("DDI_SUB_AOS_01_" + aosValues[i].replace(/ /g, "_"));
		
			if (singleSubAosCheckboxField && (singleSubAosCheckboxField.length > 0)) {
				if (collectedSubAosValues != "") {
					collectedSubAosValues += ",";
				}
								
				collectedSubAosValues += getFieldValueCBWithSeparator(singleSubAosCheckboxField);
			}
		}
		
		setFieldValue(window.document.form1.DDI_SUB_AOS_01, collectedSubAosValues);
	}
}

function validate_DDI_AGE_01() {
    field = window.document.form1.DDI_AGE_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
      return alertError(field, "Please indicate your age." );
    }
    return true;
}

function validate_DDI_GRADYEAR_01() {
    field = window.document.form1.DDI_GRADYEAR_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please indicate the year you graduated." );
    }
    if ("9999" == value) {
      submitForm();
    }
    return true;
}

function validate_DDI_COUNTRY_01() {
    field = window.document.form1.COUNTRY_01;
    value = getFieldValueRB(field);
    if (!validateIsRequired(value)) {
       return alertError(field, "Please indicate what Country you reside in." );
    }
    if (!("USA" == value) && !("CAN" == value)) {
       submitForm();
    }
    return true;
}

function notUSAOrCanCountry() {
	submitForm();
    return true;
}

function validate_ZIP_01(form) {
    value = getFieldValueTF(form.ZIP_01);
    if(!validateIsRequired(value)) {
        return alertError(form.ZIP_01,  "Please enter a valid Zip Code." );
    } 
    
    countryValue = getCountryValue(window.document.form1.COUNTRY_01);
    if(countryValue == "USA") {
        if(!isUSZip(value)) {
            return alertError(form.ZIP_01,  "Please enter a valid Zip Code." );
        }
    } else if(countryValue == "CAN") {
        if(!isCANZip(value)) {
            return alertError(form.ZIP_01,  "Please enter a valid Zip Code." );
        }
    }
    return true;
}

function validate_DDI_EDUCATION_01() {
    field = window.document.form1.DDI_EDUCATION_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please indicate your level of Education." );
    }

    return true;
}

function validate_DDI_MILITARYBRANCH_01() {
    field = window.document.form1.DDI_MILITARYBRANCH_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please indicate military affiliation." );
    }
    return true;
}

function validate_PROVINCE_01(form) {
    var countryValue = getCountryValue(window.document.form1.COUNTRY_01);
    if(countryValue == "USA" || countryValue == "CAN") {
        return true;
    }
    var value = getFieldValueTF(form.PROVINCE_01)
    if(!validateIsRequired(value)) {
       return alertError(form.PROVINCE_01, "Please select your State or Province." );
    }
    return true;
}

function validate_DDI_START_PERIOD_01() {
    field = window.document.form1.DDI_START_PERIOD_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please indicate when you plan to enroll." );
    }

    return true;
}

function validate_DDI_LEARNING_01() {
    field = window.document.form1.DDI_LEARNING_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please indicate which type of program you prefer." );
    }

    return true;
}


function validate_DDI_EARN_YEARLY_01() {
    field = window.document.form1.DDI_EARN_YEARLY_01;
    value = getFieldValueLB(field)
    if(!validateIsRequired(value)) {
        return alertError(field, "Please select how much would you like to earn per year." );
    }

    return true;
}

function validate_PHONE_DAY_COUNTRY_01(form) {
    var countryValue = getCountryValue(window.document.form1.COUNTRY_01);
    if(countryValue == "USA" || countryValue == "CAN") {
        return true;
    }
    var field = window.document.form1.PHONE_DAY_COUNTRY_01;
    var value = getFieldValueTF(field);
    if(!validateIsRequired(value)) {
        return alertError(field, "Please enter a valid preferred phone number." );
    }
    return true;
}

function validate_PHONE_EVENING_COUNTRY_01(form) {
    var countryValue = getCountryValue(window.document.form1.COUNTRY_01);
    if(countryValue == "USA" || countryValue == "CAN") {
        return true;
    }
    var field = window.document.form1.PHONE_EVENING_COUNTRY_01;
    var value = getFieldValueTF(field);
    if(!validateIsRequired(value)) {
        return alertError(field, "Please enter a valid alternate phone number." );
    }
    return true;
}

function validate_PHONE_ALTERN_01(form) {
    var value = getFieldValueTF(form.PHONE_EVENING_PREFIX_01) + getFieldValueTF(form.PHONE_EVENING_SUFFIX_01);
    
    return validate_PHONE_EVENING_01_with_params(form, value, form.PHONE_EVENING_PREFIX_01, "Please enter a valid alternate phone number.");
}

function validate_PHONE_PREF_01(form) {
    var value = getFieldValueTF(form.PHONE_DAY_PREFIX_01) + getFieldValueTF(form.PHONE_DAY_SUFFIX_01);
    
    return validate_PHONE_DAY_01_with_params(form, value, form.PHONE_DAY_PREFIX_01, "Please enter a valid preferred phone number.");
}

function validateDayPhone(form) {
  if(!validate_PHONE_DAY_COUNTRY_01(form)) {
    return false;
  } else if(!validate_PHONE_DAY_AREA_01_with_messages(form, "Please enter your Area Code.", "Please enter a valid preferred phone number.")) {
    return false;
  } else if (!validate_PHONE_PREF_01(form)) {
    return false;
  }
  
  return true;
}

function validateEvePhone(form) {
  if(!validate_PHONE_EVENING_COUNTRY_01(form)) {
    return false;
  } else if(!validate_PHONE_EVENING_AREA_01_with_messages(form, "Please enter your Area Code.", "Please enter a valid alternate phone number.")) {
    return false;
  } else if (!validate_PHONE_ALTERN_01(form)) {
    return false;
  }
  
  return true;
}

function validatePhones(form) {
      var valid = true;
      var phoneDayParts = ["PHONE_DAY_AREA_01", "PHONE_DAY_PREFIX_01", "PHONE_DAY_SUFFIX_01"];
      dayPhone = 0;
      for (i=0;i<phoneDayParts.length;++i) {
        fieldObj = form.elements.namedItem(phoneDayParts[i]);
        dayPhone += (fieldObj && fieldObj.value && fieldObj.value.length>0)? 1: 0;
      }
      
      var phoneEveParts = ["PHONE_EVENING_AREA_01", "PHONE_EVENING_PREFIX_01", "PHONE_EVENING_SUFFIX_01"];
      evePhone = 0;
      for (i=0;i<phoneEveParts.length;++i) {
        fieldObj = form.elements.namedItem(phoneEveParts[i]);
        evePhone += (fieldObj && fieldObj.value && fieldObj.value.length>0)? 1: 0;
      }

      if (0 == dayPhone && 0 == evePhone) { //there is nothing in all fields
          return alertError(form.PHONE_DAY_AREA_01, "Please enter your preferred phone number." );
      }
      else {
          if (dayPhone > 0 && 0 == evePhone) {
            valid = validateDayPhone(form);
            if (valid && !isAskEnterEvePhone) {
              var isValid = alertError(form.PHONE_DAY_AREA_01, "Please enter your alternate phone number.");
              isAskEnterEvePhone = true;
              return isValid;
            }
          }
          else if (evePhone > 0 && 0 == dayPhone) {
            valid = validateEvePhone(form);
            if (valid && !isAskEnterDayPhone) {
              var isValid = alertError(form.PHONE_DAY_AREA_01, "Please enter your preferred phone number.");
              isAskEnterDayPhone = true;
              return isValid;
            }
          } else {
            valid = validateDayPhone(form);
            if (valid) {
              valid = validateEvePhone(form);
            }
          }
      }

      return valid;
}

function validate_CONFIRM_CONTACT() {
    /* LGO-218: Remove JS validation for checkbox for changed DDI forms
    var cbField = window.document.form1.confirm_contact;
    if(cbField) {
      if(cbField.checked == false) {
        return alertError(window.document.form1.confirm_contact, "Please check the box indicating your acknowledgment to be contacted.");
      }
    }
    */
    return true;
}

function showUSStates() {
    var stateField = window.document.form1.STATE_01;
    stateField.enabled = true;
    stateField.length=0;
    stateField.options[stateField.length] = new Option("Select State","");    
    stateField.options[stateField.length] = new Option("Alabama","AL");
    stateField.options[stateField.length] = new Option("Alaska","AK");
    stateField.options[stateField.length] = new Option("American Samoa ","AS");
    stateField.options[stateField.length] = new Option("Arizona","AZ");
    stateField.options[stateField.length] = new Option("Arkansas","AR");
    stateField.options[stateField.length] = new Option("Armed Forces","AE");
    stateField.options[stateField.length] = new Option("California","CA");
    stateField.options[stateField.length] = new Option("Colorado","CO");
    stateField.options[stateField.length] = new Option("Connecticut","CT");
    stateField.options[stateField.length] = new Option("Delaware","DE");
    stateField.options[stateField.length] = new Option("District of Columbia","DC");
    stateField.options[stateField.length] = new Option("Florida","FL");
    stateField.options[stateField.length] = new Option("Georgia","GA");
    stateField.options[stateField.length] = new Option("Guam","GU");
    stateField.options[stateField.length] = new Option("Hawaii","HI");
    stateField.options[stateField.length] = new Option("Idaho","ID");
    stateField.options[stateField.length] = new Option("Illinois","IL");
    stateField.options[stateField.length] = new Option("Indiana","IN");
    stateField.options[stateField.length] = new Option("Iowa","IA");
    stateField.options[stateField.length] = new Option("Kansas","KS");
    stateField.options[stateField.length] = new Option("Kentucky","KY");
    stateField.options[stateField.length] = new Option("Louisiana","LA");
    stateField.options[stateField.length] = new Option("Maine","ME");
    stateField.options[stateField.length] = new Option("Maryland","MD");
    stateField.options[stateField.length] = new Option("Massachusetts","MA");
    stateField.options[stateField.length] = new Option("Michigan","MI");
    stateField.options[stateField.length] = new Option("Minnesota","MN");
    stateField.options[stateField.length] = new Option("Mississippi","MS");
    stateField.options[stateField.length] = new Option("Missouri","MO");
    stateField.options[stateField.length] = new Option("Montana","MT");
    stateField.options[stateField.length] = new Option("Nebraska","NE");
    stateField.options[stateField.length] = new Option("Nevada","NV");
    stateField.options[stateField.length] = new Option("New Hampshire","NH");
    stateField.options[stateField.length] = new Option("New Jersey","NJ");
    stateField.options[stateField.length] = new Option("New Mexico","NM");
    stateField.options[stateField.length] = new Option("New York","NY");
    stateField.options[stateField.length] = new Option("North Carolina","NC");
    stateField.options[stateField.length] = new Option("North Dakota","ND");
    stateField.options[stateField.length] = new Option("Northern Mariana Islands","MP");
    stateField.options[stateField.length] = new Option("Ohio","OH");
    stateField.options[stateField.length] = new Option("Oklahoma","OK");
    stateField.options[stateField.length] = new Option("Oregon","OR");
    stateField.options[stateField.length] = new Option("Palau","PW");
    stateField.options[stateField.length] = new Option("Pennsylvania","PA");
    stateField.options[stateField.length] = new Option("Puerto Rico","PR");
    stateField.options[stateField.length] = new Option("Rhode Island","RI");
    stateField.options[stateField.length] = new Option("South Carolina","SC");
    stateField.options[stateField.length] = new Option("South Dakota","SD");
    stateField.options[stateField.length] = new Option("Tennessee","TN");
    stateField.options[stateField.length] = new Option("Texas","TX");
    stateField.options[stateField.length] = new Option("U.S. Virgin Islands","VI");
    stateField.options[stateField.length] = new Option("Utah","UT");
    stateField.options[stateField.length] = new Option("Vermont","VT");
    stateField.options[stateField.length] = new Option("Virginia","VA");
    stateField.options[stateField.length] = new Option("Washington","WA");
    stateField.options[stateField.length] = new Option("West Virginia","WV");
    stateField.options[stateField.length] = new Option("Wisconsin","WI");
    stateField.options[stateField.length] = new Option("Wyoming","WY");
}

function showCANStates() {
    var stateField = window.document.form1.STATE_01;
    stateField.enabled = true;
    stateField.length=0;
    stateField.options[stateField.length] = new Option("Select State","");
    stateField.options[stateField.length] = new Option("Alberta","AB");
    stateField.options[stateField.length] = new Option("British Columbia","BC");
    stateField.options[stateField.length] = new Option("Manitoba","MB");
    stateField.options[stateField.length] = new Option("New Brunswick","NB");
    stateField.options[stateField.length] = new Option("Newfoundland","NF");
    stateField.options[stateField.length] = new Option("Northwest Territories","NT");
    stateField.options[stateField.length] = new Option("Nova Scotia","NS");
    stateField.options[stateField.length] = new Option("Ontario","ON");
    stateField.options[stateField.length] = new Option("Prince Edward Island","PE");
    stateField.options[stateField.length] = new Option("Quebec","QC");
    stateField.options[stateField.length] = new Option("Saskatchewan","SK");
    stateField.options[stateField.length] = new Option("Yukon Territory","YT");
    }

function initState() {
    if (window.document.form1.COUNTRY_01) {
        var countryValue = getCountryValue(window.document.form1.COUNTRY_01);
        var stateField = window.document.form1.STATE_01;
        var value = getFieldValueLB(stateField);
        if(countryValue == "USA") {
            showUSStates();
            show("div_STATE_01");
            hide("div_PROVINCE_01");
        } else if (countryValue == "CAN") {
            showCANStates();
            show("div_STATE_01");
            hide("div_PROVINCE_01");
        }  else {
            hide("div_STATE_01");
            show("div_PROVINCE_01");
            stateField.length=0;
            stateField.options[stateField.length] = new Option("Select State","");    
            stateField.disabled = true;
            return;
        }
        selectValue(stateField,value);
        stateField.disabled = false;
        return;
    }
}

function filterHighestEd() {
    var gradYr = getFieldValueLB(window.document.form1.DDI_GRADYEAR_01);
    if (gradYr == '9999') {
    	submitForm();
    }
    
    var eduLevel = getFieldValueLB(window.document.form1.DDI_EDUCATION_01);
    if (eduLevel == 'none') {
    	submitForm();
    }
    return;
}

function filterAge() {
    var age = getFieldValueLB(window.document.form1.DDI_AGE_01);
    if (age == '17') {
    	submitForm();
    }
    
    return;
}

function selectValue(field, value) {
    for (var i = 0; i < field.options.length; i++) {
        if (field.options[i].value == value) {
        field.options[i].selected = true
                return;
        }
    }
    return;
}

function selectValueRB(field, value) {
    for (var i = 0; i < field.length; i++) {
        if (field[i].value == value) {
            field[i].checked = true;
            return;
        }
    }
    return;
}

function getFieldValueRB ( field )
{
    if(field.value) {
      return field.value;
    }
    for (i = 0; i < field.length; i++)
    {
        if (field[i].checked == true) return field[i].value;
    } 
    return "";
}

function PageQuery(q) {
  if(q.length > 1) this.q = q.substring(1, q.length);
  else this.q = null;
  this.keyValuePairs = new Array();
  if(q) {
    for(var i=0; i < this.q.split("&").length; i++) {
      this.keyValuePairs[i] = this.q.split("&")[i];
    }
  }
  this.getKeyValuePairs = function() { return
  this.keyValuePairs; }
  this.getValue = function(s) {
    for(var j=0; j < this.keyValuePairs.length; j++) {
      if(this.keyValuePairs[j].split("=")[0] == s) {
        if(this.keyValuePairs[j].split("=").length>1)
        {
          return this.keyValuePairs[j].split("=")[1];
        }
      }
    }
    return "";
  }
  this.getParameters = function() {
    var a = new Array(this.getLength());
    for(var j=0; j < this.keyValuePairs.length; j++) {
      a[j] = this.keyValuePairs[j].split("=")[0];
    }
    return a;
  }
  this.getLength = function() { return
  this.keyValuePairs.length; }
}

function queryString(key){
  var page = new PageQuery(window.location.search);
  return unescape(page.getValue(key));
}

function getLineTypeHeadline(){
  if(enableOCC) {
    var occType = queryString("_OCC");
    if(occType == 'accountant') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occAccountant'+'.g'+'if" />';
    } else if (occType == 'bounty hunter') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occBounty'+'.g'+'if" />';
    } else if (occType == 'chef') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occChef'+'.g'+'if" />';
    } else if (occType == 'counselor') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occCounselor'+'.g'+'if" />';
    } else if (occType == 'cpa') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occCPA'+'.g'+'if" />';
    } else if (occType == 'criminal investigator') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occCriminal'+'.g'+'if" />';
    } else if (occType == 'database administrator') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occDatabase'+'.g'+'if" />';
    } else if (occType == 'detective') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occDetective'+'.g'+'if" />';
    } else if (occType == 'developer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occDeveloper'+'.g'+'if" />';
    } else if (occType == 'engineer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occEngineer'+'.g'+'if" />';
    } else if (occType == 'financier') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occFinancier'+'.g'+'if" />';
    } else if (occType == 'graphic designer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occGraphic'+'.g'+'if" />';
    } else if (occType == 'healthcare manager') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occHealthcare'+'.g'+'if" />';
    } else if (occType == 'HR officer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occHuman'+'.g'+'if" />';
    } else if (occType == 'manager') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occManager'+'.g'+'if" />';
    } else if (occType == 'marketer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occMarketer'+'.g'+'if" />';
    } else if (occType == 'network specialist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occNetwork'+'.g'+'if" />';
    } else if (occType == 'paralegal') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occParalegal'+'.g'+'if" />';
    } else if (occType == 'patient advocate') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occPatient'+'.g'+'if" />';
    } else if (occType == 'police') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occPolice'+'.g'+'if" />';
    } else if (occType == 'project manager') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occProject'+'.g'+'if" />';
    } else if (occType == 'psychologist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occPsychologist'+'.g'+'if" />';
    } else if (occType == 'sales person') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occSales'+'.g'+'if" />';
    } else if (occType == 'social worker') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occSocial'+'.g'+'if" />';
    } else if (occType == 'software professional') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occSoftware'+'.g'+'if" />';
    } else if (occType == 'teacher') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occTeacher'+'.g'+'if" />';
    } else if (occType == 'therapist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occTherapist'+'.g'+'if" />';
    } else if (occType == 'psychologist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occPsychologist'+'.g'+'if" />';
    } else if (occType == 'developer') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occDeveloper'+'.g'+'if" />';
    } else if (occType == 'detective') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occDetective'+'.g'+'if" />';
    } else if (occType == 'medical billing specialist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occMedicalBilling'+'.g'+'if" />';
    } else if (occType == 'medical officer manager') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occMedicalOfficer'+'.g'+'if" />';
    } else if (occType == 'medical coding specialist') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occMedicalCoding'+'.g'+'if" />';
    } else if (occType == 'pharmacy technician') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_occPharmacy'+'.g'+'if" />';
    }
  }

  var aosType = queryString("_AOS");
  if(aosType == 'business') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accBusiness'+'.g'+'if" />';
  } else if(aosType == 'computer science') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accComputer'+'.g'+'if" />';
  } else if(aosType == 'criminal justice') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accCriminal'+'.g'+'if" />';
  } else if(aosType == 'culinary arts') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accCulinary'+'.g'+'if" />';
  } else if(aosType == 'graphic design') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accDesign'+'.g'+'if" />';
  } else if(aosType == 'education') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accEducation'+'.g'+'if" />';
  } else if(aosType == 'health and human services') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accHealth'+'.g'+'if" />';
  } else if(aosType == 'nursing') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accNursing'+'.g'+'if" />';
  } else if(aosType == 'science and engineering') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accScience'+'.g'+'if" />';
  } else if(aosType == 'psychology') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accPsychology'+'.g'+'if" />';
  } else if(aosType == 'liberal arts') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accLiberalArts'+'.g'+'if" />';
  } else if(aosType == 'technology') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accInformationTech'+'.g'+'if" />';
  } else if(aosType == 'culinary arts') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accCulinary'+'.g'+'if" />';
  } else if(aosType == 'medical') {
    return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accMedical'+'.g'+'if" />';
  } else {
    var levType = queryString("_LEV");
    if(levType == 'associates') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accAssociates'+'.g'+'if" />';
    } else if(levType == 'certificates') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accCertificates'+'.g'+'if" />';
    } else if(levType == 'bachelors') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accBachelors'+'.g'+'if" />';
    } else if(levType == 'masters') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accMasters'+'.g'+'if" />';
    } else if(levType == 'doctoral') {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accDoctorate'+'.g'+'if" />';
    } else {
      return '<im'+'g sr'+'c="/images/degreesInfo/'+templateStyle+'/headline_accelerate'+'.g'+'if" />';
    }
  }
}

function initParams() {
    var relation = new Array();
    relation['web design'] = "graphic design";// if web design will be in the url we will use graphic design
    relation['arts'] = "graphic design";
    var urlParamMap = new Array();
    urlParamMap['_AOS'] = "DDI_AOS_01";
    
    var q = window.location.search;
    
    if(q != null && q.length > 1) {
        q = q.substring(1, q.length);
        var keyValuePairs = q.split("&");
        for(var index=0; index < keyValuePairs.length; index++) {
            var delim = keyValuePairs[index].indexOf("=");
            if(delim > 0 && delim < (keyValuePairs[index].length - 1)) {
                var name = keyValuePairs[index].substring(0,delim);
                var value = keyValuePairs[index].substring(++delim,keyValuePairs[index].length);
                value = replaceSpecialSymbols(value);
                if (relation[value]) {
                    value = relation[value];
                }
                if (urlParamMap[name]) {
                    name = urlParamMap[name];
                }
                var field = window.document.getElementsByName(name);
                if(field != null && field.length > 0)
                    initField(field, value);
            }
        }
    }
}

function getDivByField(field) {
  if(field=='DDI_AGE_01') {
    return "div_DDI_AGE";
  } else if(field=='DDI_GRADYEAR_01') {
    return "div_DDI_GRADYEAR";
  } else if(field=='DDI_AOS_01') {
    return "div_DDI_AOS";
  } else if(field=='EMAIL_01') {
      var obj = document.getElementById("div_"+field);
      if (obj != undefined && obj != null) {
          return "div_"+field;
      }
      
      return "div_ZIP_01";
  } else {
    return "div_"+field;
  }
}

function showErrorQuestions() {
//ZIP and email are validated together so if both are errors only use one.
  var emailError = false;
  var zipError = false;
  var countryError=false;
  var subAosError = false;
  
  for(i=0;i<errors.length;i++) {
    if(errors[i]=='EMAIL_01') {
      emailError=true;
     } else if(errors[i]=='ZIP_01') {
      zipError=true;
     } else if(errors[i]=='COUNTRY_01') {
       countryError=true;
     } else if(errors[i]=='DDI_SUB_AOS_01') {
       subAosError = true;
     }
  }
  if(countryError) {
     errors[errors.length] = 'USCITIZEN_01';
  }
  if(subAosError) {
	 errors[errors.length] = 'DDI_AOS_01';
  }
  showHideQ(null, 0);
  var group = [];
  if (window.qListGroups) {
     window.qListGroups.length = 0;
  } else {
    qListString.length = 0;
  }
  
  for(i=0;i<errors.length;i++) {
    if (window.qListGroups) {
      //alert(errors[i]);
//      window.qListGroups[0][window.qListGroups[0].length] = getDivByField(errors[i]);
      group[group.length] = getDivByField(errors[i]);
    } else {
      if(zipError == true && emailError == true && errors[i] == 'EMAIL_01') {
      } else {
        var fieldIndex = qListString.length;
        qListString[fieldIndex] = getDivByField(errors[i]);
        resetFieldQuestion(qListString[fieldIndex]);
      }
    }
  }
  
  if(window.qListGroups) {
     window.qListGroups[0] = group;
  }
  
  showHideQ(0, null);
}

function resetFields() {
    if(errors && errors.length > 0) {
        showErrorQuestions();
        return;
    }
    isReset = false;
    if (!window.dhtmlHistoryDisabled && window.dhtmlHistory && window.dhtmlHistory.currentLocation && !window.qListGroups) {//reset all fields greater than currentLocation question
       window.inReset = true;
       currentQ=parseInt(dhtmlHistory.currentLocation.substring(2));
       if(!isNaN(currentQ)) {
         for(var i=currentQ;i<qListString.length;++i) {
           resetFieldQuestion(qListString[i]);
         }
       }
       
      isReset = true;
    }
    if (window.qListGroups) {//do not reset for groups
      window.inReset = true;
      isReset = true;
    }
    if (!isReset) {
	    if (window.document.form1.DDI_AGE_01) {
	    	window.document.form1.DDI_AGE_01.options[0].selected = true;
	    }
	    if (window.document.form1.DDI_GRADYEAR_01) {
	    	window.document.form1.DDI_GRADYEAR_01.options[0].selected = true;
	    }
	    if (window.document.form1.DDI_EDUCATION_01) {
	    	window.document.form1.DDI_EDUCATION_01.options[0].selected = true;
	    }
	    if (window.document.form1.COUNTRY_01) {
	    	window.document.form1.COUNTRY_01[0].checked = false;
	    	window.document.form1.COUNTRY_01[1].checked = false;
	    	window.document.form1.COUNTRY_01[2].checked = false;
	    }
	    if (window.document.form1.USCITIZEN_01) {
	    	window.document.form1.USCITIZEN_01[0].checked = false;
	    	window.document.form1.USCITIZEN_01[1].checked = false;
	      
	    	hide("div_COUNTRY_01");
	    	window.document.form1.COUNTRY_01[0].checked = false;
	    	window.document.form1.COUNTRY_01[1].checked = false;
	    	window.document.form1.COUNTRY_01[2].checked = false;
	    }
	    if (window.document.form1.DDI_MILITARYAFFILIATE_01) {
	        window.document.form1.DDI_MILITARYAFFILIATE_01[0].checked = false;
	        window.document.form1.DDI_MILITARYAFFILIATE_01[1].checked = false;
	    }
	    if (window.document.form1.DDI_MILITARYBRANCH_01) {
	    	window.document.form1.DDI_MILITARYBRANCH_01.options[0].selected = true;
	    } 
	    if (window.document.form1.DDI_START_PERIOD_01) {
	    	window.document.form1.DDI_START_PERIOD_01.options[0].selected = true;
	    }
	    if (window.document.form1.DDI_EARN_YEARLY_01) {
	    	window.document.form1.DDI_EARN_YEARLY_01.options[0].selected = true;
	    }
    }
}

function resetFieldQuestion(divId) {
    if(divId == 'div_DDI_AGE') {
        window.document.form1.DDI_AGE_01.options[0].selected = true;
    } else if(divId == 'div_DDI_GRADYEAR') {
        window.document.form1.DDI_GRADYEAR_01.options[0].selected = true;
    } else if(divId == 'div_DDI_EDUCATION_01') {
        window.document.form1.DDI_EDUCATION_01.options[0].selected = true;
    } else if(divId == 'div_DDI_START_PERIOD_01') {
        window.document.form1.DDI_START_PERIOD_01.options[0].selected = true;
    } else if(divId == 'div_DDI_EARN_YEARLY_01') {
        window.document.form1.DDI_EARN_YEARLY_01.options[0].selected = true;
    } else if(divId == 'div_COUNTRY_01') {
        window.document.form1.COUNTRY_01[0].checked = false;
        window.document.form1.COUNTRY_01[1].checked = false;
        window.document.form1.COUNTRY_01[2].checked = false;
    } else if(divId == 'div_USCITIZEN_01') {
        window.document.form1.USCITIZEN_01[0].checked = false;
        window.document.form1.USCITIZEN_01[1].checked = false;
        hide("div_COUNTRY_01");
        window.document.form1.COUNTRY_01[0].checked = false;
        window.document.form1.COUNTRY_01[1].checked = false;
        window.document.form1.COUNTRY_01[2].checked = false;
    } else if(divId == 'div_DDI_MILITARYBRANCH_01') {
        window.document.form1.DDI_MILITARYBRANCH_01.options[0].selected = true;
    }
}

function resetFieldValue() {
    if(window.qListGroups) {
        resetFieldQuestion(window.qListGroups[curQ]);
    }
    else if(qListString){
        resetFieldQuestion(qListString[curQ]);
    }
}

function highlightSubmissionError(field, message)
{
    var ancestor = field.parentNode;
    if (!ancestor) return false;
    if(field.name.indexOf('PHONE_DAY_')==0 || field.name.indexOf('PHONE_EVENING_')==0) {
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
    }
    if(field.name.indexOf('DDI_AOS_01')==0) {
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
    }
    if(!isErrorClass(ancestor)) {
        addErrorClass(ancestor);
        var errorMessage = document.createElement("span");
        errorMessage.id=field.name+"_errorMsg";
        errorMessage.className='warning';
        errorMessage.innerHTML = '<br>'+message;
        ancestor.appendChild(errorMessage);
    }
  if (window.formFamily && window.formFamily == "DegreesInfo") {
    var fieldName = "UNKNOWN";
    
    if (field) {
        if (field.length && field.length >0 && field[0].name && field[0].name!=null) {
          fieldName = field[0].name;
        }
        else if (field.name && field.name!=null){
          fieldName = field.name;
        }
    }
    ValidationTracker.trackAlert(fieldName, message);
  }
    
}

function removeSubmissionError(field)
{
    var ancestor = field.parentNode;
    if (!ancestor) return false;
    if(field.name.indexOf('PHONE_DAY_')==0 || field.name.indexOf('PHONE_EVENING_')==0) {
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
    }
    if(field.name.indexOf('DDI_AOS_01')==0) {
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
        ancestor = ancestor.parentNode;
    }
    if(isErrorClass(ancestor)) {
        removeErrorClass(ancestor);
    }
    elementToRemove=document.getElementById(field.name+"_errorMsg");
    if(elementToRemove) {
      ancestor.removeChild(elementToRemove);
    }
}

function addErrorClass(element) {
  if(element)
  {
    element.className+=element.className?' ddierror':'ddierror';
  }
}

function removeErrorClass(element) {
  if(element)
  {
    if(element.className) {
      var rep=element.className.match(' ddierror')?' ddierror':'ddierror';
      element.className=element.className.replace(rep,'');
    }
  }
}

function isErrorClass(element) {
  if(element)
  {
    if(element.className) {
      return element.className.indexOf('ddierror')>=0;
    }
  }
}

function alertErrors() {
  for(var i=0;i<errors.length;i++) {
    var yourElement = errors[i];
    var yourMessage = messages[i];
    highlightSubmissionError(yourElement,yourMessage);
  }
  
  return false;
}

function alertErrorsFromIds() {
  for(var i=0;i<errors.length;i++) {
    var yourElement = document.getElementById(errors[i]);
    var yourElementToHide = document.getElementById(errors[i]+"_errorMsg2");
    if(yourElementToHide && yourElementToHide.className) {
      yourElementToHide.className='hidden';
    }
    errors[i]=yourElement;
  }
  
  return alertErrors();
}

function displayMatchAndHidePII() {
    // Change the match table to 'show' and PII table to 'hide', also make sure, the match tables button is visible ('show')
    if(document.getElementById("PIITable") == null) {
       return;
    }
    show("MatchTable");
    show("continueButton");
    hide("PIITable");
    hide("requestInfoTable");
}

function displayPIIAndHideMatch() {
    if(document.getElementById("MatchTable") == null) {
       return;
    }
    if(validate_FILTERMATCHLIST()){
        hide("MatchTable");
        hide("continueButton");
        if(typeof(isEmailRemarketing) != 'undefined' && isEmailRemarketing==true && isPIIPrepopulated(window.document.form1)){
        	submitForm();
        } else {
            show("PIITable");
            show("requestInfoTable");
            show("backbutton");
        }
        return true;
    }else{
        return false;
    }
}

function isPIIPrepopulated(form){
    var isAllPrepopulated = true;
    var piiRequiredQuestions = ["DDI_TITLE", "FIRSTNAME_01", "LASTNAME_01", "ADDRESS1_01", 
                                "CITY_01", "STATE_01", "PROVINCE_01", "ZIP_01", "PHONE_DAY_COUNTRY_01", 
                                "PHONE_DAY_AREA_01", "PHONE_DAY_PREFIX_01", "PHONE_DAY_SUFFIX_01", "EMAIL_01"];
    
    for (var i = 0; i < piiRequiredQuestions.length; i++) {
        var questName = piiRequiredQuestions[i];
        var field = form[questName];
        if (field) {
            if((questName == "STATE_01" || questName == "PROVINCE_01") && isHidden("div_"+questName)){
                continue;
            }    
            var value = getFieldValue(field);
            if (isBlank(value)) {
                isAllPrepopulated = false;
                break;
            }
        }
    }      
    return isAllPrepopulated;
}

function clearErrors() {
  for(var i=0;i<errors.length;i++) {
    var yourElement = errors[i];
    removeSubmissionError(yourElement);
  }
  errors =[];
  messages = [];
}

//overrides what is in validateFields.js
function alertError(field, message) {
  var fieldName = "UNKNOWN";
    
  if (field) {
      if (field.length && field.length >0 && field[0].name && field[0].name!=null) {
        fieldName = field[0].name;
        field = field[0];
      }
      else if (field.name && field.name!=null){
        fieldName = field.name;
      }
  }

  if(typeof(useInlineErrorMessages) != 'undefined' && useInlineErrorMessages==true) {
      errors[errors.length]=field;
      messages[messages.length]=message;
      return false;
  } else {
    alert(message);
    if (field) {
      if (field.focus) {
    	  try {
    		  field.focus();
    		  
    	  } catch (e) {    		  
    		  //
    		  // disregard error
    		  //
    		  // field might be:
    		  //
    		  // a. invisible
    		  // b. not enabled
    		  // c. cannot accept focus
    		  //
    	  }
      }
    }
  }
  if (window.formFamily && window.formFamily == "DegreesInfo") {
    ValidationTracker.trackAlert(fieldName, message);
  }
  return false;
}

function updateProgressBar()
{
    if(curQ==0) {
       hide("backbutton");
    } else {
       show("backbutton");
    }
    
    updateDivProgressBar();
    updateStepsProgressBar();
	updateTextProgressBar();
}

function updateDivProgressBar() {
  var divProgress = window.document.getElementById("div_progress");
  if (divProgress) {
    if (window.qListGroups) {
      divProgress.style.width = Math.round(curQ/window.qListGroups.length * 100) + "%";
    }
    else {
      divProgress.style.width = Math.round(curQ/qListString.length * 100) + "%";
    }
  }  
}

function updateTextProgressBar() {
  var textProgress = window.document.getElementById("text_progress");
  if (textProgress) {
    if (window.qListGroups) {
		textProgress.innerHTML = "<span class='percentCompleteText'>" + Math.round(curQ/window.qListGroups.length * 100) + "%</span> Complete";
    }
    else {
		textProgress.innerHTML = "<span class='percentCompleteText'>" + Math.round(curQ/qListString.length * 100) + "%</span> Complete";
    }
  }  
}

function updateStepsProgressBar() {
  var stepsProgress = document.getElementById("steps_progress");
  if (stepsProgress) {
    var numOfSteps = 1;
    var curStep = curQ + 1;
    if (window.qListGroups) {
      numOfSteps = window.qListGroups.length;
    }
    else if (qListString){
      numOfSteps = qListString.length;
    }
    stepsProgress.innerHTML = "Step <span class='current'>" + curStep + "</span> of " + numOfSteps;
  }
}

function hideZipCodeField() {
    var zipErrorOn = false;
    if(errors) {
            var errorIndex = errors.length - 1;
            while(errorIndex >= 0 && !zipErrorOn) {
                if(errors[errorIndex] == "ZIP_01") {
                    zipErrorOn = true;  
                }

                errorIndex--;
            }
    }
    
    if(!zipErrorOn) {
        hide("HIDDEN_ZIP_01");
    }
}

function isZipCodeVisible() {
    return isVisible("HIDDEN_ZIP_01");
}

function hideEmailField(pageNumber) {
    var emailPageNo = document.getElementsByName("EMAIL_PAGE_NO");
    if(emailPageNo && emailPageNo.length > 0) {
        emailPageNo = emailPageNo[0].value;
    }

    if(emailPageNo && emailPageNo != pageNumber) {
        hide("div_EMAIL_01");   
    }
}

function isEmailVisible() {
    return isVisible("div_EMAIL_01");
}

var displayNextFieldAfterCountryClick = true;

function initializeGroups(groupMatrix) {
    if(!groupMatrix) {
        return;
    }

    var nextButtonId = "div_NEXT_BTN";
    //ATTACH next button and remove ONCHANGE events where necessary
    for(var i = 0; i < groupMatrix.length; i++) {
        var group = groupMatrix[i]

        //if group has several elements, add Next button and remove onchange/onclick events
        if(group.length > 1) {
            for(var j = 0; j < group.length; j++) {
            	if(group[j] == 'div_USCITIZEN_01') {
    	            displayNextFieldAfterCountryClick = false;
                } else {
                    removeEvents(group[j]);
                }
            }
            group[group.length] = nextButtonId;
        } 
        //else if group has a single element, add Next button if required, keep onchange events
        else if(group.length == 1) {
            if(isNextBtnRequired(group[0])) {
                group[group.length] = nextButtonId;
            }
        }
    }

    //Show first group elements
    firstGroup = groupMatrix[0];
    for(var i = 0; i < firstGroup.length; i++) {
        var div = document.getElementById(firstGroup[i]);
        if(div) {
            div.className = div.className.replace(/hidden/, "visible"); 
        }
    }
    
    qListString = null;
}   

function removeEvents(divId) {
    var fields = getFieldsWithinDiv(divId);
    for(var i = 0; i < fields.length; i++) {
        fields[i].onchange = null;
        //if there is sub-AOS, then do not remove the onClick event for DDI_AOS_01
        if(fields[i].name == "DDI_AOS_01" && window.document.form1.DDI_SUB_AOS_01_DISPLAY) {
        	var subAosDisplay = getFieldValueTF(window.document.form1.DDI_SUB_AOS_01_DISPLAY);
        	if(subAosDisplay == "HIDE") {
        		fields[i].onclick = null;
        	}
        } else {
        	fields[i].onclick = null;
        }
    }
}

function isNextBtnRequired(divId) {
    var requiresBtn = false;
    
    if(divId == 'div_DDI_AOS' || divId == 'div_EMAIL_01' || divId == 'div_ZIP_01' || divId == 'div_DDI_DEGREELEVEL' 
    		|| (getFieldValueTF(window.document.form1.DDI_SUB_AOS_01_DISPLAY) != "HIDE" && divId == 'div_DDI_SUB_AOS')) {
        requiresBtn = true;
    }
    
    return requiresBtn;
}

function getFieldsWithinDiv(divId) {
    var fieldName = divId;
    if(fieldName.indexOf('_01') == -1) {
        fieldName = fieldName + '_01';
    }
    
    if(fieldName.indexOf('div_') == 0) {
        fieldName = fieldName.substring(4);
    }
    
    var fields = document.getElementsByName(fieldName);
    
    return fields;
}

function getFormField(fieldName) {
    return eval("window.document.form1." + fieldName);
}

function validate_OTHER_AGENT_FIRSTNAME_01(form) {
	if (!isAgentOther(form)) {
	    return true;	
	}
	
	var field = form.OTHER_AGENT_FIRSTNAME_01;
	if(field) {
        var value = getFieldValueLB(field);
        if(!validateIsRequired(value)) {
        	checkAgentOther();
            return alertError(field, "Please enter a valid agent first name or choose from the list provided.");
        }
    }
    return true;	
}

function validate_OTHER_AGENT_LASTNAME_01(form) {
	if (!isAgentOther(form)) {
	    return true;	
	}
	
    var field = form.OTHER_AGENT_LASTNAME_01;
    if(field) {
        var value = getFieldValueLB(field);
        if(!validateIsRequired(value)) {
        	checkAgentOther();
            return alertError(field, "Please enter a valid agent last name or choose from the list provided.");
        }
    }
    return true;	
}

function isAgentOther(form) {
	var field = form.AGENT_NAME_01;
	if(field) {
        var value = getFieldValueLB(field);
        if (value == 'Other,Other') {
        	return true;
        }
	}
	
	return false;
}

function validate_AGENT_NAME_01(form) {
	var field = form.AGENT_NAME_01;
	if(field) {
        var value = getFieldValueLB(field);
        if(!validateIsRequired(value)) {
            return alertError(field, "Please select agent name.");
        }
    }
    return true;
}

function validate_AGENT_FIRSTNAME_01(form) {
    var field = form.AGENT_FIRSTNAME_01;
    if(field) {
        var value = getFieldValueLB(field);
        if(!validateIsRequired(value)) {
            return alertError(field, "Please select agent's first name");
        }
    }
    return true;
}

function validate_AGENT_LASTNAME_01(form) {
    var field = form.AGENT_LASTNAME_01;
    if(field) {
        var value = getFieldValueLB(field);
        if(!validateIsRequired(value)) {
            return alertError(field, "Please select agent's last name");
        }
    }
    return true;
}

function validateIsNumeric(value) {
   var validChars = "0123456789.";
   var isNumeric=true;
   var charact;

   for (i = 0; i < value.length && isNumeric == true; i++) 
   { 
     charact = value.charAt(i); 
      if (validChars.indexOf(charact) == -1) 
      {
         isNumeric = false;
      }
   }
   return isNumeric;
}

function validateLength(value, expectedLength) {
    var actualLength = value.length;
    if (actualLength != expectedLength){
        return false;
    }
    return true;
}

function trimString(str) {
    return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function resetForwardHistory() {
}

function citizenChanged(citizenField) {
  resetForwardHistory();
  optField = window.document.form1.USCITIZEN_01;
  optValue = getFieldValueRB(optField);
  if(optValue == 'YES' && window.hideResidencyForUSCitizen) {
    setCountryFieldToEqualUS();
    hide("div_COUNTRY_01");
    if(displayNextFieldAfterCountryClick) {
        displayNextQ(window.document.form1.USCITIZEN_01);
    }
  } else {
    showCountryQuestion();
  }
}

function citizenChangedNonSeamless(citizenField) {

	var zitizen = getFieldValueRB(window.document.form1.USCITIZEN_01);
	
	if(zitizen == 'YES' && window.hideResidencyForUSCitizen) {
	    setCountryFieldToEqualUS();
	    hide("div_COUNTRY_01");
	} else {
		showCountryQuestion();
	}
}

function hideCountryBasedOnCitizen(citizenField) {
	var optField = window.document.form1.USCITIZEN_01;
	var optValue = getFieldValueRB(optField);
	if(optValue == 'YES' && window.hideResidencyForUSCitizen) {
		setCountryFieldToEqualUS();
		hide("div_COUNTRY_01");
	} else {
		showCountryQuestion();
	}
}

function showCountryQuestion() {
  window.document.form1.COUNTRY_01[0].checked = false;
  window.document.form1.COUNTRY_01[1].checked = false;
  window.document.form1.COUNTRY_01[2].checked = false;
  show("div_COUNTRY_01");
}

function countryQuestionClicked(countryField) {
	if(displayNextFieldAfterCountryClick) {
	    displayNextQ(window.document.form1.USCITIZEN_01);
	}
}

function setCountryFieldToEqualUS() {
	var countryField = window.document.form1.COUNTRY_01;
	for(var i=0;i<countryField.length;i++) {
        if(countryField[i].value=='USA') {
            countryField[i].checked=true;
        } else {
        	countryField[i].checked=false;
        }
    }
}

function initializeMilitaryAffiliate(form){
	if (window.noPreselectMilitaryAffiliate) {
		form.DDI_MILITARYAFFILIATE_01[0].checked = false;
		form.DDI_MILITARYAFFILIATE_01[1].checked = false;
	} 
}

//This only use to resolve issue with browser reloading
function addToDefaultFieldNameValueArray(form, fieldNameArray) {
	for (var i = 0; i < fieldNameArray.length; i++) {
		var field = form[fieldNameArray[i]];
		if (!field) {
			continue;
		}
		if (field.type == 'text' || field.type == 'hidden') {
			defaultFieldNameValueArray.push([field, field.value]);
		} else if (field.type == 'select-one') {
			defaultFieldNameValueArray.push([field, field.selectedIndex]);
		} else if ((field.type == 'checkbox' || field[0].type == 'checkbox') 
			|| (field.type == 'radio' || field[0].type == 'radio')) {
		    if (field.length == 0) {
		    	defaultFieldNameValueArray.push([field, field.checked]);
		    } else {
		    	for (var j = 0; j < field.length; j++) {
		    		defaultFieldNameValueArray.push([field[j], field[j].checked]); 
		    	}
		    }
		}
	}
}

//This only use to resolve issue with browser reloading
function resetFieldsToDefaultValue() {
	for (var i = 0; i < defaultFieldNameValueArray.length; i++) {
		var field = defaultFieldNameValueArray[i][0];
		var value = defaultFieldNameValueArray[i][1];
		
		if (field.type == 'text' || field.type == 'hidden') {
			field.value = value;
		} else if (field.type == 'select-one') {
			field.selectedIndex = value;
		} else if (field.type == 'checkbox' || field.type == 'radio') {
			field.checked = value;
		}
	}
}

function filterPrograms(schoolName) {
	var locValue = getFieldValueLB(window.document.form1.PROGRAM_LOCATION_01);
	var field = window.document.form1["MATCH_FILTER_" + schoolName];
	var value = getFieldValueLB(field);
	var fdIds = locsFdIds[locValue];
	
	// remove all children
	while(field.firstChild) {
		field.removeChild(field.firstChild);
	}
	
	field.disabled = false;
	var firstOption = createOption("Please Select a Program:", "");
	field.insertBefore(firstOption, field.firstChild);
	if(fdIds) {
		var currentLevel = null;
		for (var i = 0; i < fdIds.length; i++) {
			var progLevel = progNames[fdIds[i]][1];
			var optGroup = findOptGroup(field, progLevel);
			var option = createOption(progNames[fdIds[i]][0], fdIds[i]);
			optGroup.appendChild(option);
		}
	} else {
		field.disabled = true;
	}
	setFieldValueLB(field, value);
	// set current selection: Please Select a Program on location
	field.selectedIndex = 0;
}

function findOptGroup(node, name) {
	var optGroup = null;
	for(var i=0; i < node.childNodes.length; i++) { 
		var child = node.childNodes[i];
		if(child.tagName.toLowerCase() == "optgroup") {
			if(child.getAttribute('label').toLowerCase() == name.toLowerCase()) {
				optGroup = child;
				break;
			}
		}
	}
	
	// create optgroup if it's not there
	if(optGroup == null) {
		optGroup = window.document.createElement('optgroup');
		optGroup.setAttribute('label', name);
		node.appendChild(optGroup);
	}
	return optGroup;
}

function createOption(label, value) {
	var option = window.document.createElement('option');
	var text = window.document.createTextNode(label);
	option.setAttribute('value', value);
	option.appendChild(text);
	return option;
}

function prepopMilitaryAffiliate(militaryAffiliateName, containerMilitaryBranchId) {
	var militaryAffiliateField = window.document.form1[militaryAffiliateName];
	if (militaryAffiliateField) {
		if (!window.militaryAffiliatePrepop) {
			militaryAffiliateField[0].checked = false;
			militaryAffiliateField[1].checked = false;
		} else {
			if ("YES" == window.militaryAffiliatePrepop.toUpperCase()) {
				militaryAffiliateField[0].checked = true;
			} else {
				militaryAffiliateField[1].checked = true;
			}
		}
		
		showHideMilitaryBranch(militaryAffiliateName,containerMilitaryBranchId);
	}
}

function showHideMilitaryBranch(militaryAffiliateName, containerMilitaryBranchId) {
	var militaryAffiliateElement = window.document.form1[militaryAffiliateName];
	
	if (militaryAffiliateElement[0].checked) {
		var containerMilitaryBranchElement = document.getElementById(containerMilitaryBranchId);
        try {
        	if (containerMilitaryBranchElement.nodeName == "TR") {
        		containerMilitaryBranchElement.style.display = "table-row";
        	} else {
        		show(containerMilitaryBranchId);
        	}
        }
        catch(err) {
        	containerMilitaryBranchElement.style.display = "block";
        }
	} else {
		hide(containerMilitaryBranchId);
    }
}

function showHideCountry(citizenId, containerCountryId) {
	if (window.hideResidencyForUSCitizen) {
		if (window.document.getElementById(citizenId).checked) {
			hide(containerCountryId);
		} else {
			show(containerCountryId);
		}
    } else {
    	show(containerCountryId);
    }
}

function initAgentInfo() {
	var form = window.document.form1;
	var agentFirstNameField = form["AGENT_FIRSTNAME_01"];
	var agentLastNameField = form["AGENT_LASTNAME_01"];
	var defaultValue = "Please select one";
	
	if (agentFirstNameField && agentLastNameField && typeof(agentFirstNamesArray) != 'undefined') {
		var agentFirstNameValue = getFieldValue(agentFirstNameField);
		var agentLastNameValue = getFieldValue(agentLastNameField);
		agentFirstNameField.length = 0;
		agentLastNameField.length = 0;
		addOptionToListBox(agentFirstNameField, "", defaultValue);
		
		for(var i = 0; i < agentFirstNamesArray.length; i++) {
			addOptionToListBox(agentFirstNameField, agentFirstNamesArray[i], agentFirstNamesArray[i]);
		}
		
		if (isBlank(agentFirstNameValue)) {
			setFieldValue(agentFirstNameField.id, "");
			agentLastNameField.disabled = true;
		} else {
			addOptionToListBox(agentLastNameField, "", defaultValue);
			populateLastName(agentFirstNameField);
			setFieldValue(agentLastNameField.id, agentLastNameValue);
			agentLastNameField.disabled = false;
		}
	}
}

function setCecWTParams() {
	var form = window.document.form1;
	var agentNameField = form["AGENT_NAME_01"];
	var agentFirstNameField = form["AGENT_FIRSTNAME_01"];
	var agentLastNameField = form["AGENT_LASTNAME_01"];
	
	var agentNameValue = getFieldValue(agentNameField);
	
	if (isNotBlank(agentNameValue) && agentFirstNameField && agentLastNameField) {
		var names = agentNameValue.split(",");
		var firstName = names[1];
		var lastName = names[0];
		
		setFieldValue(agentFirstNameField, firstName);
		setFieldValue(agentLastNameField, lastName);
	}
}

function setWTParams(concatenatedAgentValue) {
	var form = window.document.form1;
	var agentIdField = form["WARM_TRANSFER_AGENT_ID_01"];
	var agentNameField = form["WARM_TRANSFER_AGENT_NAME_01"];
	var agentEmailField = form["WARM_TRANSFER_EMAILS_01"];
	var agentIdValue = getFieldValue(agentIdField);
	
	if (isNotBlank(agentIdValue) && agentNameField && agentEmailField && typeof(agentIdsMap) != 'undefined') {
	    var agentParamValues = agentIdsMap[agentIdValue];
	    if (isArray(agentParamValues)) {
	    	setFieldValue(agentNameField, agentParamValues[0]);
	    	setFieldValue(agentEmailField, agentParamValues[1]);
		} else {
			setFieldValue(agentNameField, agentParamValues);
		}
	}
}

function populateLastName(agentFirstNameField) {
	var form = window.document.form1;
	var agentFirstNameField = form["AGENT_FIRSTNAME_01"];
	var agentLastNameField = form["AGENT_LASTNAME_01"];
	var agentFirstNameValue = getFieldValue(agentFirstNameField);
	var defaultValue = "Please select one";
	var otherValue = "Other";
	
	if (agentLastNameField) {
		agentLastNameField.length = 0;
		agentLastNameField.disabled = true;
	}
	
	if (isNotBlank(agentFirstNameValue) && agentLastNameField && typeof(agentLastNamesMap) != 'undefined') {
		addOptionToListBox(agentLastNameField, "", defaultValue);
		var agentLastNames = agentLastNamesMap[agentFirstNameValue];
		if (isArray(agentLastNames)) {
			for(var i = 0; i < agentLastNames.length; i++) {
				addOptionToListBox(agentLastNameField, agentLastNames[i], agentLastNames[i]);
			}
		}
		
		if(agentFirstNameValue.toLowerCase() != otherValue.toLowerCase()) {
		    addOptionToListBox(agentLastNameField, otherValue, otherValue);
		}
		
		setFieldValue(agentLastNameField, "");
		if (isBlank(getFieldValue(agentFirstNameField))) {
			agentLastNameField.disabled = true;
		} else {
			agentLastNameField.disabled = false;
		}
	} 
}

function inArray( elem, array ) {
	
	var ret = false;
	
	if ( array.indexOf && array.indexOf( elem ) > -1) {
		ret = true;
	} else {
		for ( var i = 0, length = array.length; i < length; i++ ) {
			if ( array[ i ] === elem ) {
				ret = true;
				break;
			}
		}
	}

	return ret;
}

/**
 * 
 */
var UIUtil = UIUtil || {};
UIUtil.DDIToolTip = function() {
    var logoClass = 'match-logo';
    var descriptionSuffix = '_description';
    var descriptionsContainerId = 'matchedSchoolDescriptions';
    var generateToolTips = function(logos) {
        for (var i=0, len=logos.length; i< len; i++) {
            var prefix = logos[i].id.split("_")[0];
            var content = document.getElementById(prefix + descriptionSuffix).innerHTML;
	        $(logos[i]).qtip({
	           position: {corner : {target: 'topRight', tooltip: 'bottomLeft'}},
	           content: content,
               style: {
	                  tip: 'bottomLeft',
	                  border: {
	                     width: 2,
	                     radius: 4
	                  },
	                  width: 500,
	                  padding: 10, 
	                  name: 'cream' 
	           }
	        });
        }
    };
    
    return {
        init: function() {
           //check first if there are descriptions
           var descriptionsContainer = document.getElementById(descriptionsContainerId);
           if (descriptionsContainer !== null) {
	            //check if jQuery is present
	            if (typeof jQuery !== 'undefined') {
	               //check if qTip is loaded 
	               if (typeof $(document.body).qtip !== 'undefined') {
	                   //call on ready
	                   $(function() {
	                       var logos = $('.' + logoClass);
		                       generateToolTips(logos);
	                       
	                   });
	               }
	            }
           }
	    }
    };
}();

UIUtil.DDIAOSToolTip = function() {
   var dataDivId = 'aos_tooltip_map';
   var flexFormAOSContainer = 'DDI_AOS_01_INPUT_SPAN';
   
   var generate = function generate() {
       for (var aos in aosToolTipMap) {
	        $('#' + aos).qtip({
	           position: {corner : {target: 'topLeft', tooltip: 'bottomLeft'}},
	           content: aosToolTipMap[aos],
               style: {
	                  tip: 'bottomMiddle',
	                  border: {
	                     width: 2,
	                     radius: 4
	                  },
	                  width: 400,
	                  padding: 10, 
	                  name: 'cream' 
	           }
	        });
       }
   };
   
   createIds = function createIds() {
       var inputs = $('#' + flexFormAOSContainer + ' input').each(function(index) {
           var id = $(this).val().replace(' ', '_');
           $(this).parent().attr('id', id);
       });
   };

   return {
       init: function init() {
           var div = document.getElementById(dataDivId);
           if (div !== null) {
	           var jsString = div.innerHTML;
	           if (jsString !== '') {
	               //this should generate the object literal defining the map
	               eval(jsString);
	           }
           }
   
           if (typeof aosToolTipMap !== 'undefined' && aosToolTipMap !== null) {
              if (typeof isFlexForm !== 'undefined' && isFlexForm === true) {
                  createIds();
              }
              generate(); 
           }
       }
   };
}();


UIUtil.MatchPageButtonToggler = function() {
    var disabledButtonClass = 'submitBtnDisabled';
    var enabledButtonClass = 'submitBtnActive';
    var submitButtonId = 'matchPageBtn';
    var elementsClassName = 'dummyButtonClass';
    
    var attachEventListeners = function() {
        var elements = $('.' + elementsClassName);
        
        for (var i=0, len=elements.length; i<len; i++) {
            $(elements[i]).change(toggleClassName);
        }
    };
    
    var toggleClassName = function(e) {
        
        if (hasNoSelectedFields()) {
            $('#' + submitButtonId).toggleClass(enabledButtonClass, false);//remove
            $('#' + submitButtonId).toggleClass(disabledButtonClass, true);//add
        }
        else {
            $('#' + submitButtonId).toggleClass(enabledButtonClass, true);//add
            $('#' + submitButtonId).toggleClass(disabledButtonClass, false);//remove
        }
    };
    
    var hasNoSelectedFields = function(e) {
        var elements = $('.' + elementsClassName);
        var hasSelected = false;
        
        for (var i=0, len=elements.length; i<len; i++) {
            if (elements[i].value !== '') {
                hasSelected = true;
            }
        }
        
        if (hasSelected) {
            return false;
        }
        else {
            return true;
        }
        
    };
    
    return {
        init: function() {
            if (typeof jQuery !== 'undefined') {
               attachEventListeners(); 
               //trigger onload
               toggleClassName();
               
               $(document.body).find('input[type=text]').each(function() {
                   $(this).attr('autocomplete', 'off');
               });
            }
        }
    };
}();


UIUtil.PIIButtonToggler = function() {
    var provinceListId = 'PROVINCE_01'; 
    var stateListId = 'STATE_01'; 
    var fieldList = [];//to keep track if which fields we're listening to
    var disabledButtonClass = 'submitBtnDisabled';
    var enabledButtonClass = 'submitBtnActive';
    var submitButtonId = 'piiBtn';
    
    var attachEventListeners = function() {
        for (var i=0, len=buttonPIIGroup.length; i<len; i++) {
            //special case state and province fields 
            if (buttonPIIGroup[i] === stateListId || buttonPIIGroup[i] === provinceListId) {
                //check if field is hidden, if it is we don't need to listen to this field
                if (document.getElementById('div_' + buttonPIIGroup[i]).style.display !== 'none') {
                    $('#' + buttonPIIGroup[i]).change(toggleClassName);
                    fieldList.push(buttonPIIGroup[i]);
                }
            }
            else {
                var element = document.getElementById(buttonPIIGroup[i]);
                fieldList.push(buttonPIIGroup[i]);
                
                if (element.nodeName === 'INPUT') {
                   $('#' + buttonPIIGroup[i]).keyup(toggleClassName); 
                }
                else {
                   $('#' + buttonPIIGroup[i]).change(toggleClassName); 
                }
            }
        }
    };
    
    var toggleClassName = function(e) {
        if (hasEmptyFields()) {
            
	        $('#' + submitButtonId).toggleClass(enabledButtonClass, false);//remove
	        $('#' + submitButtonId).toggleClass(disabledButtonClass, true);//add
		}
	    else {
	        $('#' + submitButtonId).toggleClass(enabledButtonClass, true);//add
	        $('#' + submitButtonId).toggleClass(disabledButtonClass, false);//remove
        }
    };
    
    var hasEmptyFields = function(e) {
        for (var i=0, len=fieldList.length; i<len; i++) {
            var element = document.getElementById(fieldList[i]);
            if (element.nodeName === 'INPUT') {
               if (/^\s+$/.test(element.value) || element.value === "") {
                   return true;
               }
            }
            else {
               if (element.value === '') {
                   return true;
               }
            }
        }
        
        return false;
    };
    
    return {
        init: function() {
            //buttonPIIGroup is a global variable from the PII page
            if (typeof buttonPIIGroup !== 'undefined' && typeof jQuery !== 'undefined') {
               attachEventListeners(); 
               //trigger on load
               toggleClassName();
               //backup check, that runs every 300ms
               setInterval(function() {
                   if ($('#' + submitButtonId).hasClass(disabledButtonClass)) {
                       toggleClassName();
                   }
               }, 300);
            }
	    }
    };
}();


UIUtil.QualifyingQuestionsButtonToggler = function() {
    var nextButtonId = 'div_NEXT_BTN';
    var usCitizenDivId = 'div_USCITIZEN_01';
    var countryDivId = 'div_COUNTRY_01';
    var militaryBranchDivId = 'div_DDI_MILITARYBRANCH_01';
    var militaryBranchName = 'DDI_MILITARYBRANCH_01';
    var militaryAffiliateName = 'DDI_MILITARYAFFILIATE_01';
    var militaryAffiliateDivId = 'div_DDI_MILITARYBRANCH_01_options';
    var submitButtonId = 'page1Btn';
    var disabledButtonClass = 'submitBtnDisabled';
    var enabledButtonClass = 'submitBtnActive';
    var historyClass = 'historyLink';
    var backLinkId = 'backLink';
    var forwardLinkId = 'forwardLink';
        
    var elementSuffix = '_01';
    var defaultSelectLabel = 'Please select one:';
    
    var nameToQListIndexMap = {};
    var groupQuestionsFilledOutFlagMap = {};
    var qListGroupCopy = [];
    
    var getElementName = function(divIdGroup) {
        var elementName = divIdGroup.replace('div_', '');
        
        if (elementName.indexOf(elementSuffix) == -1 ) {
            elementName += elementSuffix;
        }
        
        return elementName;
    };
    
    var toggleClassName = function(param) {
        var divId = (typeof param === 'string') ? param : param.data.divIdGroup;
    
        if (hasEmptyFields(divId)) {
            $('#' + submitButtonId).toggleClass(enabledButtonClass, false);//remove
            $('#' + submitButtonId).toggleClass(disabledButtonClass, true);//add
        }
        else {
            $('#' + submitButtonId).toggleClass(enabledButtonClass, true);//add
            $('#' + submitButtonId).toggleClass(disabledButtonClass, false);//remove
        }
    };
    
    var attachQuestionListeners = function(divIdGroup) {

        var elementName = getElementName(divIdGroup);
        var element = $('form[name="form1"] *[name="'+ elementName + '"]');
        if (element[0].nodeName === 'INPUT') {
	        if (element.length > 1) {
	            for (var i=0, len=element.length; i<len; i++) {
		            $(element[i]).bind('click', {divIdGroup : divIdGroup}, toggleClassName);
	            }
	        }
	        else if (element[0].type === 'text') {
	            $(element[0]).bind('keyup', {divIdGroup : divIdGroup}, toggleClassName);
	        }
	    }
        //select element
	    else {
            $(element[0]).bind('change', {divIdGroup : divIdGroup}, toggleClassName);
            	    }
    };
    
    var skipField = function(fieldDiv) {
        return (fieldDiv === nextButtonId || (fieldDiv === countryDivId && document.getElementById(countryDivId).style.display === 'none') || (fieldDiv === militaryBranchDivId && document.getElementById(militaryAffiliateDivId).style.display === 'none'))
    };
    
    var hasEmptyFields = function(elementName) {
        var index = nameToQListIndexMap[elementName];
        //possible not to get an index on streamline version with dropdowns when checking empty fields
        if (typeof index === 'undefined') {
            return false;
        }
        
        var list = qListGroupCopy[index];
        for (var i=0, len=list.length; i<len; i++) {
            if (skipField(list[i])) {
                continue;
            }
            var elementName = getElementName(list[i]);
            var elements = $('form[name="form1"] *[name="'+ elementName + '"]');
	        if (elements[0].nodeName === 'INPUT') {
	            //radio button or checkbox 
		        if (elements.length > 1) {
		           var isAllUnChecked = true; 
		           for (var j=0, len2=elements.length; j<len2; j++) {
		               //check if there is unchecked field
		               if (elements[j].checked === true) {
		                  isAllUnChecked = false; 
		               }
		           }
		           
		           if (isAllUnChecked == true) {
		               
		               return true;
		           }
		        }
		        else if (elements[0].type === 'text') {
		            if (/^\s+$/.test(elements[0].value) || elements[0].value === "") {
		                return true;
		            }
		        }
		    }
	        //select element
		    else {
		        if (elements[0].value === '') {
	                return true;
		        }
		    }        }
        return false;
    };
    
    triggerToggle =  function(e) {
        var index;
        if (this.id === backLinkId) {
           index = curQ - 1; 
        }
        else {
           index = curQ + 1; 
        }
        toggleClassName(qListGroupCopy[index][0]);
    };
    
    return {
        init: function() {
            if (typeof jQuery === 'undefined') {
                return;
            }
            //copy list because we're going to manipulate it and we don't 
            //want to affect existing code
	        for (var k=0, len3=qListGroups.length; k<len3; k++) {
                qListGroupCopy[k] = qListGroups[k].slice();//use slice to make a true copy not a reference
	        }
    
            for (var i=0, len=qListGroupCopy.length; i<len; i++) {
               //check if there's a next button, if so we need to do toggling. 
               //the next button id is located at end of the array for each group
               if (qListGroupCopy[i][qListGroupCopy[i].length - 1] === nextButtonId) {
                  for (var j=0, len2=qListGroupCopy[i].length; j<len2; j++) {
                      var divName = qListGroupCopy[i][j];
                      nameToQListIndexMap[divName] = i;
                      if (divName !== nextButtonId) {
		                  
		                  //handle special cases for military affiliation and us citizenship
		                  if (divName === usCitizenDivId) {
			                  attachQuestionListeners(divName);
			                  qListGroupCopy[i].push(countryDivId);
		                      nameToQListIndexMap[countryDivId] = i;
			                  attachQuestionListeners(countryDivId);
		                      
		                  }
		                  else if (divName === militaryBranchDivId) {
			                  attachQuestionListeners(divName);
			                  qListGroupCopy[i].push(militaryAffiliateName);
		                      nameToQListIndexMap[militaryAffiliateName] = i;
			                  attachQuestionListeners(militaryAffiliateName);
		                  }
		                  else {
			                  attachQuestionListeners(divName);
		                  }
                      }
                  }
               }
            }//end of for loop
            
            //attach listeners for back and forward link and refresh
            $('.' + historyClass).click(triggerToggle);
            
            this.doToggle();
            
            //backup check, that runs every 300ms
            setInterval(function() {
                if ($('#' + submitButtonId).hasClass(disabledButtonClass)) {
                    UIUtil.QualifyingQuestionsButtonToggler.doToggle();
                }
            }, 300);
	    },
	    doToggle: function() {
	       toggleClassName(qListGroupCopy[curQ][0]); 
	    }
    };
}();

var DDI = DDI || {};

DDI.SubmitButtonHandler = function() {
    var disabledButtonClass = 'submitBtnDisabled';
    return {
        processContinue: function(event, submitFunction, param) {
            var event = event || window.event;
            
            if (ConfigChecker.isButtonTogglingEnabled()) {
                if (param.className !== disabledButtonClass) {
                    submitFunction.call(this, param); 
                    UIUtil.QualifyingQuestionsButtonToggler.doToggle();
                    //if we're doing splash
                    if (qListGroups[1].length > 1) {
	                    DDI.MessagePicker.toggleQualifyingPageMessages();
                    }
                }
            }
            else {
                submitFunction.call(this, param); 
            }
           
            return false;
        },
        processSubmit: function(event, form, param) {
            if (ConfigChecker.isButtonTogglingEnabled()) {
                if (param.className !== disabledButtonClass) {
                    if (validateForm(form)) {
                    	submitForm(form);
                    }
                }
            }
            else {
                if (validateForm(form)) {
                	submitForm(form);
                }
            }
            
            return false;
        }
    };
}();

DDI.MessagePicker = function() {
    
    var matchLogoClass = 'match-logo';
    var reMatchLogoContainerId = 'preMatchedSchoolLogos';
    var rejectSchoolsInputId = 'rejectedSchoolsNum';
    
    var matchHeadlineSingularId = 'matchHeadlineSingular';
    var matchSubheadlineSingularId = 'matchSubheadlineSingular';
    var matchHeadlinePluralId = 'matchHeadlinePlural';
    var matchSubheadlinePluralId = 'matchSubheadlinePlural';
    var reMatchHeadlineSingularId = 'reMatchHeadlineSingular';
    var reMatchSubheadlineSingularId = 'reMatchSubheadlineSingular';
    var reMatchHeadlinePluralId = 'reMatchHeadlinePlural';
    var reMatchSubheadlinePluralId = 'reMatchSubheadlinePlural';
    var rejectHeadlineSingularId = 'rejectHeadlineSingular';
    var rejectSubheadlineSingularId = 'rejectSubheadlineSingular';
    var rejectHeadlinePluralId = 'rejectHeadlinePlural';
    var rejectSubheadlinePluralId = 'rejectSubheadlinePlural';
    var matchCTASingularId = 'matchCTASingular';
    var matchCTAPluralId = 'matchCTAPlural';
    var reMatchCTASingularId = 'reMatchCTASingular';
    var reMatchCTAPluralId = 'reMatchCTAPlural';
    var rejectCTASingularId = 'rejectCTASingular';
    var rejectCTAPlurasId = 'rejectCTAPluras';
    var headline1Id = 'headline1';
    var subheadline1Id = 'subheadline1';
    var headline2Id = 'headline2';
    var subheadline2Id = 'subheadline2';
    var ctaText1Id = 'ctaText1';
    var ctaText2Id = 'ctaText2';
    var sidebar1Id = 'sidebar1';
    var sidebar2Id = 'sidebar2';
    
    return {
        processMatchPageMessages: function() {
            if(isRematchPage()) {
                
                var rejectedInput = document.getElementById(rejectSchoolsInputId);
                
                if (rejectedInput == null) {
                    
                    var logos = $('#' + reMatchLogoContainerId + ' li');
                    if (logos.length > 1) {
		                $("#" + reMatchHeadlinePluralId + ",#" + reMatchSubheadlinePluralId + ",#" + reMatchCTAPluralId).css("display", "");
                    }
                    else {
		                $("#" + reMatchHeadlineSingularId + ",#" + reMatchSubheadlineSingularId + ",#" + reMatchCTASingularId).css("display", "");
                    }
                }
                else {
                    if (+rejectedInput.value > 1) {
		                $("#" + rejectHeadlinePluralId + ",#" + rejectSubheadlinePluralId + ",#" + rejectCTAPlurasId).css("display", "");
                    }
                    else {
		                $("#" + rejectHeadlineSingularId + ",#" + rejectSubheadlineSingularId + ",#" + rejectCTASingularId).css("display", "");
                    }
                }
            }
            else if(!isRematchPage()) {
                var matchLogos = $('.' + matchLogoClass); 
                if (matchLogos.length > 1) {
	                $("#" + matchHeadlinePluralId + ",#" + matchSubheadlinePluralId + ",#" + matchCTAPluralId).css("display", "");
                }
                else {
	                $("#" + matchHeadlineSingularId + ",#" + matchSubheadlineSingularId + ",#" + matchCTASingularId).css("display", "");
                }
            }
        },
        toggleQualifyingPageMessages: function() {
            $("#" + headline1Id + ",#" + subheadline1Id + ",#" + ctaText1Id + ",#" + sidebar1Id).css("display", "none");
            
            $("#" + headline2Id + ",#" + subheadline2Id + ",#" + ctaText2Id + ",#" + sidebar2Id).css("display", "");
        }
    };
}();

ConfigChecker = function() {
    
    return {
        isButtonTogglingEnabled : function() {
            return (typeof enableButtonToggling !== 'undefined' && enableButtonToggling === true)
        },
        isToolTipEnabled : function() {
            return (typeof enableButtonToggling !== 'undefined' && enableTooltips === true)
        },
        isMessagePickerEnabled : function() {
            return (typeof enableMessagePicker !== 'undefined' && enableMessagePicker === true);
        },
        isRematchLogosEnabled: function() {
            return (typeof enableRematchLogos !== 'undefined' && enableRematchLogos === true);
        },
        isPopunderEnabled: function() {
            return (typeof showPopunder !== 'undefined' && showPopunder !== 'NONE');
        }
        
    };
}();
