String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

var predDateExit = new Date();
var predDateExit2 = new Date();

function show_error(message) { alert("Validation error:\r\n\r\n" + message); }

function nothingOrBig(field, size, msg) {

  var str = (''+field.value).trim();

  if (str=='') {
	show_error('Please enter a value for the "' + msg + '" field');
	field.focus();
	return true;
  }
  if (str.length > size) {
	show_error('The "' + msg + '" field may only contain a maximum of ' +size+ ' characters' + "\r\n" + 'Please correct this and try again.');
	field.focus();
	return true;
  }
  if (/'/.test(str)) {
	show_error('The ' + msg + " field may not contain '\r\nPlease correct this and try again.");
	field.focus();
	return true;
  }

}

function fieldEmpty(field, msg) { 

  if ((''+field.value).trim().length == 0) {
	show_error("Please enter a value for the '" + msg + "' field.");
	field.focus();
	return true;
  }

  if (/'/g.test(field.value)) {
	show_error("The '" + msg + "' field may not contain '\r\nPlease correct this and try again." );
	field.focus();
	return true;
  }

  return false;

}

//since dateDiff accepts dates objects and strings, we just return what we got
function DateValue(smth) { return smth; }

//maybe we will need it
var Now = new Date();


function fieldBiggerThan(field, size, msg) {

  var str = (''+field.value).trim();
  
  if(str.length > size) {
	show_error('The ' + msg + ' field may only contain a maximum of ' + size + ' characters. ' + "\r\n Please correct this and try again.");
	field.focus();
	return true;
  } 

  else if (/'/.test(str)) {
	  show_error('The ' + msg + " field may not contain '\r\nPlease correct this and try again.");
	  field.focus();
	  return true;
  }

  return false;

}


//receives only references for DOM objects
function dateNotOk(d, m, y, msg) { return !isDate(y.options[y.selectedIndex].text + " " + m.selectedIndex + " " + d.selectedIndex); }

var dateNotOK = dateNotOk;


function digitsNotOk(input, msg) {
  if (!/^[0-9]*$/.test((''+input.value).trim().replace(/\+/g,"").replace(/\)/g, "").replace(/\(/g, "").replace(/\s*/g, ""))) {
	show_error("'" + msg + "' can only contain numbers and spaces. Please correct this and click continue.");
	input.focus();
	return true;
  }
}


var digitsNotOK = digitsNotOk;

function dateDiff(date1, date2) 
{

  if (typeof date1 == 'object') date1 = new Date(date1.valueOf()); 
  else if (typeof date1 == 'string') { var d1 = date1.split(' '), date1 = new Date(d1[0]*1, (d1[1]-1)*1, d1[2]*1); }

  if (typeof date2 == 'object') date2 = new Date(date2.valueOf());
  else if (typeof date2 == 'string') { var d1 = date2.split(' '), date2 = new Date(d1[0]*1, (d1[1]-1)*1, d1[2]*1); }

  var d = date1.valueOf() - date2.valueOf();

  var a = Math.floor(d/1000); 
  a = Math.floor(a/60);
  a = Math.floor(a/60);
  a = Math.floor(a/24);

  return a;

}

var DateDiff = dateDiff;

function isDate(dateStr) {
  var date = dateStr.split(' ');
  var year = date[0], month = date[1], day = date[2];
  if (month < 1 || month > 12) return false;
  if (day < 1 || day > 31) return false;
  if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;
  if (month == 2) if (day > 29 || (day==29 && !(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)))) return false;
  return true;
}


var homeAddressCountryChanged = function(){

  var newCountry = document.theVisaForm.homeAddressCountry.options[document.theVisaForm.homeAddressCountry.selectedIndex].text;

  if (newCountry == "United Kingdom") document.theVisaForm.homeAddressCounty.removeAttribute("disabled");

  else document.theVisaForm.homeAddressCounty.setAttribute("disabled","true");

};


function dateAdd(timeU, byMany, dateObj) {

  if (typeof dateObj == 'object') dateObj = new Date(dateObj.valueOf()); 
  else if (typeof dateObj == 'string') { var d1 = dateObj.split(' '), dateObj = new Date(d1[0]*1, (d1[1]-1)*1, d1[2]*1); }

  var millisecond=1;
  var second=millisecond*1000;
  var minute=second*60;
  var hour=minute*60;
  var day=hour*24;
  var year=day*365;

  var newDate, dVal=dateObj.valueOf();
  switch(timeU) {
	case "ms": newDate=new Date(dVal+millisecond*byMany); break;
	case "s":  newDate=new Date(dVal+second*byMany); break;
	case "mi": newDate=new Date(dVal+minute*byMany); break;
	case "h":  newDate=new Date(dVal+hour*byMany); break;
	case "d":  newDate=new Date(dVal+day*byMany); break;
	case "y":  newDate=new Date(dVal+year*byMany); break;
  }

  return newDate;

}

var visaForm_validate = function (e) {

	var theForm = document.all["theVisaForm"];

	var theDay = theForm.visitDayOfEntry.selectedIndex;
	var theMonth = theForm.visitMonthOfEntry.selectedIndex;
	var theYear = theForm.visitYearOfEntry.options[theForm.visitYearOfEntry.selectedIndex].text;

	if (nothingOrBig(theForm.firstName, 50, "First Name")) return stop(e); ;

	if (nothingOrBig(theForm.surName, 50, "Surname")) return stop(e); ;

	if (fieldBiggerThan(theForm.middleName, 50, "Middle Name")) return stop(e); ;

	var g = document.all['gender'];
	if (!g.item(0).checked && !g.item(1).checked) {
		show_error("Please select your Gender.");
		g[0].focus();
		return stop(e); ;
	}

	if (dateNotOk(theForm.dobDay, theForm.dobMonth, theForm.dobYear, "your date of birth.")) {
		show_error('Your date of birth is invalid! Please check it and try again.');
		theForm.dobDay.focus();
		return stop(e); ;
	}

	dc = theForm.dobYear.options[theForm.dobYear.selectedIndex].text + " " + theForm.dobMonth.selectedIndex + " " + theForm.dobDay.selectedIndex;

	if (dateDiff(dc, Now) > 0) {
		show_error("Your date of birth is later than or equal to todays date, please correct this and then click the continue button again.");
		theForm.dobDay.focus();
		return stop(e); ;
	}

	if (nothingOrBig(theForm.cityOfBirth, 40, "City Of Birth")) {
		theForm.cityOfBirth.focus();
		return stop(e);
	}

	if (fieldBiggerThan(theForm.homeAddress1, 6, "House Number")) {
		theForm.homeAddress1.focus();
		return stop(e); ;
	}

	if (fieldBiggerThan(theForm.homeAddress2, 50, "Street")) {
		theForm.homeAddress2.focus();
		return stop(e); ;
	}

	if (nothingOrBig(theForm.homeAddressCity, 50, "City or Town")) {
		theForm.homeAddressCity.focus();
		return stop(e); ;
	}


	var t = theForm.homeAddressCounty.options[theForm.homeAddressCounty.selectedIndex].text;
	var c = theForm.homeAddressCountry.options[theForm.homeAddressCountry.selectedIndex].text;
	if ((c == "United Kingdom") && ((t == "") || (t.substr(0, 2) == "--"))) {
		show_error("Please select a 'county' for your home address.");
		theForm.homeAddressCounty.removeAttribute("disabled");
		theForm.homeAddressCounty.focus();
		return stop(e);
	}

	if (nothingOrBig(theForm.homeAddressPostCode, 10, "Post Code")) {
		return stop(e);
	}

	if (nothingOrBig(theForm.homeTelephone, 20, "Home Telephone")) {
		return stop(e);
	}

	if (digitsNotOK(theForm.homeTelephone, "Home Telephone Number")) {
		return stop(e); ;
	}

	if (nothingOrBig(theForm.email, 50, "Email Address")) {
		return stop(e); ;
	}

	if (fieldEmpty(theForm.emailConfirm, "Email Confirm")) {
		return stop(e); ;
	}

	if (('' + theForm.email.value).trim() != ('' + theForm.emailConfirm.value).trim()) {
		show_error("Your email and email confirm addresses do not match, please correct this.");
		theForm.email.focus();
		return stop(e); ;
	}


	// check medical insurance if available
	if (document.getElementById('insurCompany'))
	{
//		if (fieldEmpty(theForm.insurCompany, "Insurance company")) {
//			return stop(e);
//		}
//		if (fieldEmpty(theForm.insurNumber, "Policy number")) {
//			return stop(e);
//		}
//		if (dateNotOk(theForm.insurFromDay, theForm.insurFromMonth, theForm.insurFromYear, "your medical insurance issued date.")) {
//			show_error("The date of issue of your medical insurance is invalid! Please check it and try again.");
//			theForm.insurFromDay.focus();
//			return stop(e); ;
//		}
//		if (dateNotOk(theForm.insurUntilDay, theForm.insurUntilMonth, theForm.insurUntilYear, "your medical insurance expiry date.")) {
//			show_error("The date of expiry of your medical insurance is invalid! Please check it and try again.");
//			theForm.insurUntilDay.focus();
//			return stop(e); ;
//		}
	}


	if (nothingOrBig(theForm.passportNumber, 20, "Passport Number")) {
		return stop(e); ;
	}

	if (dateNotOk(theForm.passportDayIssued, theForm.passportMonthIssued, theForm.passportYearIssued, "your passport issued date.")) {
		show_error("The date of issue of your passport is invalid! Please check it and try again.");
		theForm.passportDayIssued.focus();
		return stop(e); ;
	}

	if (dateNotOK(theForm.passportDayExpires, theForm.passportMonthExpires, theForm.passportYearExpires, "your passport expiry date.")) {
		show_error("The date of expiry of your passport is invalid! Please check it and try again.");
		theForm.passportDayExpires.focus();
		return stop(e);
	}

	var piss = theForm.passportYearIssued.options[theForm.passportYearIssued.selectedIndex].text + " " + theForm.passportMonthIssued.selectedIndex + " " + theForm.passportDayIssued.selectedIndex;
	var pexp = theForm.passportYearExpires.options[theForm.passportYearExpires.selectedIndex].text + " " + theForm.passportMonthExpires.selectedIndex + " " + theForm.passportDayExpires.selectedIndex;

	if (DateDiff(piss, Now) > 0) {
		show_error("Your passport issued date is later than today, please correct this.");
		theForm.passportDayIssued.focus();
		return stop(e); ;
	}

	if (DateDiff(piss, pexp) >= 0) {
		show_error("Your passport issued date is later than or equal to your passport expiry date, please correct this.");
		theForm.passportDayIssued.focus();
		return stop(e); ;
	}

	var entd = theForm.visitYearOfEntry.options[theForm.visitYearOfEntry.selectedIndex].text + " " + theForm.visitMonthOfEntry.selectedIndex + " " + theForm.visitDayOfEntry.selectedIndex;
	var expd = theForm.visitYearOfExit.options[theForm.visitYearOfExit.selectedIndex].text + " " + theForm.visitMonthOfExit.selectedIndex + " " + theForm.visitDayOfExit.selectedIndex;

	var visaEntries = document.getElementById('visaEntries');
	if (visaEntries.selectedIndex == 1) //double
	{
		var entd2 = theForm.visitYearOfEntry2.options[theForm.visitYearOfEntry2.selectedIndex].text + " " + theForm.visitMonthOfEntry2.selectedIndex + " " + theForm.visitDayOfEntry2.selectedIndex;
		var expd2 = theForm.visitYearOfExit2.options[theForm.visitYearOfExit2.selectedIndex].text + " " + theForm.visitMonthOfExit2.selectedIndex + " " + theForm.visitDayOfExit2.selectedIndex;

		if (!isDate(entd2) || !isDate(expd2)) {
			show_error("Date is not valid, please check it");
			theForm.visitDayOfEntry2.focus();
			return stop(e);
		}

		if (DateDiff(entd2, expd) < 0) {
			show_error("Your second entry date is earlier than your first exit date; please amend the dates.");
			theForm.visitDayOfEntry2.focus();
			return stop(e);
		}
		//if ((visaType=="Tourist")&&(DateDiff(expd2, entd)>30))
		if (((DateDiff(expd2, entd) > 30) && (visaType == "Tourist"))
		|| ((visaType == "Transit") && ((DateDiff(Now, entd) > 2) || DateDiff(Now, entd2) > 2))) {
			show_error("A double-entry Belarus tourist visa lasts for maximum 30 days (with both visits taking place during that period) and your dates exceed this.  Please amend your dates or opt for a single-entry visa to cover your first planned trip instead.");
			theForm.visitDayOfExit2.focus();
			return stop(e);
		}

	}
	if (DateDiff(Now, entd) > 0) {
		show_error("Your visa date of entry is earlier than or equal to current date.\r\nPlease correct this and try again");
		theForm.visitDayOfEntry.focus();
		return stop(e); ;
	}

	if (dateNotOK(theForm.visitDayOfEntry, theForm.visitMonthOfEntry, theForm.visitYearOfEntry, "your entry to Russia date.")) {
		show_error('Your entry to Russia date is invalid, please check it and try again.');
		theForm.visitDayOfEntry.focus();
		return stop(e); ;
	}

	if (dateNotOK(theForm.visitDayOfExit, theForm.visitMonthOfExit, theForm.visitYearOfExit, "your exit from Russia date.")) {
		show_error('Your exit from Russia date is invalid, please check it and try again.');
		theForm.visitDayOfExit.focus();
		return stop(e); ;
	}

	if (DateDiff(expd, entd) < 1) {
		show_error("Visa end date is earlier than or equal to visa start date.\r\nPlease correct this and try again");
		theForm.visitYearOfExit.focus();
		return stop(e);
	}

	if (!isDate(entd) || !isDate(expd)) {
		show_error("Date is not valid, please check it");
		theForm.visitDayOfEntry.focus();
		return stop(e);
	}

	/*  if ((visaType=='tourist') && ((DateDiff(expd,entd))>29)) {
	show_error("A tourist visa is only valid for a maximum of 30 days (inclusive) and your dates of entry and exit exceed this.\r\nPlease correct your dates.");
	theForm.visitDayOfEntry.focus();
	return stop(e);
	}*/

	if (DateDiff(expd, entd) > validFor) {
		show_error("A " + visaType + " visa is only valid for a maximum of " + validFor + " days (inclusive) and your dates of entry and exit exceed this.\r\nPlease correct your dates.");
		theForm.visitDayOfEntry.focus();
		return stop(e);
	}

	if ((DateDiff(entd, dateAdd("d", 13, Now)) <= 0) &&
		 !window.confirm("From the travel dates you have indicated, it is possible that if you are applying by post you will not be able to obtain your visa in time. \r\n\r\nIf you are NOT delivering or collecting your documents in person then we recommend that you either use an agency service or change your dates of travel.\r\n\r\nDo you still want to submit your application?")
	  ) {
		theForm.visaType.focus();
		return stop(e); ;
	}

	/*  var mess  = "You can not apply for a tourist visa more than 3 months (90 days) before your proposed\r\ndate of entry ";
	mess += "into Russia.\r\n\r\nIf we receive your application before this we will hold it until ";
	mess += dateAdd("d", -90, DateValue(entd));
	mess += "\r\nand then take it to the consulate.\r\n\r\nDo you still want to submit your application?";

	if ( (DateDiff(dateAdd("d", 90, Now), entd) <= 0) && 
	(!window.confirm(mess)) 
	) {
	theForm.visitDayOfEntry.focus();
	return stop(e);;
	}*/

	if ((dateDiff(pexp, expd) <= 180)) {
		show_error("Your passport expires within 6 months of your proposed date of exit from Russia.\r\nEither change your dates of travel or obtain a new passport.");
		theForm.visitDayOfExit.focus();
		return stop(e); ;
	}


	if (!theForm.earlierBeen.item(0).checked && !theForm.earlierBeen.item(1).checked) {
		show_error("Please select if you have ever been to Belarus");
		return stop(e);
	}

	if (!theForm.earlierRefused.item(0).checked && !theForm.earlierRefused.item(1).checked) {
		show_error("Please select if you have ever been refused a Belarussian visa");
		return stop(e);
	}

	if (!theForm.earlierCharged.item(0).checked && !theForm.earlierCharged.item(1).checked) {
		show_error("Please select if you have ever been charged with violating the Belarussian law while in Belarus");
		return stop(e);
	}

	if (!theForm.earlierDeported.item(0).checked && !theForm.earlierDeported.item(1).checked) {
		show_error("Please select if you have ever been deported from any country");
		return stop(e);
	}

	if (!theForm.children.item(0).checked && !theForm.children.item(1).checked) {
		show_error("Please select if you have children under 16 years of age travelling with you");
		return stop(e);
	}

	if (!theForm.tandc.item(0).checked) {
		show_error("Please indicate that you have read the terms and conditions");
		theForm.tandc.item(0).focus();
		return stop(e);
	}

	return true;



};

var stop = function(e) {if (e&&e.preventDefault) e.preventDefault(); return false;};

var calculateExitDate = function(param)
{ 
  ShowHighlightDates();
  param = param || 1;
  if (visaType=="Tourist") return;  
  var theForm = document.theVisaForm;
  var d_ent, m_ent, y_ent;
  var d_ext, m_ext, y_ext;
  if (param==1)
  {
	d_ent = theForm.visitDayOfEntry;
	m_ent = theForm.visitMonthOfEntry;
	y_ent = theForm.visitYearOfEntry;
	d_ext = theForm.visitDayOfExit;  
	m_ext = theForm.visitMonthOfExit; 
	y_ext = theForm.visitYearOfExit;  
  }
  else if (param==2)
  {
	d_ent = theForm.visitDayOfEntry2; 
	m_ent = theForm.visitMonthOfEntry2; 
	y_ent = theForm.visitYearOfEntry2;
	d_ext = theForm.visitDayOfExit2;  
	m_ext = theForm.visitMonthOfExit2;  
	y_ext = theForm.visitYearOfExit2;  
  }
	
  
  if ((d_ent.selectedIndex == 0) || (m_ent.selectedIndex == 0) || (y_ent.selectedIndex == 0)) return;

  if (dateNotOk(d_ent, m_ent, y_ent)) 
  {
	show_error('Date of entry you selected is invalid, please correct this and try again');
	return false;
  }

  var dt = new Date();
  dt.setYear(y_ent.options[y_ent.selectedIndex].text * 1);  
  dt.setMonth(m_ent.selectedIndex-1,d_ent.selectedIndex);  
  
  if (dateDiff(dt, new Date())<=0) 
  {
	show_error("Date of entry you selected is earlier than or equal to today, please correct this and try again");
	return false;
  }


  var add = d_ent.selectedIndex + (visaType == "tourist" ? 29 : 1);

  dt.setDate(add); // adding proper amount of days

  var newMonth = dt.getMonth(), 
	  newYear = dt.getFullYear(), 
	  newDay = dt.getDate();
  
  d_ext.selectedIndex = newDay;
  m_ext.selectedIndex = newMonth+1;

  for (var i=0,opts=y_ext.options,l=opts.length; i<l; ++i) 
	if (opts[i].text == newYear) 
		y_ext.selectedIndex = i;

  
  if (param==1)
  {
	  predDateExit.setYear(y_ext.options[y_ent.selectedIndex].text * 1);
	  predDateExit.setMonth(m_ext.selectedIndex-1);
	  predDateExit.setDate(d_ext.selectedIndex);
  }
  else if (param==2)
  {
	  predDateExit2.setYear(y_ext.options[y_ent.selectedIndex].text * 1);
	  predDateExit2.setMonth(m_ext.selectedIndex-1);
	  predDateExit2.setDate(d_ext.selectedIndex);
  }
	ShowHighlightDates();    
};

var checkEntryDate = function(param)
{  
  param = param || 1;
  var theForm = document.getElementById('theVisaForm');
  var d_ent, m_ent, y_ent;
  var d_ext,  m_ext, y_ext;
  if (param==1)
  {
	 d_ent = theForm.visitDayOfEntry; 
	 m_ent = theForm.visitMonthOfEntry; 
	 y_ent = theForm.visitYearOfEntry;
	 d_ext = theForm.visitDayOfExit;  
	 m_ext = theForm.visitMonthOfExit;  
	 y_ext = theForm.visitYearOfExit;
  }
  else if (param==2)
  {
	 d_ent = theForm.visitDayOfEntry2; 
	 m_ent = theForm.visitMonthOfEntry2; 
	 y_ent = theForm.visitYearOfEntry2;
	 d_ext = theForm.visitDayOfExit2;  
	 m_ext = theForm.visitMonthOfExit2;  
	 y_ext = theForm.visitYearOfExit2;
  }

  if ((d_ext.selectedIndex == 0) || (m_ext.selectedIndex == 0) || (y_ext.selectedIndex == 0)) return;

  var entryDate = y_ent.options[y_ent.selectedIndex].text + " " + m_ent.selectedIndex + " " + d_ent.selectedIndex;
  var exitDate  = y_ext.options[y_ext.selectedIndex].text + " " + m_ext.selectedIndex + " " + d_ext.selectedIndex;

  var diff = DateDiff(exitDate, entryDate);

  if (diff < 0)
  {
	show_error("Your date of entry is less than a date of exit.");
	return false;
  }
  else if (diff>((visaType.toLowerCase() == "tourist" ? 29 : 1))) 
  {
	var tomsg = "A Belarrus Tourist Visa is valid for a maximum visit of 30 days, your requested dates exceed this\r\n\r\nPlease check your dates and try again.";
	var trmsg;
	var visaEntries=document.getElementById('visaEntries'); 
	if (visaEntries.selectedIndex==0) //double    
		trmsg = "A Belarussian Transit Visa is valid for a maximum visit of 48 hours, please check your dates and try again.";
	else if (visaEntries.selectedIndex==1) //double        
		trmsg = "A double-entry Belarus Transit Visa is only valid for 2 consecutive days on each journey; please check your dates and try again.";
	show_error(visaType.toLowerCase() == "tourist" ? tomsg : trmsg);
	return false;
  }
  
  ShowHighlightDates();
  
  /*if (visaType=="Transit")
	  if ( ((param==1)&&(DateDiff(exitDate, predDateExit)>0))||((param==2)&&(DateDiff(exitDate, predDateExit2)>0)) )
	  {        
		alert("A double-entry Belarus Transit Visa is only valid for 2 consecutive days on each journey; please check your dates and try again.");
		return false;
	  }
*/
};
