﻿// JScript File

var WEB_CONTROL_ERROR_CSS_CLASS = 'WebControlError';
var LABEL_ERROR_CSS_CLASS = 'LabelControlError';

function AddCssClass(element, className) 
{    
    if (!ContainsCssClass(element, className)) 
    {
        if (element.className === '') 
        {
            element.className = className;
        }
        else 
        {
            element.className += ' ' + className;
        }
    }
}

function ContainsCssClass(element, className) 
{
   var classNames = element.className.split(' ');
   for (var index = 0; index < classNames.length; index++)
   {
      if (classNames[index] == className) return true;
   }
   
   return false;
}

function RemoveCssClass(element, className) 
{    
    var currentClassName = ' ' + element.className + ' ';
    var index = currentClassName.indexOf(' ' + className + ' ');
    if (index >= 0) 
    {
        element.className = TrimString(currentClassName.substr(0, index) + ' ' + currentClassName.substring(index + className.length + 1, currentClassName.length));
    }
}

function AddOrRemoveCssClass(condition, element, className, onlyRemoveError)
{
   if (condition)
      AddCssClass(element, className);
   else
      RemoveCssClass(element, className);
}

function IsNumeric(str)
{ 
   str=str.replace(/^\s+|\s+$/g, '') ;
   if((str.length == 1 && str.match(/^\d+$/g)) || ((str.length > 1) && str.match(/^[-]{0,1}\d*[.]{0,1}\d*$/g))) return true;
   return false; 
}

function TrimString(str)
{
   var _ret = str.replace(/^\s+|\s+$/g, ''); 
   return _ret.replace(/^(\&nbsp\;)+|(\&nbsp\;)+$/g, '');
}

function AddError(condition, controlToValidateId, controlLabelId, panelErrorId, errorLabelId, errorMessage, onlyRemoveError)
{
   var controlToValidate = document.getElementById(controlToValidateId);
   var panelError = document.getElementById(panelErrorId);
   var labelError = document.getElementById(errorLabelId);
   var controlLabel = document.getElementById(controlLabelId);
   
   if (controlToValidate != null) 
   {
      if (!condition || (condition && !onlyRemoveError)) AddOrRemoveCssClass(condition, controlToValidate, WEB_CONTROL_ERROR_CSS_CLASS, onlyRemoveError);
   }
   if (controlLabel != null)
   {
      if (!condition || (condition && !onlyRemoveError)) AddOrRemoveCssClass(condition, controlLabel, LABEL_ERROR_CSS_CLASS, onlyRemoveError);
   }
   if (!condition || (condition && !onlyRemoveError)) AddOrRemoveCssClass(condition, labelError, LABEL_ERROR_CSS_CLASS, onlyRemoveError);
   
   var previousDisplayMode = panelError.style.display;
   panelError.style.display = (((condition && !onlyRemoveError) || (previousDisplayMode == "block" && condition)) ? "block" : "none");
   labelError.innerHTML = (((condition && !onlyRemoveError) || (previousDisplayMode == "block" && condition)) ? errorMessage : "");
   
   return condition;
}

function ValidateTextBoxNotEmpty(labelId, textBoxId, labelErrorId, panelErrorId, errorMessage, onlyRemoveError)
{
   var textBox = document.getElementById(textBoxId);
   var condition = (textBox.value == null) || (TrimString(textBox.value) == "");
   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
}

function ValidateDropDownNotEmpty(labelId, panelDropDownId, labelErrorId, panelErrorId, errorMessage, dropDownId, onlyRemoveError)
{
   var dropDown = document.getElementById(dropDownId);
   var condition = (dropDown.value == null) || (TrimString(dropDown.value) == "");
   return !AddError(condition, panelDropDownId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
}

function ValidateRegion(labelId, panelDropDownId, labelErrorId, panelErrorId, errorMessage, countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError)
{
   var countryDropDown = document.getElementById(countryDropDownId);
   var regionDropDown = document.getElementById(regionDropDownId);
   var regionTextBox = document.getElementById(regionTextBoxId);
   var condition ;
   if(TrimString(countryDropDown.value) == "United States")
   {
      condition = ((regionDropDown.value == null) || (TrimString(regionDropDown.value) == ""));
      return !AddError(condition, panelDropDownId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
   }
   else
   {
      condition = (regionTextBox.value == null) || (TrimString(regionTextBox.value) == "");
      return !AddError(condition, regionTextBoxId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError); 
   }
}

function ChangeStatesVisibility(dropCountryId, dropRegionId, textBoxRegionId)
{
   var dropCountry = document.getElementById(dropCountryId);
   var isUsaSelected = (dropCountry.value == 'United States');
   
   document.getElementById(dropRegionId).style.display = (isUsaSelected ? "block" : "none");
   document.getElementById(textBoxRegionId).style.display = (!isUsaSelected ? "block" : "none");
   
   return false;
}

function ValidateMail(labelId, textBoxId, labelErrorId, panelErrorId, errorMessage, errorMessage2, onlyRemoveError)
{
	var mailTextBox = document.getElementById(textBoxId);
	var filter  = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;	
	var condition = !filter.test(mailTextBox.value)
	var condition2 = (mailTextBox.value == null) || (TrimString(mailTextBox.value) == "");
	if(condition2)
	   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
	else if(condition)
	   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage2, onlyRemoveError);
	else
	   return !AddError(false, textBoxId, labelId, panelErrorId, labelErrorId, "", false);
}

function ValidatePassword(labelId, textBoxId, labelErrorId, panelErrorId, labelId2, textBoxId2, labelErrorId2, panelErrorId2, errorMessage, errorMessage2, errorMessage3, onlyRemoveError)
{
	var passTextBox = document.getElementById(textBoxId);
	var passTextBox2 = document.getElementById(textBoxId2);
	var value1 = passTextBox.value;
	var value2 = passTextBox2.value;
	var condition = (passTextBox.value == null);
	var condition2 = (passTextBox.value != null) && (TrimString(passTextBox.value) != "") && (value1.length <=7);
	var condition3 = (passTextBox.value != null) && (TrimString(passTextBox.value) != "") && (value1 != value2);
	if(condition)
	   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
	else if(condition2)
	{
	   var val21 = !AddError(condition2, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage2, onlyRemoveError);
	   var val22 = !AddError(condition2, textBoxId2, labelId2, panelErrorId2, labelErrorId2, errorMessage2, onlyRemoveError);
	   return (val21 && val22);
	}
	else if(condition3)
	{
	   var val31 = !AddError(condition3, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage3, onlyRemoveError);
	   var val32 = !AddError(condition3, textBoxId2, labelId2, panelErrorId2, labelErrorId2, errorMessage3, onlyRemoveError);
	   return (val31 && val32);
	}
	else
	{
	   var val41 = !AddError(false, textBoxId, labelId, panelErrorId, labelErrorId, "", false);
	   var val42 = !AddError(false, textBoxId2, labelId2, panelErrorId2, labelErrorId2, "", false);
	   return (val41 && val42);
	}
}

function ValidateRadioButton(radioButtonListId, radioButtonListLabelErrorId, radioButtonListPanelErrorId, errorMessage, onlyRemoveError)
{
	var condition = true;
	var radioButtonList = document.getElementById(radioButtonListId);
	for (i = 0; i < radioButtonList.childNodes.length; i++)
	{
      if (TrimString(radioButtonList.childNodes[i].tagName) == "INPUT")
         if(radioButtonList.childNodes[i].checked)
         {
	         condition=false;
	         break;
	      }
	}
	return !AddError(condition, radioButtonListId, null, radioButtonListPanelErrorId, radioButtonListLabelErrorId, errorMessage, onlyRemoveError);
}

function IsValidDate(textBoxId, allowOnlyBeforeCurrentYear)
{
   var dateTextBox = document.getElementById(textBoxId);
   var dateResult = new Date();
   
   var dateValue = dateTextBox.value;
   if (dateValue.length != 10) return null;
   
   var values = dateValue.split("/");
   if (values.length != 3) return null;
   
   if (values[0].length != 2 || values[1].length != 2 || values[2].length != 4) return null;
   if (!IsNumeric(values[0]) || !IsNumeric(values[1]) || !IsNumeric(values[2])) return null;
   
   var monthValue = parseInt(values[0], 10);
   var dayValue = parseInt(values[1], 10);
   var yearValue = parseInt(values[2], 10);
   
   if (monthValue <= 0 || monthValue > 12) return null;
   if (dayValue <= 0 || dayValue > 31) return null;
   if (yearValue <= 0 || (allowOnlyBeforeCurrentYear && yearValue >= dateResult.getFullYear())) return null;
   
   switch (monthValue)
   {
      case 4:
      case 6:
      case 9:
      case 11:
         if (monthValue > 30) return null;
         break;
      case 2:
         var isBisectYear = ((yearValue % 4) == 0);
         if ((isBisectYear && dayValue > 29) || (!isBisectYear && dayValue > 28)) return null;
         break;
   }
   
   dateResult = new Date(yearValue, monthValue - 1, dayValue);
   
   return dateResult;
}

function ValidateDate(labelId, textBoxId, labelErrorId, panelErrorId, errorMessage, errorMessage2, onlyOlderThanThreeYears, onlyRemoveError)
{   
	var dateTextBox = document.getElementById(textBoxId);
	//var filter  = /^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$/;	
	//var condition = !filter.test(dateTextBox.value)
	var dateValue = IsValidDate(textBoxId, true);
	var currentDate = new Date();
	currentDate.setFullYear(currentDate.getFullYear() - 3);
	var condition = (dateValue == null);
	var condition2 = (dateTextBox.value == null) || (TrimString(dateTextBox.value) == "");
	if (condition2)
	   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
	else if (condition)
	   return !AddError(condition, textBoxId, labelId, panelErrorId, labelErrorId, errorMessage2, onlyRemoveError);
	else if (onlyOlderThanThreeYears && dateValue > currentDate)
	   return !AddError(true, textBoxId, labelId, panelErrorId, labelErrorId, "Applicant must be at least three years old", onlyRemoveError)
	else
	   return !AddError(false, textBoxId, labelId, panelErrorId, labelErrorId, "", false);
}

function ValidateFinancialResourcesFileUpload(fileUploadId, radioButtonByMailId, radioButtonAttachedId, panelErrorId, labelErrorId, panelFiles, onlyRemoveError)
{
   var errorMessage = "Select at least one option for financial resources";
   var condition=true;
	var radioButtonByMail = document.getElementById(radioButtonByMailId);
	var radioButtonAttached = document.getElementById(radioButtonAttachedId);
	var fileUpload = document.getElementById(fileUploadId);
	var isFileUploadEmpty = (fileUpload.value == null || fileUpload.value == "");
	
	if(!radioButtonByMail.checked && !radioButtonAttached.checked)
	   return !AddError(true, "", "", panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
	if(radioButtonByMail.checked)
	   return !AddError(false, "", "", panelErrorId, labelErrorId, "", onlyRemoveError);
	if(radioButtonAttached.checked)
	   return !AddError(!PanelFilesExists(panelFiles) && isFileUploadEmpty && !onlyRemoveError, "", "", panelErrorId, labelErrorId, "Please select a file for financial resources", onlyRemoveError);
}

function ValidateMusicSkillFileUpload(radioButtonByMailId, radioButtonAttachedId, panelErrorId, labelErrorId, nrDoc, panelFiles, onlyRemoveError)
{
	var radioButtonByMail = document.getElementById(radioButtonByMailId);
	var radioButtonAttached = document.getElementById(radioButtonAttachedId);
	var errorMessage = "Select at least one option for music skill evaluation";
	
	if(!radioButtonByMail.checked && !radioButtonAttached.checked)
	   return !AddError(true, "", "", panelErrorId, labelErrorId, errorMessage, onlyRemoveError);
	if(radioButtonByMail.checked)
	   return !AddError(false, "", "", panelErrorId, labelErrorId, "", onlyRemoveError);
   if(radioButtonAttached.checked)
      return ValidateReferenceFiles(nrDoc, panelErrorId, labelErrorId, panelFiles, onlyRemoveError);
}

function ValidateReferenceFiles(nrDoc, panelErrorMusicFileId, labelErrorMusicFileId, panelFiles, onlyRemoveError)
{
   var nr = parseInt(document.getElementById(nrDoc).value);   
   
   return !AddError(!PanelFilesExists(panelFiles) && nr<=0 && !onlyRemoveError, "", "", panelErrorMusicFileId, labelErrorMusicFileId, "'Reference File' field is required", onlyRemoveError);
}

function IsEntireFormValid(applicantInformationControls, cosignerControls, careerGoalsControls, 
   instrumentNeedsControls, musicSkillsControls, financialResourcesControls, performanceControls, 
   additionalInformationControls, applicationFeeControls, scholarshipApplicationControls, 
   buttonSubmitId, webControlErrorCssClass, labelErrorCssClass)
{
   var isValid = true;
   
   WEB_CONTROL_ERROR_CSS_CLASS = webControlErrorCssClass;
   LABEL_ERROR_CSS_CLASS = labelErrorCssClass;
   
   if (applicantInformationControls)
      isValid = IsApplicantInformationValid(applicantInformationControls) && isValid;
      
   if (cosignerControls)
      isValid = IsCosignerValid(cosignerControls, applicantInformationControls[40]) && isValid;
   
   if (careerGoalsControls)
      isValid = IsCareerGoalsValid(careerGoalsControls) && isValid;
   
   if (instrumentNeedsControls)
      isValid = IsInstrumentNeedsValid(instrumentNeedsControls) && isValid;
   
   if (musicSkillsControls)
      isValid = IsMusicSkillsValid(musicSkillsControls) && isValid;
   
   if (financialResourcesControls)
      isValid = IsFinancialResourcesValid(financialResourcesControls) && isValid;
   
   if (performanceControls)
      isValid = IsPerformanceValid(performanceControls) && isValid;
   
   if (additionalInformationControls)
      isValid = IsAdditionalInfoValid(additionalInformationControls) && isValid;
   
   if (applicationFeeControls)
      isValid = IsApplicationFeeValid(applicationFeeControls) && isValid;
   
   SetErrorLabel(scholarshipApplicationControls, isValid);
   
   if (isValid) DisableSubmitButton(buttonSubmitId);
   
   return isValid;
}

function DisableSubmitButton(buttonSubmitId)
{
    var buttonSubmit = document.getElementById(buttonSubmitId);
    buttonSubmit.style["display"] = "none";
    //buttonSubmit.disabled = true;
}

function IsApplicantInformationValid(applicantInformationControls)
{
   var firstNameLabelId = applicantInformationControls[0];
   var firstNameTextBoxId = applicantInformationControls[1];
   var firstNameLabelErrorId = applicantInformationControls[2];
   var firstNamePanelErrorId = applicantInformationControls[3];
   var lastNameLabelId = applicantInformationControls[4];
   var lastNameTextBoxId = applicantInformationControls[5];
   var lastNameLabelErrorId = applicantInformationControls[6];
   var lastNamePanelErrorId = applicantInformationControls[7];
   var addressLabelId = applicantInformationControls[8];
   var addressTextBoxId = applicantInformationControls[9];
   var addressLabelErrorId = applicantInformationControls[10];
   var addressPanelErrorId = applicantInformationControls[11];
   var cityLabelId = applicantInformationControls[12];
   var cityTextBoxId = applicantInformationControls[13];
   var cityLabelErrorId = applicantInformationControls[14];
   var cityPanelErrorId = applicantInformationControls[15];
   var countryLabelId = applicantInformationControls[16];
   var countryPanelId = applicantInformationControls[17];
   var countryLabelErrorId = applicantInformationControls[18];
   var countryPanelErrorId = applicantInformationControls[19];
   var countryDropDownId = applicantInformationControls[20];
   var regionLabelId = applicantInformationControls[21];
   var regionPanelId = applicantInformationControls[22];
   var regionLabelErrorId = applicantInformationControls[23];
   var regionPanelErrorId = applicantInformationControls[24];
   var regionDropDownId = applicantInformationControls[25];
   var regionTextBoxId = applicantInformationControls[26];
   var postCodeLabelId = applicantInformationControls[27];
   var postCodeTextBoxId = applicantInformationControls[28];
   var postCodeLabelErrorId = applicantInformationControls[29];
   var postCodePanelErrorId = applicantInformationControls[30];
   var telNumberLabelId = applicantInformationControls[31];
   var telNumberTextBoxId = applicantInformationControls[32];
   var telNumberLabelErrorId = applicantInformationControls[33];
   var telNumberPanelErrorId = applicantInformationControls[34];
   var emailLabelId = applicantInformationControls[35];
   var emailTextBoxId = applicantInformationControls[36];
   var emailLabelErrorId = applicantInformationControls[37];
   var emailPanelErrorId = applicantInformationControls[38];
   var dateOfBirthLabelId = applicantInformationControls[39];
   var dateOfBirthTextBoxId = applicantInformationControls[40];
   var dateOfBirthLabelErrorId = applicantInformationControls[41];
   var dateOfBirthPanelErrorId = applicantInformationControls[42];
   
   var isValid = true;
   
   isValid = ValidateApplicantInformationFirstName(firstNameLabelId, firstNameTextBoxId, firstNameLabelErrorId, firstNamePanelErrorId, false) && isValid;
   isValid = ValidateApplicantInformationLastName(lastNameLabelId, lastNameTextBoxId, lastNameLabelErrorId, lastNamePanelErrorId, false) && isValid;   
   isValid = ValidateApplicantInformationAddress(addressLabelId, addressTextBoxId, addressLabelErrorId, addressPanelErrorId, false) && isValid;   
   isValid = ValidateApplicantInformationCity(cityLabelId, cityTextBoxId, cityLabelErrorId, cityPanelErrorId, false) && isValid;
   isValid = ValidateApplicantInformationCountry(countryLabelId, countryPanelId, countryLabelErrorId, countryPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, false) && isValid;
   isValid = ValidateApplicantInformationRegion(regionLabelId, regionPanelId, regionLabelErrorId, regionPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, false) && isValid;   
   isValid = ValidateApplicantInformationPostCode(postCodeLabelId, postCodeTextBoxId, postCodeLabelErrorId, postCodePanelErrorId, false) && isValid;
   isValid = ValidateApplicantInformationTelNumber(telNumberLabelId, telNumberTextBoxId, telNumberLabelErrorId, telNumberPanelErrorId, false) && isValid;
   isValid = ValidateApplicantInformationEmail(emailLabelId, emailTextBoxId, emailLabelErrorId, emailPanelErrorId, false) && isValid;
   isValid = ValidateApplicantInformationBirthDate(dateOfBirthLabelId, dateOfBirthTextBoxId, dateOfBirthLabelErrorId, dateOfBirthPanelErrorId, false) && isValid;

   return isValid;
}

function IsApplicantUnder21(textBoxApplicantBirthDateId)
{
   var currentDate = new Date();
   try
   {
      var dateTextBox = document.getElementById(textBoxApplicantBirthDateId);
      var birthDate = new Date(Date.parse(dateTextBox.value));
   }
   catch(e)
   {
      return false;
   }
   if((currentDate.getTime() - birthDate.getTime()) <= (21*365*24*3600*1000))
      return true;
   return false;
}

function IsCosignerValid(cosignerControls, textBoxApplicantBirthDateId)
{
   var cosingerNameLabelId = cosignerControls[0];
   var cosignerNameTextBoxId = cosignerControls[1];
   var cosignerNameLabelErrorId = cosignerControls[2];
   var cosignerNamePanelErrorId = cosignerControls[3];
   var cosignerAddressLabelId = cosignerControls[4];
   var cosignerAddressTextBoxId = cosignerControls[5];
   var cosignerAddressLabelErrorId = cosignerControls[6];
   var cosignerAddressPanelErrorId = cosignerControls[7];
   var cosignerTelNumberLabelId = cosignerControls[8];
   var cosignerTelNumberTextBoxId = cosignerControls[9];
   var cosignerTelNumberLabelErrorId = cosignerControls[10];
   var cosignerTelNumberPanelErrorId = cosignerControls[11];
   var cosignerEmailLabelId = cosignerControls[12];
   var cosignerEmailTextBoxId = cosignerControls[13];
   var cosignerEmailLabelErrorId = cosignerControls[14];
   var cosignerEmailPanelErrorId = cosignerControls[15];
   var cosignerRelationshipLabelId = cosignerControls[16];
   var cosignerRelationshipTextBoxId = cosignerControls[17];
   var cosignerRelationshipLabelErrorId = cosignerControls[18];
   var cosignerRelationshipPanelErrorId = cosignerControls[19];

   ClearCosignerErrors(cosignerControls);
   
   var isValid = true;
   if(!IsApplicantUnder21(textBoxApplicantBirthDateId))
   {
      return ValidateOver21CosignerEmail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, false);
   }
   
   isValid = ValidateCosignerName(cosingerNameLabelId, cosignerNameTextBoxId, cosignerNameLabelErrorId, cosignerNamePanelErrorId, false) && isValid;
   isValid = ValidateCosignerAddress(cosignerAddressLabelId, cosignerAddressTextBoxId, cosignerAddressLabelErrorId, cosignerAddressPanelErrorId, false) && isValid;
   isValid = ValidateCosignerTelNumber(cosignerTelNumberLabelId, cosignerTelNumberTextBoxId, cosignerTelNumberLabelErrorId, cosignerTelNumberPanelErrorId, false) && isValid;
   isValid = ValidateCosignerEmail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, textBoxApplicantBirthDateId, false) && isValid;
   isValid = ValidateCosignerRelationship(cosignerRelationshipLabelId, cosignerRelationshipTextBoxId, cosignerRelationshipLabelErrorId, cosignerRelationshipPanelErrorId, false) && isValid;
   
   return isValid;
}

function IsCareerGoalsValid(careerGoalsControls)
{
   var careerGoalsTextBoxId = careerGoalsControls[0];
   var careerGoalsLabelErrorId = careerGoalsControls[1];
   var careerGoalsPanelErrorId = careerGoalsControls[2];
   
   var isValid = true;
   
   isValid = ValidateCareerGoals(careerGoalsTextBoxId, careerGoalsLabelErrorId, careerGoalsPanelErrorId, false);
   
   return isValid;
}

function IsInstrumentNeedsValid(instrumentNeedsControls)
{
   var radioButtonListInstrumentsId = instrumentNeedsControls[0];
   var radioButtonListInstrumentsLabelErrorId = instrumentNeedsControls[1];
   var radioButtonListInstrumentsPanelErrorId = instrumentNeedsControls[2];
   var textBoxInstrumentNeedsId = instrumentNeedsControls[3];
   var textBoxInstrumentNeedsLabelErrorId = instrumentNeedsControls[4];
   var textBoxInstrumentNeedsPanelErrorId = instrumentNeedsControls[5];  
 
   var isValid = true;
   
   isValid = ValidateInstrumentNeedsInstrumentsList(radioButtonListInstrumentsId, radioButtonListInstrumentsLabelErrorId, radioButtonListInstrumentsPanelErrorId, false) && isValid;
   isValid = ValidateInstrumentNeedsTextBox(textBoxInstrumentNeedsId, textBoxInstrumentNeedsLabelErrorId, textBoxInstrumentNeedsPanelErrorId, false) && isValid;
   
   return isValid;
}

function IsMusicSkillsValid(musicSkillsControls)
{
   var radioButtonByMailId = musicSkillsControls[0];
   var radioButtonAttachedid = musicSkillsControls[1];
   var panelErrorId = musicSkillsControls[2];
   var labelErrorId = musicSkillsControls[3];
   var nrDocs = musicSkillsControls[4];
   var panelFiles = musicSkillsControls[5];
   
   var isValid = true;
   
   isValid = ValidateMusicSkillFileUpload(radioButtonByMailId, radioButtonAttachedid, panelErrorId, labelErrorId, nrDocs, panelFiles, false) && isValid;
   
   return isValid;
}

function IsFinancialResourcesValid(financialResourcesControls)
{
   var textBoxFinancialResourcesId = financialResourcesControls[0];
   var textBoxFinancialResourcesLabelErrorId = financialResourcesControls[1];
   var textBoxFinancialResourcesPanelErrorId = financialResourcesControls[2];
   var fileUploadFinancialResourcesId = financialResourcesControls[3];
   var fileUploadFinancialResourcesLabelErrorId = financialResourcesControls[4];
   var fileUploadFinancialResourcesPanelErrorId = financialResourcesControls[5];
   var radioButtonByMailId = financialResourcesControls[6];
   var radioButtonAttachedId = financialResourcesControls[7];
   var panelFiles = financialResourcesControls[8];
   
   AddError(false, textBoxFinancialResourcesId, "" , textBoxFinancialResourcesPanelErrorId, textBoxFinancialResourcesLabelErrorId, "", false);
   AddError(false, "" , "" , fileUploadFinancialResourcesPanelErrorId, fileUploadFinancialResourcesLabelErrorId, "", false);
   
   var isValid = true;
   
   isValid = ValidateFinancialResourcesTextBox(textBoxFinancialResourcesId, textBoxFinancialResourcesLabelErrorId, textBoxFinancialResourcesPanelErrorId, false) && isValid;
   isValid = ValidateFinancialResourcesFileUpload(fileUploadFinancialResourcesId, radioButtonByMailId,radioButtonAttachedId, fileUploadFinancialResourcesPanelErrorId, fileUploadFinancialResourcesLabelErrorId, panelFiles, false) && isValid;
   
   return isValid;
}

function IsPerformanceValid(performanceControls)
{
   var textBoxPerformanceId = performanceControls[0];
   var textBoxPerformanceLabelErrorId = performanceControls[1];
   var textBoxPerformancePanelErrorId = performanceControls[2];
   var panelErrorMusicFileId = performanceControls[3];
   var labelErrorMusicFileId = performanceControls[4];
   var hiddenTextNumberOfUploadsId = performanceControls[5];
   var iframeId = performanceControls[6];
   
   var isValid = true;
   
   isValid = ValidatePerformanceTextBox(textBoxPerformanceId, textBoxPerformanceLabelErrorId, textBoxPerformancePanelErrorId, false) && isValid;
   isValid = ValidateMusicFiles(hiddenTextNumberOfUploadsId, iframeId, panelErrorMusicFileId, labelErrorMusicFileId, false) && isValid;
   
   return isValid;
}

function ValidateMusicFiles(hiddenTextNumberOfUploadsId, iframeId, panelErrorMusicFileId, labelErrorMusicFileId, onlyRemoveError)
{
   var condition = false;
   var numberOfUploads = document.getElementById(hiddenTextNumberOfUploadsId);
   if(!numberOfUploads || numberOfUploads.value == "0" || numberOfUploads.value == "") condition = true;
   
   return !AddError( condition && !onlyRemoveError, iframeId, "", panelErrorMusicFileId, labelErrorMusicFileId, "'Music file' field is required", onlyRemoveError);
}

function IsAdditionalInfoValid(additionalInformationControls)
{
   var isValid = true;
   //does not need validation
   return isValid;
}

function IsApplicationFeeValid(applicationFeeControls)
{
   var firstNameLabelId = applicationFeeControls[0];
   var firstNameTextBoxId = applicationFeeControls[1];
   var firstNameLabelErrorId = applicationFeeControls[2];
   var firstNamePanelErrorId = applicationFeeControls[3];
   var lastNameLabelId = applicationFeeControls[4];
   var lastNameTextBoxId = applicationFeeControls[5];
   var lastNameLabelErrorId = applicationFeeControls[6];
   var lastNamePanelErrorId = applicationFeeControls[7];
   var cardNumberLabelId = applicationFeeControls[8];
   var cardNumberTextBoxId = applicationFeeControls[9];
   var cardNumberLabelErrorId = applicationFeeControls[10];
   var cardNumberPanelErrorId = applicationFeeControls[11];
   var cardExpirationLabelId = applicationFeeControls[12];
   var cardExpirationMonthTextBoxId = applicationFeeControls[13];
   var cardExpirationYearTextBoxId = applicationFeeControls[14];
   var cardExpirationLabelErrorId = applicationFeeControls[15];
   var cardExpirationPanelErrorId = applicationFeeControls[16];
   var cardSecurityCodeLabelId = applicationFeeControls[17];
   var cardSecurityCodeTextBoxId = applicationFeeControls[18];
   var cardSecurityCodeLabelErrorId = applicationFeeControls[19];
   var cardSecurityCodePanelErrorId = applicationFeeControls[20];
   var billingAddressStreetLabelId = applicationFeeControls[21];
   var billingAddressStreetTextBoxId = applicationFeeControls[22];
   var billingAddressStreetLabelErrorId = applicationFeeControls[23];
   var billingAddressStreetPanelErrorId = applicationFeeControls[24];
   var billingAddressCityLabelId = applicationFeeControls[25];
   var billingAddressCityTextBoxId = applicationFeeControls[26];
   var billingAddressCityLabelErrorId = applicationFeeControls[27];
   var billingAddressCityPanelErrorId = applicationFeeControls[28];
   var billingAddressCountryLabelId = applicationFeeControls[29];
   var billingAddressCountryDropDownId = applicationFeeControls[30];
   var billingAddressCountryPanelId = applicationFeeControls[31];
   var billingAddressCountryLabelErrorId = applicationFeeControls[32];
   var billingAddressCountryPanelErrorId = applicationFeeControls[33];
   var billingAddressRegionLabelId = applicationFeeControls[34];
   var billingAddressRegionDropDownId = applicationFeeControls[35];
   var billingAddressRegionPanelId = applicationFeeControls[36];
   var billingAddressRegionLabelErrorId = applicationFeeControls[37];
   var billingAddressRegionPanelErrorId = applicationFeeControls[38];
   var billingAddressRegionTextBoxId = applicationFeeControls[39];
   var billingAddressPostCodeLableId = applicationFeeControls[40];
   var billingAddressPostCodeTextBoxId =  applicationFeeControls[41];
   var billingAddressPostCodeLabelErrorId = applicationFeeControls[42];
   var billingAddressPostCodePanelErrorId = applicationFeeControls[43];
   var cardTypeLabelId = applicationFeeControls[44];
   var cardTypeDropDownId = applicationFeeControls[45];
   var cardTypePanelId = applicationFeeControls[46];
   var cardTypeLabelErrorId = applicationFeeControls[47];
   var cardTypePanelErrorId = applicationFeeControls[48];
   var labelMonthForExpirationId = applicationFeeControls[49];
   var labelYearForExpirationId = applicationFeeControls[50];

   var isValid = true;
      
   isValid = ValidateApplicationFeeFirstNameTextBox(firstNameLabelId, firstNameTextBoxId,firstNameLabelErrorId, firstNamePanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeLastNameTextBox(lastNameLabelId, lastNameTextBoxId,lastNameLabelErrorId,lastNamePanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeCardNumberTextBox(cardNumberLabelId, cardNumberTextBoxId,cardNumberLabelErrorId, cardNumberPanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeExpirationTextBoxes(cardExpirationLabelId, labelMonthForExpirationId, cardExpirationMonthTextBoxId, labelYearForExpirationId, cardExpirationYearTextBoxId, cardExpirationLabelErrorId, cardExpirationPanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeStreetTextBox(billingAddressStreetLabelId, billingAddressStreetTextBoxId, billingAddressStreetLabelErrorId, billingAddressStreetPanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeCityTextBox(billingAddressCityLabelId, billingAddressCityTextBoxId, billingAddressCityLabelErrorId, billingAddressCityPanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeCountry(billingAddressCountryLabelId, billingAddressCountryPanelId, billingAddressCountryLabelErrorId, billingAddressCountryPanelErrorId, billingAddressCountryDropDownId, billingAddressRegionDropDownId, billingAddressRegionTextBoxId, false) && isValid;
   isValid = ValidateApplicationFeePostCodeTextBox(billingAddressPostCodeLableId, billingAddressPostCodeTextBoxId, billingAddressPostCodeLabelErrorId, billingAddressPostCodePanelErrorId, false) && isValid;
   isValid = ValidateApplicationFeeCardType(cardTypeLabelId, cardTypePanelId, cardTypeLabelErrorId, cardTypePanelErrorId, cardTypeDropDownId, false) && isValid;
   isValid = ValidateApplicationFeeRegion(billingAddressRegionLabelId, billingAddressRegionPanelId, billingAddressRegionLabelErrorId, billingAddressRegionPanelErrorId, billingAddressCountryDropDownId, billingAddressRegionDropDownId, billingAddressRegionTextBoxId, false) && isValid;
   isValid = ValidateApplicationFeeSecurityCodeTextBox(cardSecurityCodeLabelId, cardSecurityCodeTextBoxId, cardSecurityCodeLabelErrorId, cardSecurityCodePanelErrorId, false) && isValid;
   return isValid;
}

function SetErrorLabel(scholarshipApplicationControls, isValid)
{
   var errorLabelId = scholarshipApplicationControls[0];
   var errorLabel = document.getElementById(errorLabelId); 
   if(!isValid)
   {
      var message = "There is a problem with your application.";
      message += "<br />Please review the application for error messages highlighted in red. Thank you.";
      errorLabel.innerHTML = message;
      errorLabel.style.display = "block";
   }
   else
   {
      errorLabel.innerHTML = "Updating...";
      errorLabel.style.display = "block";
   }   
   AddOrRemoveCssClass(!isValid, errorLabel, LABEL_ERROR_CSS_CLASS, false);
}


/*========== BEGIN REGION FOR SEPARATE METHODS ============*/

function ValidateApplicantInformationFirstName(firstNameLabelId, firstNameTextBoxId, firstNameLabelErrorId, firstNamePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(firstNameLabelId, firstNameTextBoxId, firstNameLabelErrorId, firstNamePanelErrorId, "'First name' field is required", onlyRemoveError);
}

function ValidateApplicantInformationLastName(lastNameLabelId, lastNameTextBoxId, lastNameLabelErrorId, lastNamePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(lastNameLabelId, lastNameTextBoxId, lastNameLabelErrorId, lastNamePanelErrorId, "'Last name' field is required", onlyRemoveError);
}

function ValidateApplicantInformationAddress(addressLabelId, addressTextBoxId, addressLabelErrorId, addressPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(addressLabelId, addressTextBoxId, addressLabelErrorId, addressPanelErrorId, "'Address' field is required", onlyRemoveError);
}

function ValidateApplicantInformationCity(cityLabelId, cityTextBoxId, cityLabelErrorId, cityPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(cityLabelId, cityTextBoxId, cityLabelErrorId, cityPanelErrorId, "'City' field is required", onlyRemoveError);
}

function ValidateApplicantInformationCountry(countryLabelId, countryPanelId, countryLabelErrorId, countryPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError)
{
   if (onlyRemoveError) ChangeStatesVisibility(countryDropDownId, regionDropDownId, regionTextBoxId);
   return ValidateDropDownNotEmpty(countryLabelId, countryPanelId, countryLabelErrorId, countryPanelErrorId, "'Country' field is required", countryDropDownId, onlyRemoveError);
}

function ValidateApplicantInformationRegion(regionLabelId, regionPanelId, regionLabelErrorId, regionPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError)
{
   return ValidateRegion(regionLabelId, regionPanelId, regionLabelErrorId, regionPanelErrorId, "'State/Region' field is required", countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError);
}

function ValidateApplicantInformationPostCode(postCodeLabelId, postCodeTextBoxId, postCodeLabelErrorId, postCodePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(postCodeLabelId, postCodeTextBoxId, postCodeLabelErrorId, postCodePanelErrorId, "'Postcode' field is required", onlyRemoveError);
}

function ValidateApplicantInformationTelNumber(telNumberLabelId, telNumberTextBoxId, telNumberLabelErrorId, telNumberPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(telNumberLabelId, telNumberTextBoxId, telNumberLabelErrorId, telNumberPanelErrorId, "'Telephone Number' field is required", onlyRemoveError);
}

function ValidateApplicantInformationEmail(emailLabelId, emailTextBoxId, emailLabelErrorId, emailPanelErrorId, onlyRemoveError)
{
   return ValidateMail(emailLabelId, emailTextBoxId, emailLabelErrorId, emailPanelErrorId, "'E-mail address' field is required","Incorrect Email Address (the format should be similar to myaddress@somewebsite.com)", onlyRemoveError);
}

function ValidateApplicantInformationUserName(emailLabelId, emailTextBoxId, emailLabelErrorId, emailPanelErrorId, onlyRemoveError)
{
   return ValidateMail(emailLabelId, emailTextBoxId, emailLabelErrorId, emailPanelErrorId, "'Username' field is required","Incorrect username (the format should be similar to myaddress@somewebsite.com)", onlyRemoveError);
}

function ValidateUserPassword(labelId, textBoxId, labelErrorId, panelErrorId, labelId2, textBoxId2, labelErrorId2, panelErrorId2, onlyRemoveError)
{
   return ValidatePassword(labelId, textBoxId, labelErrorId, panelErrorId, labelId2, textBoxId2, labelErrorId2, panelErrorId2, "'Password' field is required", "'Password' field must must have minimum 8  characters ","'Password' field must be identic with 'Password Confirmation' field is required", onlyRemoveError);
}

function ValidateApplicantInformationBirthDate(dateOfBirthLabelId, dateOfBirthTextBoxId, dateOfBirthLabelErrorId, dateOfBirthPanelErrorId, onlyRemoveError)
{
   return ValidateDate(dateOfBirthLabelId, dateOfBirthTextBoxId, dateOfBirthLabelErrorId, dateOfBirthPanelErrorId, "'Date of birth' field is required", "Please format your date as specified (mm/dd/yyyy)", true, onlyRemoveError);   
}

function ClearCosignerErrors(cosignerControls)
{
   var cosingerNameLabelId = cosignerControls[0];
   var cosignerNameTextBoxId = cosignerControls[1];
   var cosignerNameLabelErrorId = cosignerControls[2];
   var cosignerNamePanelErrorId = cosignerControls[3];
   var cosignerAddressLabelId = cosignerControls[4];
   var cosignerAddressTextBoxId = cosignerControls[5];
   var cosignerAddressLabelErrorId = cosignerControls[6];
   var cosignerAddressPanelErrorId = cosignerControls[7];
   var cosignerTelNumberLabelId = cosignerControls[8];
   var cosignerTelNumberTextBoxId = cosignerControls[9];
   var cosignerTelNumberLabelErrorId = cosignerControls[10];
   var cosignerTelNumberPanelErrorId = cosignerControls[11];
   var cosignerEmailLabelId = cosignerControls[12];
   var cosignerEmailTextBoxId = cosignerControls[13];
   var cosignerEmailLabelErrorId = cosignerControls[14];
   var cosignerEmailPanelErrorId = cosignerControls[15];
   var cosignerRelationshipLabelId = cosignerControls[16];
   var cosignerRelationshipTextBoxId = cosignerControls[17];
   var cosignerRelationshipLabelErrorId = cosignerControls[18];
   var cosignerRelationshipPanelErrorId = cosignerControls[19];

   AddError(false, cosignerNameTextBoxId, cosingerNameLabelId, cosignerNamePanelErrorId, cosignerNameLabelErrorId, "", false);
   AddError(false, cosignerAddressTextBoxId, cosignerAddressLabelId, cosignerAddressPanelErrorId, cosignerAddressLabelErrorId, "", false);
   AddError(false, cosignerTelNumberTextBoxId, cosignerTelNumberLabelId, cosignerTelNumberPanelErrorId, cosignerTelNumberLabelErrorId, "", false);
   AddError(false, cosignerEmailTextBoxId, cosignerEmailLabelId, cosignerEmailPanelErrorId, cosignerEmailLabelErrorId, "", false);
   AddError(false, cosignerRelationshipTextBoxId, cosignerRelationshipLabelId, cosignerRelationshipPanelErrorId, cosignerRelationshipLabelErrorId, "", false);
}

function ValidateCosignerName(cosignerNameLabelId, cosignerNameTextBoxId, cosignerNameLabelErrorId, cosignerNamePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(cosignerNameLabelId, cosignerNameTextBoxId, cosignerNameLabelErrorId, cosignerNamePanelErrorId, "'Cosigner’s name' field is required", onlyRemoveError);
}

function ValidateCosignerAddress(cosignerAddressLabelId, cosignerAddressTextBoxId, cosignerAddressLabelErrorId, cosignerAddressPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(cosignerAddressLabelId, cosignerAddressTextBoxId, cosignerAddressLabelErrorId, cosignerAddressPanelErrorId, "'Cosigner’s address' field is required", onlyRemoveError);
}

function ValidateCosignerTelNumber(cosignerTelNumberLabelId, cosignerTelNumberTextBoxId, cosignerTelNumberLabelErrorId, cosignerTelNumberPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(cosignerTelNumberLabelId, cosignerTelNumberTextBoxId, cosignerTelNumberLabelErrorId, cosignerTelNumberPanelErrorId, "'Cosigner’s telephone number' field is required", onlyRemoveError);
}

function ValidateCosignerEmail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, textBoxApplicantBirthDateId, onlyRemoveError)
{
   if (!IsApplicantUnder21(textBoxApplicantBirthDateId))
      return ValidateOver21CosignerEmail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, onlyRemoveError);
   return ValidateMail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, "'Cosigner’s e-mail address ' field is required", "Please enter a valid email address", onlyRemoveError);
}

function ValidateCosignerRelationship(cosignerRelationshipLabelId, cosignerRelationshipTextBoxId, cosignerRelationshipLabelErrorId, cosignerRelationshipPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(cosignerRelationshipLabelId, cosignerRelationshipTextBoxId, cosignerRelationshipLabelErrorId, cosignerRelationshipPanelErrorId, "'Cosigner’s relationship to applicant' field is required", onlyRemoveError);
}
   
function ValidateOver21CosignerEmail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, onlyRemoveError)
{
   var isValid = true;
   var emailTextBox= document.getElementById(cosignerEmailTextBoxId);
   if(!((emailTextBox.value == null) || (TrimString(emailTextBox.value) == "")))
      isValid = ValidateMail(cosignerEmailLabelId, cosignerEmailTextBoxId, cosignerEmailLabelErrorId, cosignerEmailPanelErrorId, "'Cosigner’s e-mail address ' field is required", "Please enter a valid email address", onlyRemoveError) && isValid;
   else
      isValid = !AddError(false, cosignerEmailTextBoxId, cosignerEmailLabelId, cosignerEmailPanelErrorId, cosignerEmailLabelErrorId, "", onlyRemoveError) && isValid;
   return isValid;
}

function ValidateCareerGoals(careerGoalsTextBoxId, careerGoalsLabelErrorId, careerGoalsPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty("", careerGoalsTextBoxId, careerGoalsLabelErrorId, careerGoalsPanelErrorId, "'Career Goals' is a required field", onlyRemoveError);
}

function ValidateInstrumentNeedsInstrumentsList(radioButtonListInstrumentsId, radioButtonListInstrumentsLabelErrorId, radioButtonListInstrumentsPanelErrorId, onlyRemoveError)
{
   return ValidateRadioButton(radioButtonListInstrumentsId, radioButtonListInstrumentsLabelErrorId, radioButtonListInstrumentsPanelErrorId, "Please select an instrument", onlyRemoveError);
}

function ValidateInstrumentNeedsTextBox(textBoxInstrumentNeeds, textBoxInstrumentNeedsLabelErrorId, textBoxInstrumentNeedsPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty("", textBoxInstrumentNeeds, textBoxInstrumentNeedsLabelErrorId, textBoxInstrumentNeedsPanelErrorId, "'Instrument needs' field is required", onlyRemoveError);
}

function ValidateFinancialResourcesTextBox(textBoxFinancialResourcesId, textBoxFinancialResourcesLabelErrorId, textBoxFinancialResourcesPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty("", textBoxFinancialResourcesId, textBoxFinancialResourcesLabelErrorId, textBoxFinancialResourcesPanelErrorId, "'Financial resources' field is required", onlyRemoveError);
}

function ValidatePerformanceTextBox(textBoxPerformanceId,textBoxPerformanceLabelErrorId,textBoxPerformancePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty("", textBoxPerformanceId, textBoxPerformanceLabelErrorId, textBoxPerformancePanelErrorId, "'Performance describe' field is required", onlyRemoveError);
}

function ValidateApplicationFeeFirstNameTextBox(textBoxFirstNameLabelId, textBoxFirstNameId,textBoxFirstNameLabelErrorId,textBoxFirstNamePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxFirstNameLabelId, textBoxFirstNameId, textBoxFirstNameLabelErrorId, textBoxFirstNamePanelErrorId, "'First name' field is required", onlyRemoveError);
}

function ValidateApplicationFeeLastNameTextBox(textBoxLastNameLabelId, textBoxLastNameId,textBoxLastNameLabelErrorId,textBoxLastNamePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxLastNameLabelId, textBoxLastNameId, textBoxLastNameLabelErrorId, textBoxLastNamePanelErrorId, "'Last Name' field is required", onlyRemoveError);
}

function ValidateApplicationFeeCardNumberTextBox(textBoxCardNumberLabelId, textBoxCardNumberId,textBoxCardNumberLabelErrorId,textBoxCardNumberPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxCardNumberLabelId, textBoxCardNumberId, textBoxCardNumberLabelErrorId, textBoxCardNumberPanelErrorId, "'Card Number' field is required", onlyRemoveError);
}

function ValidateApplicationFeeExpirationTextBoxes(textBoxExpirationLabelId, labelMonthForExpirationId, textBoxExpirationMonthId, labelYearForExpirationId, textBoxExpirationYearId, textBoxExpirationLabelErrorId, textBoxExpirationPanelErrorId, onlyRemoveError)
{
   var isAllOk = true;
   var errorMessage = "'Expiration' fields are required";
   var textBoxMonth = document.getElementById(textBoxExpirationMonthId);
   var textBoxYear = document.getElementById(textBoxExpirationYearId);
   var labelMonth = document.getElementById(labelMonthForExpirationId);
   var labelYear = document.getElementById(labelYearForExpirationId);
   
   var textBoxesNotEmpty = (textBoxMonth.value != null) && (TrimString(textBoxMonth.value) != "");
   textBoxesNotEmpty = ((textBoxYear.value != null) && (TrimString(textBoxYear.value) != "")) && textBoxesNotEmpty;
   
   isAllOk = textBoxesNotEmpty && isAllOk;
   
   if (textBoxesNotEmpty)
   {      
      errorMessage = "Wrong format for 'Expiration' fields";
      var currentDate = new Date();
      var intMonthValue = parseInt(textBoxMonth.value, 10);
      var intYearValue = parseInt(textBoxYear.value, 10);
      var isMonthOk = IsNumeric(textBoxMonth.value) && !isNaN(intMonthValue) && (intMonthValue > 0) && (intMonthValue <= 12);            
      var isYearOk = IsNumeric(textBoxYear.value) && !isNaN(intYearValue);
            
      var isAllOk = isMonthOk && isYearOk && isAllOk;
      if (isAllOk)
      {
         errorMessage = "The card has already expired";
         isAllOk = (intYearValue == currentDate.getFullYear() && intMonthValue > currentDate.getMonth() + 1);
         isAllOk = isAllOk || (intYearValue > currentDate.getFullYear());
      }
      
   }
   
   AddError(!isAllOk, textBoxExpirationMonthId, textBoxExpirationLabelId, textBoxExpirationPanelErrorId, textBoxExpirationLabelErrorId, errorMessage, onlyRemoveError);
   AddError(!isAllOk, textBoxExpirationYearId, textBoxExpirationLabelId, textBoxExpirationPanelErrorId, textBoxExpirationLabelErrorId, errorMessage, onlyRemoveError);
   
   //if (!condition || (condition && !onlyRemoveError)) AddOrRemoveCssClass(condition, labelError, LABEL_ERROR_CSS_CLASS, onlyRemoveError);
   
   if (isAllOk || (!isAllOk && !onlyRemoveError)) AddOrRemoveCssClass(!isAllOk, labelMonth, LABEL_ERROR_CSS_CLASS, onlyRemoveError);
   if (isAllOk || (!isAllOk && !onlyRemoveError)) AddOrRemoveCssClass(!isAllOk, labelYear, LABEL_ERROR_CSS_CLASS, onlyRemoveError);
   
   return isAllOk;
}

function ValidateApplicationFeeStreetTextBox(textBoxStreetLabelId, textBoxStreetId, textBoxStreetLabelErrorId, textBoxStreetPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxStreetLabelId, textBoxStreetId, textBoxStreetLabelErrorId, textBoxStreetPanelErrorId, "'Street' field is required", onlyRemoveError);
}

function ValidateApplicationFeeCityTextBox(textBoxCityLabelId, textBoxCityId,textBoxCityLabelErrorId,textBoxCityPanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxCityLabelId, textBoxCityId, textBoxCityLabelErrorId, textBoxCityPanelErrorId, "'City' field is required", onlyRemoveError);
}

function ValidateApplicationFeeCountry(countryLabelId, countryPanelId, countryLabelErrorId, countryPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError)
{
   if (onlyRemoveError) ChangeStatesVisibility(countryDropDownId, regionDropDownId, regionTextBoxId);
   return ValidateDropDownNotEmpty(countryLabelId, countryPanelId, countryLabelErrorId, countryPanelErrorId, "'Country' field is required", countryDropDownId, onlyRemoveError);
}

function ValidateApplicationFeePostCodeTextBox(textBoxPostCodeLabelId, textBoxPostCodeId, textBoxPostCodeLabelErrorId, textBoxPostCodePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxPostCodeLabelId, textBoxPostCodeId, textBoxPostCodeLabelErrorId, textBoxPostCodePanelErrorId, "'Zip/Postcode' field is required", onlyRemoveError);
}

function ValidateApplicationFeeCardType(cardTypeLabelId, cardTypePanelId, cardTypeLabelErrorId, cardTypePanelErrorId, cardTypeDropDownId, onlyRemoveError)
{
   return ValidateDropDownNotEmpty(cardTypeLabelId, cardTypePanelId, cardTypeLabelErrorId, cardTypePanelErrorId, "'Card Type' field is required", cardTypeDropDownId, onlyRemoveError);
}

function ValidateApplicationFeeRegion(regionLabelId, regionPanelId, regionLabelErrorId, regionPanelErrorId, countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError)
{
   return ValidateRegion(regionLabelId, regionPanelId, regionLabelErrorId, regionPanelErrorId, "'State/Region' field is required", countryDropDownId, regionDropDownId, regionTextBoxId, onlyRemoveError);
}

function ValidateApplicationFeeSecurityCodeTextBox(textBoxSecurityCodeLabelId, textBoxSecurityCodeId, textBoxSecurityCodeLabelErrorId, textBoxSecurityCodePanelErrorId, onlyRemoveError)
{
   return ValidateTextBoxNotEmpty(textBoxSecurityCodeLabelId, textBoxSecurityCodeId, textBoxSecurityCodeLabelErrorId, textBoxSecurityCodePanelErrorId, "'Security Code' field is required", onlyRemoveError);
}

/*========== END REGION FOR SEPARATE METHODS ============*/



function PanelFilesExists(panelId)
{
   var panelFiles = document.getElementById(panelId);
   return (panelFiles != null) && panelFiles.style.display != 'none';
}

function GetFileExtension(path)
{
   if (!path || path.length == 0 ) 
      return '';
      
   var dotIndex = path.lastIndexOf('.');
   var slashIndex = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
   if (dotIndex == -1 || dotIndex < slashIndex)
      return '';
      
   return path.substr(dotIndex, path.length).toLowerCase();
}

//======================== INDIVIDUAL FILE UPLOADING =======================================
// definitions for field ids
var UPLOAD_STATUS_ID = "applicantPerformanceUploadStatus"

var APPLICANT_PERFORMANCE_COUNT_ID = "applicantPerformanceUploadCount"
var APPLICANT_PERFORMANCE_STATUS_ID = "applicantPerformanceUploadStatus"
var APPLICANT_PERFORMANCE_FRAME_NAME = "ApplicantPerformance"
var APPLICANT_PERFORMANCE_FRAME_ID = "frameApplicantPerformance"
var APPLICANT_PERFORMANCE_FILES_ID = "applicantPerformanceUploadedFiles"

var APPLICANT_REFERENCE_COUNT_ID = "applicantReferenceUploadCount"
var APPLICANT_REFERENCE_STATUS_ID = "applicantReferenceUploadStatus"
var APPLICANT_REFERENCE_FRAME_NAME = "ApplicantReference"
var APPLICANT_REFERENCE_FRAME_ID = "frameApplicantReference"
var APPLICANT_REFERENCE_FILES_ID = "applicantReferenceUploadedFiles"



var mUploading = false;
var mTimeout = 0;
var mRefreshTimeout = 2 * 1000; //2 seconds
var MAX_TIMEOUT = 30 * 60 * 1000; //30 minutes in miliseconds
var mCurrentFile = "";
var mCurrentFileId = "";
var mLastFileType = "";
// POSSIBLE VALUES:
// "TAX_RETURN"
// "REFERENCE"
// "MUSIC";

var mLastUploadState = "NOT STARTED";
// POSSIBLE VALUES:
// "NOT STARTED" - initial value
// "IN PROGRESS" - this value could/should be corelated with mUploading
// "SUCCESSFUL" - this value is available only if the server says the save went OK
// "UNSUCCESSFUL" - this value is available only if the server rejects it nicely (maybe the size is larger than 20MB)
// "TIMEOUT" - this value is available if the max wait time has passed

function BeginUploadForTaxReturnFile(taxReturnFileIFRAMEId)
{
    var fileName = "";
    //TODO get the fileName from the IFRAME
    BeginUploadForFile(fileName, "TAX_RETURN");
}

function BeginUploadForReferenceFile(referenceFileIFRAMEId)
{
    var fileName = "";
    //TODO get the fileName from the IFRAME
    BeginUploadForFile(fileName, "REFERENCE");
}

function BeginUploadForMusicFile(musicFileIFRAMEId)
{
    var fileName = "";
    //TODO get the fileName from the IFRAME
    BeginUploadForFile(fileName, "MUSIC");
}

function BeginUploadForFile(fileName, fileType, fileId)
{
    if (mUploading)
    {
        var message = "There is another upload in progress for file '" + mCurrentFile + "'.";
        message += "\nPlease wait for it to finish. You will receive a notification when you can start uploading a new file";
        alert(message);
        return false;
    }
    
    mTimeout = 0;
    mUploading = true;
    mCurrentFile = fileName;
    mCurrentFileId = fileId;
    mLastUploadState = "IN PROGRESS";
    mLastFileType = fileType;
    setTimeout(VerifyUploadIsFinished, mRefreshTimeout);
    
    return true;
}

function VerifyUploadIsFinished()
{
   if (!mUploading) return;
   
    //var successful = "UPLOAD OK"; //TODO check the state of the hidden value used for uploading (the IFRAME will set that one)
    var successful = document.getElementById(UPLOAD_STATUS_ID).value;
    if (successful == "UPLOAD OK")
    {
        alert("File '" + mCurrentFile + "' was uploaded successfully!");
        mTimeout = 0;
        mUploading = false;
        mLastUploadState = "SUCCESSFUL";
        AddFileByType();
        mLastFileType = "";
        
        return true;
    }
    else if (successful == "UPLOAD REJECTED")
    {
        alert("File '" + mCurrentFile + "' was rejected because its size is larger than 20MB");
        mTimeout = 0;
        mUploading = false;
        mLastUploadState = "UNSUCCESSFUL";
        mLastFileType = "";
        
        return true;
    }
    else if (mTimeout >= MAX_TIMEOUT)
    {
        alert('The upload operation for file \'' + mCurrentFile +  '\' has timed out! Please try again.');
        mTimeout = 0;
        mUploading = false;
        mLastUploadState = "TIMEOUT";
        
        //TODO Stop IFRAME for other iframes
        if(mLastFileType == 'MUSIC')
            window.frames[APPLICANT_PERFORMANCE_FRAME_NAME].stop();
        
        mLastFileType = "";
        
        
        
        return false;
   }
   
   mTimeout += mRefreshTimeout;
   setTimeout(VerifyUploadIsFinished, mRefreshTimeout);
}

function AddFileByType()
{
    if (mLastFileType == "TAX_RETURN")
    {
        //TODO add a new <p> or <tr> to the table of tax return files (actually there is only one such file)
    }
    else if (mLastFileType == "REFERENCE")
    {
        var fileTable = document.getElementById(APPLICANT_REFERENCE_FILES_ID);
        var lastRow = fileTable.rows.length;
        
        var newRow = fileTable.insertRow(lastRow);
        newRow.id = "fileRow" + mCurrentFileId;
        
        var nameCell = newRow.insertCell(0);
        nameCell.innerHTML = mCurrentFile;
                
        var deleteCell = newRow.insertCell(1);
        var deleteHTML = "<a href=\"javascript:DeleteUploadedFile('" + mCurrentFileId + "', 'REFERENCE')\">Delete</a>" +
                         "<input type='hidden' id='fileDelete" + mCurrentFileId + "' name='fileDelete" + mCurrentFileId + "' value='' />"
        
        
        deleteCell.innerHTML = deleteHTML;
        var uploadCount = document.getElementById(APPLICANT_REFERENCE_COUNT_ID);
        uploadCount.value = parseInt(uploadCount.value) + 1;
    }
    else if (mLastFileType == "MUSIC")
    {
        
        var fileTable = document.getElementById(APPLICANT_PERFORMANCE_FILES_ID);
        var lastRow = fileTable.rows.length;
        
        var newRow = fileTable.insertRow(lastRow);
        newRow.id = "fileRow" + mCurrentFileId;
        
        var nameCell = newRow.insertCell(0);
        nameCell.innerHTML = mCurrentFile;
                
        var deleteCell = newRow.insertCell(1);
        var deleteHTML = "<a href=\"javascript:DeleteUploadedFile('" + mCurrentFileId + "', 'MUSIC')\">Delete</a>" +
                         "<input type='hidden' id='fileDelete" + mCurrentFileId + "' name='fileDelete" + mCurrentFileId + "' value='' />"
        
        
        deleteCell.innerHTML = deleteHTML;
        var uploadCount = document.getElementById(APPLICANT_PERFORMANCE_COUNT_ID);
        uploadCount.value = parseInt(uploadCount.value) + 1;
        
        
    }
}

function SetUploadCountForMusicFiles(value)
{
    var uploadCount = document.getElementById(APPLICANT_PERFORMANCE_COUNT_ID);
    uploadCount = value;
        
}

function SetUploadCountForReferenceFiles(value)
{
    var uploadCount = document.getElementById(APPLICANT_REFERENCE_COUNT_ID);
    uploadCount = value;
        
}

function DeleteUploadedFile(fileId, fileType)
{
   // Hide the row
   var fileRow = document.getElementById('fileRow' + fileId);
   fileRow.style.display = 'none';
   
   // Set the delete input field to true
   var fileDelete = document.getElementById('fileDelete' + fileId);
   fileDelete.value = 'true';
   
   // Check if all the rows are hidden, and if true, hide the entire panel
//   var allHidden = true;
//   var fileTableBody = fileRow.parentNode;
//   for (var index = 0; index < fileTableBody.childNodes.length; index++)
//   {
//      if (fileTableBody.childNodes[index].nodeType == 1 &&
//         fileTableBody.childNodes[index].style.display != 'none')
//      {
//         allHidden = false;
//         break;
//      }
//   }
//   
//   if (allHidden)
//   {
//      var panelFiles = fileRow.parentNode.parentNode.parentNode;
//      panelFiles.style.display = 'none';
//   }

    var currentCountId = "";
    
    if (fileType == "TAX_RETURN")
    {
        // TODO
    }
    else if (fileType == "REFERENCE")
    {
       currentCountId = APPLICANT_REFERENCE_COUNT_ID;
    }
    else if (fileType == "MUSIC")
    {
        currentCountId = APPLICANT_PERFORMANCE_COUNT_ID;       
    }
   
    var uploadCount = document.getElementById(currentCountId);
    uploadCount.value = parseInt(uploadCount.value) - 1;
}
