var maxHeight=60;
var opened = 0;
var seconds = 80;
var amount = 0;
var _ = (''+document.location).split('?'); if ((_.length>0) && (typeof _[1] != 'undefined') && (_[1].split('=').length>1)) for (var v = _[1].split('&'),i=0,a,queryString={}; i<v.length; ++i) { a=v[i].split('='); queryString[unescape(a[0])] = unescape(a[1].replace(/#.*/, '')); } else { queryString = {}; queryString["service"] = "SE30-10-7";}

var lastWorkQ = false, lastEducationQ = false, visitedCountriesQ = false;

/*
 * This function show or hide detailed information of payments 
*/
function ShowPriceDetailed()
{
 var d=document.getElementById('priceTextDetail');
 if (!d) return;
 if (d.style.display=="none") d.style.display="";
 else d.style.display="none"; 
}

function IsAvailableVisaType_ForVSDServiceAndPurpose(visaType) {
    if (visaType == TypesVisaEnum.ME3Y) {
        var visaService_SelectHtmlElement = document.getElementById("visaService");
        var VSDService = visaService_SelectHtmlElement.options[visaService_SelectHtmlElement.selectedIndex].text;

        var purposeOfVisit_SelectHtmlElement = document.getElementById("purposeOfVisit");
        var purposeOfVisit = purposeOfVisit_SelectHtmlElement.options[purposeOfVisit_SelectHtmlElement.selectedIndex].text;

        if (!((VSDService == "I have my own Visa Support") && (purposeOfVisit == "Work"))) {
            return false;
        }        
    }
    return true;
}

function FillVisaTypeSelectElement() {

    var values = [
                    TypesVisaEnum.SE30,
                    TypesVisaEnum.SE90,
                    TypesVisaEnum.DE30,
                    TypesVisaEnum.DE90,
                    TypesVisaEnum.ME06,
                    TypesVisaEnum.ME12,
                    TypesVisaEnum.ME3Y
                ];

    for (var i = 0; i < values.length; i++) {
        var isRemove = false;

        if (!IsAvailableVisaType_ForVSDServiceAndPurpose(values[i]))
            isRemove = true;

        if (!IsAvailableVisaType_ForCitizenship(values[i]))
            isRemove = true;

        if (isRemove)
            values.splice(i, 1);
    }
    
    
    var visaType_SelectHtmlElement = document.getElementById("visaType");
    FillSelectElement(visaType_SelectHtmlElement, values);
}

/*
 *  This function show total information in the end of page which relative of type visit
 */
function ShowHighlightDates()
{    
    
    var entry=document.getElementById("visaType");
    entry=entry.options[entry.selectedIndex].text;    
    var entrydate,
        exitdate,
        str;
    document.getElementById("SingleHighlight").style.display="none";
    document.getElementById("DoubleHighlight").style.display="none";
    document.getElementById("MultiHighlight").style.display="none";
    if ( (entry=="Single Entry valid for 1 month")||(entry=="Single Entry valid for 3 months") )     
    {
        document.getElementById("SingleHighlight").style.display="";        
        entrydate=document.getElementById("SENTRYDATE");
        exitdate=document.getElementById("SEXITDATE");
    }
    else if ( (entry=="Double Entry valid for 1 month")||(entry=="Double Entry valid for 3 months") )     
    {        
        document.getElementById("DoubleHighlight").style.display="";;
        entrydate=document.getElementById("DENTRYDATE");
        exitdate=document.getElementById("DEXITDATE");
    }
    else //multi
    {
        document.getElementById("MultiHighlight").style.display="";;
        entrydate=document.getElementById("MENTRYDATE");
        exitdate=document.getElementById("MEXITDATE");        
    }
    var Day=document.getElementById("visitDayOfEntry");
    Day=Day.options[Day.selectedIndex].text;
    var Month=document.getElementById("visitMonthOfEntry");
    Month=Month.options[Month.selectedIndex].text;
    var Year=document.getElementById("visitYearOfEntry");
    Year=Year.options[Year.selectedIndex].text;
    if ((Day=="Day")||(Month=="Month")||(Year=="Year"))
    {
        entrydate.innerText="<not specified>";
    }
    else 
    {
        //entrydate.innerHTML=Day.substr(0,Day.length-2)+"<sup>"+Day.substr(Day.length-2,2)+"</sup> "+Month+" "+Year;
        entrydate.innerHTML=Day.substr(0,Day.length-2)+" "+Month+" "+Year;
    }
    Day=document.getElementById("visitDayOfExit");
    Day=Day.options[Day.selectedIndex].text;
    Month=document.getElementById("visitMonthOfExit");
    Month=Month.options[Month.selectedIndex].text;
    Year=document.getElementById("visitYearOfExit");
    Year=Year.options[Year.selectedIndex].text;
    if ((Day=="Day")||(Month=="Month")||(Year=="Year"))
    {
        exitdate.innerText="<not specified>";
    }
    else 
    {
        //exitdate.innerHTML=Day.substr(0,Day.length-2)+"<sup>"+Day.substr(Day.length-2,2)+"</sup> "+Month+" "+Year;
        exitdate.innerHTML=Day.substr(0,Day.length-2)+" "+Month+" "+Year;
    }    
}


function digitsNotOKJS(p, msg)
{
  var temp="";
  if(trim(p.value) != "") 
  {
    temp = p.value.replace(" ","");
	temp = temp.replace("(","");
	temp = temp.replace(")","");
	if(!IsNumeric(temp)) 
	{
	    alert("'" + msg + "' can only contain numbers and spaces. Please correct this and click continue.");
		return true;
    }
  }
  return false;
}

function fieldEmptyJS(fieldCheck, msg)
{
    if (trim(fieldCheck.value) == "")
    {
	    alert("Please enter a value for the '" + msg + "' field.");
	    return true;
	}
	else 
	    if (fieldCheck.value.indexOf("'")>-1)
	    {
		    alert("The '" + msg + "' field may not contain '" + "\n" + "Please correct this and try again.");
	    } 
	    else return false;
}

function fieldBiggerThanJS(fieldCheck, size, msg) 
{
    if((trim(fieldCheck.value)).length > size) 
    {
	    alert("The '" + msg + "' field may only contain a maximum of " + size + " characters." + "\n" + "Please correct this and try again.");
	    return true;
	}
    else 
    {
	    if(fieldCheck.value.indexOf("'") > -1) 
	    {
		    alert("The '" + msg + "' field may not contain '" + "\n" + "Please correct this and try again.");
		    return true;
	    } 
	    else return false;
    }
}

function nothingOrBigJS(fieldCheck, size, msg) 
{
    var nothingOrBig = false;
    if (trim(fieldCheck.value)=="")
    {
        alert("Please enter a value for the '" + msg + "' field.");
        nothingOrBig = true;
        return nothingOrBig;
    }
    if ((trim(fieldCheck.value)).length > size)
    {
        alert("The '" + msg + "' field may only contain a maximum of " + size + " characters." + "\n" + "Please correct this and try again.");
        nothingOrBig = true;
        return nothingOrBig;
    }
    if (fieldCheck.value.indexOf("'")>-1)
    {
        alert("The '" + msg + "' field may not contain '" + "\n" + "Please correct this and try again.");
        nothingOrBig = true;
        return nothingOrBig;
    }
}

function refreshButs() 
{
    var ar = ['add_visitRelatives','add_company_details','add_education_details'];
    
    for(var k=0,parentNode,divToClone; k<ar.length;k++) 
    {
        parentNode = document.getElementById(ar[k]);
        divToClone = parentNode.getElementsByTagName("div");
        
        for (var i=0, inputs, div; (div=divToClone[i]); ++i)
        { 
            inputs = div.getElementsByTagName('input'); 
            for (var j=0, tmp; (tmp=inputs[j]); j++)
            { 
                if(tmp.className == "rightTop2")
                {
                    tmp.style.width = "90px";
                    if (divToClone.length==1)
                    {
                        tmp.style.display = tmp.value=='Add next' ? 'inline' : 'none';
                    }
                    else 
                    {
                        if (i == divToClone.length-1) inputs[j].style.display = 'inline';
                        else tmp.style.display = tmp.value=='Add next' ? 'none' : 'inline';
                    }
                }
            }
        }
    }
}

function deleteNext(obj)
{
    var parent = obj.parentNode.parentNode; 
    if (confirm('Are you sure you want to remove this item?'))
        parent.parentNode.removeChild(parent); 
    
    refreshButs();
}

function showNext2(buttonObj, maxNumber, alertText)
{
    var parentNode = buttonObj.parentNode.nodeName == "DIV" ? buttonObj.parentNode: buttonObj.parentNode.parentNode.parentNode;
    
    var divToClone = parentNode.getElementsByTagName("div");
    var cloneNumber = divToClone.length;
    var cloneNum = 0;
    
    if ((maxNumber>0)&&(maxNumber<=cloneNumber))
    {
        alert("You dont't need to list more than "+maxNumber+" "+alertText+"."); 
        return false;
    }
    if (divToClone[0])
    {
        cloneNum = divToClone.length-1;
        var newNode = divToClone[cloneNum].cloneNode(true);
        parentNode.appendChild(newNode);
        
        var inputs = newNode.getElementsByTagName('input'); 
        
        divToClone = parentNode.getElementsByTagName("div");
        for(var i=0; i<divToClone.length; ++i)
        { 
            if(i==divToClone.length-1) 
            {                
                inputs2 = divToClone[i].getElementsByTagName('textarea'); 
                for (var k=0; k<inputs2.length; k++) 
                    inputs2[k].value = '';
                inputs = divToClone[i].getElementsByTagName('input');
                for (var k=0; k<inputs.length; k++) 
                {
                    
                    if(inputs[k].className!="rightTop2")
                        inputs[k].value = '';
                }                
                
            }
        }
        refreshButs();
    }
}

var mes = 
[
'<div id="divpr1"></div>','<div id="divd1"></div>',
'There are three basic types of business visa invitation that allow for either a single, double or multiple visits to Russia within their validity period. The validity period covers the start date requested for the visa for the specified number of days and you may enter and leave within the validity period of the visa (inclusive of the start and end date).<br><br><b>Single entry</b> visas may be requested for a period of either 30 or 90 days and allow one visit during the validity period of the visa.<br><br><b>Double entry</b> visas may be requested for a period of either 30 or 90 days and allow two visits during the validity period of the visa.<br><br><b>Multiple entry</b> visas may be requested for a period of 6 or 12 months and allow multiple visits during the validity period of the visa. For multiple entry visas you may only stay in the country for a maximum of 3 months during one visit and visa holders may only stay a maximum of 90 days within a 180 day period.',
'This is the time taken by the Russian authorities in Moscow to process and issue your visa support documents once we have submitted the application to them. The processing time is calculated in working days and does not include weekends, UK or Russian public holidays or the day of order.<br><br>Processing of your visa support documents will not start until you have paid and sent us a scan or clear fax of your passport page and if applicable your last Russian visa.<br><br>Please note that the visa support documents are issued the next working day after processing has completed and we can not start processing the visa until we receive them. The times to process and for our London office to receive the visa support documents (or the Telex support to be received by the Consulate) is included in the expected date of issue calculation.<br><br>If you have obtained your own visa support documents then simply select "I have my own visa support" option and provide the document with your application. The cost and expected date of issue calculation will change to reflect this.',
'The Consular Processing is the number of processing days that it will take the Russian Consulate to issue your visa once we have lodged your application with them.<br><br>The consulate charge an extra fee for processing on a 1 day service and this cost and time is included in the expected date of issue calculations.',
'<b>Purpose of visit - Business visas</b><br><br>The purpose of visit requested for your visa should generally correspond with your initial visit intentions. The purpose of visit will be written on the visa support documents and encoded into your visa, however, this does not restrict you to this purpose and you may, for example, use a business visa to visit family or friends or use a cultural visa to subsequently visit Russia for business purposes.<br><br>If you have your own visa support then select the closest matching purpose to the one you have listed on it.<br><br>If you are ordering your visa support through Real Russia then you may select from the following options, please note that not all options are available for all <a href="bvisasupportinfo.asp" target="_blank">visa support services</a>:<br><br><b>BUSINESS</b> - for people who are going to Russia for business including meetings, conferences, contract negotiations and such general business activities. When applying at the consulate you will require a letter from your company stating the purpose of your visit to Russia and who will finance the trip.<br><br><b>CULTURAL</b> - for people who are going to Russia for cultural or extended tourism periods. No supporting letter from an organiser is required, however you may be asked to provide a letter explaining your purpose of visit and show recent bank statements to demonstrate that you can support yourself in Russia for the period of the visa.<br><br><b>DRIVER</b> - for people who are going to be driving commercial or passenger vehicles in Russia. When applying at the consulate you will require a letter from your company stating the purpose of your visit to Russia.<br><br><b>FAMILY MEMBER</b> - for children under the age of 18 who are going to be travelling with an adult family member. When applying at the consulate the parent will be required to provide a letter stating the purpose of your visit to Russian and proof that they either have a Russia visa or are applying for one at the same time.<br><br><b>SPORT</b> - for people who are going to be taking part in an organised sporting event, either as a professional or amateur. When applying at the consulate you will require a letter from the event sponsor stating the purpose of your visit to Russia.',
'Tell us what you would like us to do with your passport and visa after we have collected it from the consulate.<br><br>We can return this to your home, work or other address using a range of options. The most common for UK delivery is Royal Mail Special Delivery which is inexpensive, secure and guaranteed for delivery the next working day. If you choose the insurance option for an extra &pound;3.60, then we will ensure that it is sent with &pound;2,500 of consequential loss insurance in addition to the standard maximum &pound;500 contents insurance (&pound;50 contents insurance for pre-9am delivery). You may also ensure that it is delivered on a Saturday if posted on a Friday for an extra &pound;2.70.<br><br>If you are outside the UK or require urgent return of your passport and visa then you may select &ldquo;Other courier - prices on application&rdquo; and we will obtain a quote for you from a reliable courier company. The courier is charged at cost.<br><br>For non-urgent International delivery you may select &ldquo;Royal Mail International delivery&rdquo; (Airsure / International Signed for) which can take up to 10 days but is much cheaper and the contents are insured for loss up to &pound;500.<br><br>If you are travelling as part of a group and we are processing other members’ visas, then you may ask us to return your passport with someone else&#39;s by selecting "Return with another passport" and then enter the details of this person into the comments box.<br><br>If you are applying for more than one visa with us, you need only indicate (and pay for) your chosen delivery option in one record. Please select &ldquo;Multi-application (delivery option indicated in other record)&rdquo; in your other records.<br><br>Finally you can collect your passport and visa from our office in person or by sending someone with photo ID - to select this choose &ldquo;I will collect from your office&rdquo;.',

'A Russian Business/Cultural visa is valid for a maximum of 30 or 90 days for single- and double-entry, and 180 or 365 days for multi-entry, inclusive of day of entry and exit.  The start date exactly matches the date you request on the invitation. You may enter and exit at any time within the visa validity (with a restriction on multi-entry visas that you can stay max. 90 days in Russia in each 180-day period); as such we would recommend that you add a few days before your expected date of travel to allow for changes in your plans.<br><br>Please note for double-/multi-entry visas the visa will be valid from the start date until the end date requested during which both/all visits must be completed.<br><br>Important! It is your responsibility to ensure that the dates you request for your visa meet your trip requirements as Russian visas cannot be altered once issued.<br/><br/>And please make sure the cities are pre-populated according to service level (which relates to VSD provider) and there is the ‘Why are these cities here?’ link.',

'Please select the cities that you will be visiting and also the hotels or hostels you will be staying in. If you are unsure or don&#39;t know where you will be staying then select any available hotel or hostel from the list. If you are visiting more than five cities then select either the largest ones or the ones that you will be spending the most time in.<br><br>If you are travelling along the Trans-Siberian, Trans-Mongolian or Trans-Manchurian railway then select &ldquo;Trans-Siberian railway&rdquo; as your city and &ldquo;Various – according to program&rdquo; for your hotel.',


'Please indicate the hotel(s) / accommodation address where you will be staying in at least one of the cities selected above. If you are unsure where you will be staying then simply write NOT YET KNOWN.',

'Select &ldquo;Yes&rdquo; ONLY if the child is listed in your passport AND is travelling with you to Russia.',
'If you need your passport back by a specific date, for example you need it to travel, then please select &ldquo;Yes&rdquo; and enter the date you require to receive the passport back by.<br><br>When we receive your application documents and if on the service level you have selected the visa can not be processed and returned to you in time to meet this date then we will attempt to contact you for instructions before we submit them to the consulate as per our standard terms and conditions.<br><br>If you answer &ldquo;No&rdquo; to this question then we will assume you do not need your passport back until the visa has been processed and returned on the service level you have selected.',

'<div id="divpr2"></div>','<div id="divd2"></div>',
'Please enter your name as it is printed in your passport, if you have had previous surnames, through marriage for example, please also enter these as well.<br><br>You should provide your current home address and also a working telephone number so we can contact you if required.<br><br>We will send order information and status updates to the email address you provide. Ensure that this you have access to and monitor it and that it does not block messages from our system.',
'Details about the passport you will use to apply for the visa are very important.<br><br>Finally, select the country that issued the passport you will be using. If you were born in the former USSR then you may need to provide proof that you no longer have or never had citizenship from that country with your application. ',
'Please enter the name, address and phone number of the company you work for or the educational establishment you are attending. The position is your job title if employed or &ldquo;student&rdquo; if you are in education.',

'<div id="divpr3"></div>','<div id="divd3"></div>',
'You should only select yes if you have blood relative who are Russian nationals actually living or resident in Russia now.<br><br>If you select &ldquo;Yes&rdquo; then you will need to provide the full details for each one. New relatives may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>',
'Only select &ldquo;Yes&rdquo; if you have been arrested or convicted of a Criminal offence.<br><br>If you select &ldquo;Yes&rdquo; then you will need to provide the country and date for each one. If there is more than one then new details may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'Only answer &ldquo;Yes&rdquo; if you were required to notify the authorities of the disease or condition by law, or, if you were a registered drug addict. Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'The question is self explanatory.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'If you select &ldquo;Yes&rdquo; then you will need to provide the country and year of issue for each Russian visa.<br><br>If there is more than one then new details may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>If you cannot remember them all then please list those you can and enter the fact that you cannot remember them all in the comments box at the end of this form.<br><br>We will also need you to tell us the month and year of your last visit to Russia, again if you cannot remember the approximate month and year is acceptable.',
'Select &ldquo;Yes&rdquo; if you have previously applied for a Russian visa and been refused.<br><br>You will need to provide the country where you applied and exact date of refusal for each refused Russian visa. If there is more than one then new details may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'Select &ldquo;Yes&rdquo; if you have had a Russian visa cancelled by the Russian authorities, other than for the purpose of issuing a new Russian visa.<br><br>You will need to provide the country where you applied and exact date of refusal for each refused Russian visa. If there is more than one then new details may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'Select &ldquo;Yes&rdquo; if you have been officially deported from the Russian Federation by the Russian authorities.<br><br>You will need to provide the country where you were deported to and exact date it occurred. If there is more than one then new details may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'Only answer &ldquo;Yes&rdquo; if you stayed in Russia after your visa had expired or were in Russia unlawfully.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'The question is self explanatory, if you answer &ldquo;Yes&rdquo; you will be required to briefly give details.<br><br>Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though you may be interviewed by a consular officer before they issue the visa.',
'The question is self explanatory, if you answer &ldquo;Yes&rdquo; you will be required to briefly give details.',
'The question is self explanatory, if you answer &ldquo;Yes&rdquo; you will be required to briefly give details.',
'The question is self explanatory, if you answer &ldquo;Yes&rdquo; you will be required to briefly give details.',
'Please list the countries you have visited in the last 10 years and indicate the year of visit.<br><br>If there are more than ten then new countries may be added to the form by clicking the &ldquo;Add next&rdquo; button that will be displayed.',
'Please select the countries that have ever issued you with a passport.',
'If you answer &ldquo;Yes&rdquo; then the consulate may require you provide evidence that you are no longer a Russian or citizen of a member of the FSU before they issue your visa.<br><br>Please note, that saying &ldquo;My Russian passport has expired&rdquo; does not mean you are no longer a Russian citizen and you will not be able to apply for a Russian visa using a &ldquo;foreign&rdquo; second passport.',
'Please note that answering &ldquo;Yes&rdquo; does not automatically signify ineligibility for a visa though the Russian consulate may require further information before they issue the visa.',
'If you answer &ldquo;Yes&rdquo; then we will require you to detail the your last two places of employment.<br><br>To add the second place of employment please click the &ldquo;Add next&rdquo; button.',
'If you answer &ldquo;Yes&rdquo; then we will require you to provide details of each educational establishment. If you can not remember or do not have the exact details then please enter your best guess.<br><br>If there are more than one, then new establishments may be added to the form by clicking the &ldquo;Add next&ldquo; button that will be displayed.',
'Only answer &ldquo;No&rdquo; if the person applying for the visa is not the person signing the application form.'];

/*
    if client age < 18 return true 
*/
function OnChangeDateOfBirth() {
    var dobDay = document.getElementById("dobDay");
    var dobMonth = document.getElementById("dobMonth");
    var dobYear = document.getElementById("dobYear");
    if ((dobDay.value != "Day") && (dobMonth.value != "Month") && (dobYear.value != "Year")) {
        var month = dobMonth.options[dobMonth.selectedIndex].text;
        switch (month) {
            case "January": month = 0; break;
            case "February": month = 1; break;
            case "March": month = 2; break;
            case "April": month = 3; break;
            case "May": month = 4; break;
            case "June": month = 5; break;
            case "July": month = 6; break;
            case "August": month = 7; break;
            case "September": month = 8; break;
            case "October": month = 9; break;
            case "November": month = 10; break;
            case "December": month = 11; break;
        }
        var dob = new Date();
        var day = dobDay.options[dobDay.selectedIndex].text;
        var day = day.substr(0, day.length - 2);
        dob.setMonth(month);
        dob.setDate(day);
        var year = dobYear.options[dobYear.selectedIndex].text;
        dob.setYear(year);
        var now = new Date();
        var fullyears = ((now - dob) / (1000 * 60 * 60 * 24 * 365));
        if (fullyears < 18) {
            alert("You are applying for a visa for someone under 18.  Please note, if the applicant has at least one parent who has a Russian passport and they will be entering Russia together, it is no longer possible to apply for a visa through an agency unless you have an original private invitation for the child.\r\n\r\nIf this does not apply, please continue; otherwise, please contact us for more information.");
        }
    }
}


window.onload = function () {

    /*@cc_on
    @if (@_jscript_version <= 5.6)
    var iframe = document.getElementById("mainDescDiv").appendChild(document.createElement("iframe"));
    iframe.src = "<html></html>";
    iframe.id = "shim";
    iframe.style.display = "none";
    @end@*/

    document.getElementById("dobDay").onchange = OnChangeDateOfBirth;
    document.getElementById("dobMonth").onchange = OnChangeDateOfBirth;
    document.getElementById("dobYear").onchange = OnChangeDateOfBirth;

    document.getElementById("moreTerms").onclick = openTerms;

    document.getElementById("previousClientMenu").onclick = showReturnClients;
    document.getElementById("loginButton").onclick = login;

    document.getElementById("visaType").onchange = visaTypeChanged;
    document.getElementById("visaService").onchange = setPriceFromCurrent;
    document.getElementById("consularService").onchange = setPriceFromCurrent;
    document.getElementById("purposeOfVisit").onchange = setPriceFromCurrent;
    document.getElementById("deliveryOption").onchange = deliveryChange;
    document.getElementById("deliveryRadio1").onclick = showotherAddressText;
    document.getElementById("deliveryRadio2").onclick = showotherAddressText;
    document.getElementById("deliveryRadio3").onclick = showotherAddressText;

    document.getElementById("insurance").onclick = setPriceFromCurrent;
    document.getElementById("saturday").onclick = setPriceFromCurrent;

    document.getElementById("homeAddressCountry").onchange = homeAddressCountryChanged;
    document.getElementById("visitArriveCityTo").onchange = visitArriveCitiesChanged;
    document.getElementById("visitDepartCityFrom").onchange = visitArriveCitiesChanged;

    document.getElementById("visitDayOfEntry").onchange = makevisa;
    document.getElementById("visitMonthOfEntry").onchange = makevisa;
    document.getElementById("visitYearOfEntry").onchange = makevisa;

    document.getElementById("passportCitzenship").onchange = function () {
        checkConsulateService();
        window.sameday = "true";
        setPriceFromCurrent();

        var obj = document.getElementById("passportCitzenship");
        var passportCitzenship = obj.options[obj.selectedIndex].text;
        setSelect(document.getElementById("passportCountry1"), passportCitzenship);

        if (in_array(passportCitzenship, visaFree.split(","))) {
            var texts = "";
            if (passportCitzenship == "Thailand") {
                texts = "Citizens of " + passportCitzenship + " do not require a visa for Russian Federation up to 30 days.";
            }
            else if (passportCitzenship == "Israel") {
                texts = "Isreali nationals may enter Russia as a tourist for visits of upto 90 days without a visa.";
            }
            else if (passportCitzenship == "Turkey") {
                texts = "Citizens of Turkey do not need a visa for trips of up to 30 days to the Russian Federation (the total time spent in the Russian Federation in the course of multiple visits must not exceed 90 days in any 180-day period).";
            }
            else {
                texts = "Citizens of " + passportCitzenship + " do not require a visa for Russian Federation.";
            }
            alert(texts);
        }

        FillVisaTypeSelectElement();
        FillVSDServicesForCitizenship();
    }

    document.getElementById("countryOfBirth").onchange = function () {
        countryOfBirthChange;
        showAddFields();
    }

    if (document.forms["theVisaForm"]) document.forms["theVisaForm"].reset();


    //document.getElementById("POWStatus").onchange = powStatusChanged;
    powStatusChanged(document.getElementById('POWStatus'));


    var cit = queryString["cit"];

    window.sameday = queryString["sameday"];
    // if(cit == "Canada") window.sameday = "false";

    if (typeof cit != "undefined") {
        var sl = document.getElementById('passportCitzenship');
        var cind;
        for (var i = 0, l = sl.options.length, cur; i < l; ++i) {
            cur = sl.options[i];
            if (cur.text == cit) {
                sl.selectedIndex = i;
                if (document.getElementById("passportCountry1"))
                    document.getElementById("passportCountry1").selectedIndex = i + 1;
                break;
            }
        }
    }

    //var service = queryString["service"].substring(0,4);
    var service = queryString["service"].split("-");
    switch (service[0]) {
        case "SE30": document.getElementById('visaType').selectedIndex = 0; break;
        case "SE90": document.getElementById('visaType').selectedIndex = 1; break;
        case "DE30": document.getElementById('visaType').selectedIndex = 2; break;
        case "DE90": document.getElementById('visaType').selectedIndex = 3; break;
        case "ME06": document.getElementById('visaType').selectedIndex = 4; break;
        case "ME12": document.getElementById('visaType').selectedIndex = 5; break;
    }
    switch (service[0].substring(0, 2)) {
        case "ME":
            switch (service[1]) {
                case "18": document.getElementById('visaService').selectedIndex = 0; break;
                case "14": document.getElementById('visaService').selectedIndex = 1; break;
                case "12": document.getElementById('visaService').selectedIndex = 2; break;
                case "12T": document.getElementById('visaService').selectedIndex = 3; break;
                //case "5": document.getElementById('visaService').selectedIndex = 3; break;    
                //case "3": document.getElementById('visaService').selectedIndex = 4; break;    
                case "0": document.getElementById('visaService').selectedIndex = 4; break;
            } break;
        case "SE":
            switch (service[1]) {
                case "12": document.getElementById('visaService').selectedIndex = 0; break;
                case "8": document.getElementById('visaService').selectedIndex = 1; break;
                case "5": document.getElementById('visaService').selectedIndex = 2; break;
                case "3": document.getElementById('visaService').selectedIndex = 3; break;
                case "2": document.getElementById('visaService').selectedIndex = 4; break;
                case "1": document.getElementById('visaService').selectedIndex = 5; break;
                //case "0.5": document.getElementById('visaService').selectedIndex = 6; break;    
                case "0": document.getElementById('visaService').selectedIndex = 6; break;
            } break;
        case "DE":
            switch (service[1]) {
                case "12": document.getElementById('visaService').selectedIndex = 0; break;
                case "8": document.getElementById('visaService').selectedIndex = 1; break;
                case "5": document.getElementById('visaService').selectedIndex = 2; break;
                case "3": document.getElementById('visaService').selectedIndex = 3; break;
                case "2": document.getElementById('visaService').selectedIndex = 4; break;
                case "1": document.getElementById('visaService').selectedIndex = 5; break;
                //case "0.5": document.getElementById('visaService').selectedIndex = 6; break;    
                case "0": document.getElementById('visaService').selectedIndex = 6; break;
            } break;
    }

    populateConsularService(service[2]);

    setSelected("purposeOfVisit", queryString["purpose"]);

    if (document.getElementById('maritalStatus')) document.getElementById('maritalStatus').onchange = showAddFields;
    if (document.getElementById('passportRusYes')) document.getElementById('passportRusYes').onclick = showAddFields;
    if (document.getElementById('passportRusNo')) document.getElementById('passportRusNo').onclick = showAddFields;
    if (document.getElementById('visitPays')) document.getElementById('visitPays').onchange = showAddFields;
    if (document.getElementById('visaBeforeYes')) document.getElementById('visaBeforeYes').onclick = showAddFields;
    if (document.getElementById('visaBeforeNo')) document.getElementById('visaBeforeNo').onclick = showAddFields;
    if (document.getElementById('visitArrestedYes')) document.getElementById('visitArrestedYes').onclick = showAddFields;
    if (document.getElementById('visitArrestedNo')) document.getElementById('visitArrestedNo').onclick = showAddFields;
    if (document.getElementById('visitAfflictedYes')) document.getElementById('visitAfflictedYes').onclick = showAddFields;
    if (document.getElementById('visitAfflictedNo')) document.getElementById('visitAfflictedNo').onclick = showAddFields;
    if (document.getElementById('visaRefusedYes')) document.getElementById('visaRefusedYes').onclick = showAddFields;
    if (document.getElementById('visaRefusedNo')) document.getElementById('visaRefusedNo').onclick = showAddFields;
    if (document.getElementById('visaCancelledYes')) document.getElementById('visaCancelledYes').onclick = showAddFields;
    if (document.getElementById('visaCancelledNo')) document.getElementById('visaCancelledNo').onclick = showAddFields;
    if (document.getElementById('visitDeportedYes')) document.getElementById('visitDeportedYes').onclick = showAddFields;
    if (document.getElementById('visitDeportedNo')) document.getElementById('visitDeportedNo').onclick = showAddFields;
    if (document.getElementById('specialisedSkillsYes')) document.getElementById('specialisedSkillsYes').onclick = showAddFields;
    if (document.getElementById('specialisedSkillsNo')) document.getElementById('specialisedSkillsNo').onclick = showAddFields;
    if (document.getElementById('militaryYes')) document.getElementById('militaryYes').onclick = showAddFields;
    if (document.getElementById('militaryNo')) document.getElementById('militaryNo').onclick = showAddFields;
    if (document.getElementById('conflictsYes')) document.getElementById('conflictsYes').onclick = showAddFields;
    if (document.getElementById('conflictsNo')) document.getElementById('conflictsNo').onclick = showAddFields;
    if (document.getElementById('visitRelativesYes')) document.getElementById('visitRelativesYes').onclick = showAddFields;
    if (document.getElementById('visitRelativesNo')) document.getElementById('visitRelativesNo').onclick = showAddFields;
    if (document.getElementById('personallyCompletedYes')) document.getElementById('personallyCompletedYes').onclick = showAddFields;
    if (document.getElementById('personallyCompletedNo')) document.getElementById('personallyCompletedNo').onclick = showAddFields;
    if (document.getElementById('organisationsYes')) document.getElementById('organisationsYes').onclick = showAddFields;
    if (document.getElementById('organisationsNo')) document.getElementById('organisationsNo').onclick = showAddFields;
    if (document.getElementById('previousJobYes')) document.getElementById('previousJobYes').onclick = showAddFields;
    if (document.getElementById('previousJobNo')) document.getElementById('previousJobNo').onclick = showAddFields;
    if (document.getElementById('moreEducationYes')) document.getElementById('moreEducationYes').onclick = showAddFields;
    if (document.getElementById('moreEducationNo')) document.getElementById('moreEducationNo').onclick = showAddFields;

    if (document.getElementById('pasportBackYes')) document.getElementById('pasportBackYes').onclick = showAddFields;
    if (document.getElementById('pasportBackNo')) document.getElementById('pasportBackNo').onclick = showAddFields;


    showAddFields();

    var myTabs = new YAHOO.widget.TabView('demo', { activeIndex: 0 });

    var infos = document.getElementsByTagName('img');
    for (var i = 0, num = 0, message; i < infos.length; i++) {
        if (infos[i].className.indexOf("imgTooltip") > -1) {
            infos[i].onclick = (function (mesNum) {
                return function () {
                    message = mes[mesNum];

                    if ((this.id == "tooltipP1") || (this.id == "tooltipP2") || (this.id == "tooltipP3")) message = replaceTooltipPrice();
                    if ((this.id == 'tooltipD1') || (this.id == 'tooltipD2') || (this.id == 'tooltipD3')) message = replaceTooltipDate();

                    showTooltip(window.event, this, message);

                    /*if ((this.id == "tooltipP1") || (this.id == "tooltipP2") || (this.id == "tooltipP3")) {
                        document.getElementById('myToolTip').style.left = '450px';
                        document.getElementById('myToolTip').style.width = '295px';

                    } else if ((this.id == 'tooltipD1') || (this.id == 'tooltipD2') || (this.id == 'tooltipD3')) {
                        document.getElementById('myToolTip').style.left = '550px';
                        document.getElementById('myToolTip').style.width = '295px';
                    } else { document.getElementById('myToolTip').style.left = '320px'; document.getElementById('myToolTip').style.width = '400px'; }
                    */
                    return false;
                }
            })(num);
            num++;
        }
    }

    setPriceFromCurrent("onload");

    //REMOVE!!!
    var debugConsole = document.getElementById('debugConsole');
    if (debugConsole) {
        with (debugConsole.style) {
            position = 'fixed';
            zIndex = '300';
            top = '300px';
            right = '40px';
            height = '300px';
            width = '200px';
            overflow = 'auto';
            background = 'white';
            border = '1px solid black';
            font = '10px Courier';
        }
    }

    ShowHighlightDates();
    document.getElementById("visitDayOfExit").onchange = ShowHighlightDates;
    document.getElementById("visitMonthOfExit").onchange = ShowHighlightDates;
    document.getElementById("visitYearOfExit").onchange = ShowHighlightDates;

    FillVisaTypeSelectElement();
    FillVSDServicesForCitizenship();

    populateVisaSupportServices(document.getElementById('visaType').selectedIndex);
}

function replaceTooltipPrice()
{
    return (document.getElementById('priceText'))? document.getElementById('priceText').value : '';
}

function replaceTooltipDate()
{
    return (document.getElementById('dateText'))? document.getElementById('dateText').value : '';
}

function addEvent(obj, evType, fn)
{ 
 	if (obj.addEventListener)
 	{ 
 	    obj.addEventListener(evType, fn, false); 
 	    return true; 
 	} 
 	else if (obj.attachEvent)
 	{ 
 	    var r = obj.attachEvent("on"+evType, fn); 
 	    return r; 
 	} 
 	else 
 	{ 
 	    return false; 
 	} 
}

//Vladimir start

var checkConsulateService = function () 
{
    var consularService = document.getElementById('consularService');
    var nationality = document.getElementById('passportCitzenship');
    nationality = nationality.options[nationality.selectedIndex].text;        
    if (nationality == "Turkey" || nationality == "India") 
    {
        consularService.options.length = 1;
        consularService.options[0].text = "Next Day";
        consularService.selectedIndex = 0;
    }
}

//Vladimir end

var populateConsularService = function(selectedInd)
{
    checkConsulateService();
    var consularService = document.getElementById('consularService');
    var nationality = document.getElementById("passportCitzenship");
    nationality = nationality.options[nationality.selectedIndex].text;
    if(window.sameday=="false") 
    {        
        if((nationality=='India')||(nationality=='Turkey'))
        {
            consularService.options.length = 1;
            consularService.options[0].text = "Next Day";
            consularService.selectedIndex = 0;
        } 
        else 
        {
            var procTime = "6 days";
            switch(nationality)
            {
                case "Australia": procTime = "10 to 14 days"; break;    
                case "Italy": procTime = "10 days"; break;    
                case "Netherlands": procTime = "10 days"; break;    
                case "United States": procTime = "10 to 14 days"; break;    
                case "Turkmenistan": procTime = "10 to 14 days"; break;
                case "France": procTime = "10 to 14 days"; break;    
            }
            consularService.options.length = 1;
            consularService.options[0].text = procTime;
        }
    } 
    else 
    {
        consularService.options.length = 2;
        consularService.options[0].text = "6 days";
        consularService.options[1].text = "Next Day";
        switch(selectedInd)
        {
            case "5": consularService.selectedIndex = 0; break;
            case "S": consularService.selectedIndex = 1; break;
        }
        checkConsulateService();
    }
}

var purposeOfVisitChange = function () {
    var vt = document.getElementById("visaType").options[document.getElementById("visaType").selectedIndex].text;
    var vsd = document.getElementById("visaService").options[document.getElementById("visaService").selectedIndex].text;
    var pov = document.getElementById("purposeOfVisit");
    var ind = pov.selectedIndex;



    var vsdProvider = "VisaNet";
    vt = vt.substring(0, 1);
    if (vsd.indexOf(" ") > 0) {
        vsd = vsd.substring(0, vsd.indexOf(" "));
    }
    else vsd = "Ex";

    if (vsd != "I") {
        if ((vt == "S") || (vt == "D")) {
            if ((vsd == "12") || (vsd == "8")) vsdProvider = "EWL";
            else vsdProvider = "VisaNet";
        }
        else if (vt == "M") {
            if ((vsd == "18") || (vsd == "14")) vsdProvider = "EWL";
            else if (vsd == "12") vsdProvider = "RH";
            else vsdProvider = "VisaNet";
        }
    }
    else vsdProvider = "ownVSD";

    var currentValue = pov.options[pov.selectedIndex].text;
    pov.options.length = 0;

    if ((vsdProvider == "CTO") || (vsdProvider == "RH")) {
        pov.options[0] = new Option("Business", "Business");
    }
    else if (vsdProvider == "EWL") {
        pov.options[0] = new Option("Business", "Business");
        pov.options[1] = new Option("Family member", "Family member");
        pov.options[2] = new Option("Sport", "Sport");
    }
    else if (vsdProvider == "VisaNet") {

        pov.options[0] = new Option("Business", "Business");
        pov.options[1] = new Option("Driver", "Driver");
        pov.options[2] = new Option("Family member", "Family member");
        if (vsd == "5") {
            pov.options[3] = new Option("Cultural", "Cultural");
        }
    }
    else if (vsdProvider == "ownVSD") {
        pov.options[0] = new Option("Business", "Business");
        pov.options[1] = new Option("Charity", "Charity");
        pov.options[2] = new Option("Commercial", "Commercial");
        pov.options[3] = new Option("Cultural", "Cultural");
        pov.options[4] = new Option("Diplomatic", "Diplomatic");
        pov.options[5] = new Option("Driver", "Driver");
        pov.options[6] = new Option("Family member", "Family member");
        pov.options[7] = new Option("Lecturing", "Lecturing");
        pov.options[8] = new Option("Private", "Private");
        pov.options[9] = new Option("Scientific", "Scientific");
        pov.options[10] = new Option("Sport", "Sport");
        pov.options[11] = new Option("Study", "Study");
        pov.options[12] = new Option("Teacher", "Teacher");
        pov.options[13] = new Option("Technical Support", "Technical Support");
        pov.options[14] = new Option("Tourist", "Tourist");
        pov.options[15] = new Option("Transit", "Transit");
        pov.options[16] = new Option("Work", "Work");
        pov.options[17] = new Option("Youth Work", "Youth Work");
    }

    setSelect(pov, currentValue);
}

var changeImportantInfo = function()
{
    var visaService = document.getElementById("visaService");
    var consularService = document.getElementById("consularService");
    var consularServiceValue=consularService.options[consularService.selectedIndex].text.toLowerCase();
    var details = document.getElementById('datesDetailsContainer');
    var details2 = document.getElementById('datesDetailsContainer2');
    var details3 = document.getElementById('datesDetailsContainer3');
    
    if (visaService.options[visaService.selectedIndex].text=="I have my own Visa Support")
    {
        document.getElementById('dateText').value =  '<div><strong>Important information</strong></div><span>The expected date of visa issue does not account for mail delivery of documents to us, Russian and UK public holidays and return postage back to you. It assumes that you apply online, pay and deliver all your documents to us today. If in doubt, please contact us and we will be happy to help.</span>';
        //details2.innerHTML = '<div>Important information</div><span>The expected date of visa issue does not account for Russian and UK public holidays (and is subject to there being space in our lodgement quota). It assumes that you apply online, pay and send your documents to us today. If in doubt, please contact us and we will be happy to help.</span>';
        //details3.innerHTML = '<div>Important information</div><span>The expected date of visa issue does not account for Russian and UK public holidays (and is subject to there being space in our lodgement quota). It assumes that you apply online, pay and send your documents to us today. If in doubt, please contact us and we will be happy to help.</span>';
    }
    else 
    {
        document.getElementById('dateText').value =  '<div><strong>Important information</strong></div><span>The expected date of visa issue does not account for Russian and UK public holidays or postage back to you if required. It assumes that you apply online, pay and send a scan or fax of your passport details page to us today, and deliver your original documents to us before the visa support document is ready. If in doubt, please contact us and we will be happy to help.</span>';
        //details2.innerHTML = '<div>Important information</div><span>The expected date of visa issue does not account for Russian and UK public holidays. It assumes that you apply online, pay and send a scan or fax of your passport page to us today. If in doubt, please contact us and we will be happy to help.</span>';
        //details3.innerHTML = '<div>Important information</div><span>The expected date of visa issue does not account for Russian and UK public holidays. It assumes that you apply online, pay and send a scan or fax of your passport page to us today. If in doubt, please contact us and we will be happy to help.</span>';
    }
}

function makevisa()
{    

    var nd = 0;
    var visaService_SelectHtmlElement = document.getElementById("visaType");
    var visaType = visaService_SelectHtmlElement.options[visaService_SelectHtmlElement.selectedIndex].text;
    switch (visaType) {
        case TypesVisaEnum.SE30: nd = 29; break;
        case TypesVisaEnum.SE90: nd = 89; break;
        case TypesVisaEnum.DE30: nd = 29; break;
        case TypesVisaEnum.DE90: nd = 89; break;
        case TypesVisaEnum.ME06: nd = 179; break;
        case TypesVisaEnum.ME12: nd = 364; break;
        case TypesVisaEnum.ME3Y: nd = 1092; break;
	    default: nd = 364;
	}

    if ((document.getElementById("visitDayOfEntry").selectedIndex==0)||(document.getElementById("visitMonthOfEntry").selectedIndex==0)||(document.getElementById("visitYearOfEntry").selectedIndex==0))
    {
	  	return false; 
	}
    var doent = document.getElementsByName("visitDayOfEntry")[0].selectedIndex + " " + document.getElementsByName("visitMonthOfEntry")[0].options[document.getElementsByName("visitMonthOfEntry")[0].selectedIndex].text + " " + document.getElementsByName("visitYearOfEntry")[0].options[document.getElementsByName("visitYearOfEntry")[0].selectedIndex].text;
    if (!isDate(document.getElementById("visitDayOfEntry").selectedIndex,document.getElementById("visitMonthOfEntry").selectedIndex-1,document.getElementById("visitYearOfEntry").options[document.getElementById("visitYearOfEntry").selectedIndex].text))
    {
        alert("The requested start date of the visa is invalid, please check it.");
        document.getElementById("visitDayOfEntry").focus();
        return false;
    }
    if ((new Date())>=(new Date(doent))) 
    {
        alert("The requested start date of the visa is in the past, please check it");
        hlite(document.getElementsByName("passportDayExpires")[0]);
        document.getElementById("visitDayOfEntry").focus();
        return false;
    }
    var newdate = new Date(doent);
    newdate.setDate(newdate.getDate()+nd);
    document.getElementsByName("visitDayOfExit")[0].selectedIndex = newdate.getDate();
    document.getElementsByName("visitMonthOfExit")[0].selectedIndex = newdate.getMonth()+1;
    document.getElementsByName("visitYearOfExit")[0].selectedIndex = newdate.getFullYear() - (new Date()).getFullYear()+1;
    
    ShowHighlightDates();
}

var visaTypeChanged = function () {
    ShowHighlightDates();
    populateVisaSupportServices(this.selectedIndex);
    changeImportantInfo();
    makevisa();
    purposeOfVisitChange();

    setPriceFromCurrent();
    var country = document.getElementById("passportCitzenship").value;    

};

var nextPage = function(pageNum)
{
    var myTabs = new YAHOO.widget.TabView('demo', { activeIndex: pageNum });
}

function showTr(obj)
{
    if (obj.id=="deliveryRadio3")
    {        
        document.getElementById("otherAddressTR").style.display="block";
    }
    else 
    {
        //obj.parentNode.parentNode.parentNode.className = "";
        document.getElementById("otherAddressTR").style.display="none";
    }
}

function showotherAddressText()
{
     obj = document.getElementById("deliveryRadio3").checked;
     if (obj)
     {
        //document.getElementById("whereToDeliver").className = "yellowBox";
        document.getElementById("otherAddressTR").style.display = "block";
     }
     else 
     {
        //document.getElementById("whereToDeliver").className = "";
        document.getElementById("otherAddressTR").style.display = "none";
     }
}

var getPriceFromCurrent = function () {
    var entry = ["SE30", "SE90", "DE30", "DE90", "ME06", "ME12", "ME3Y"][document.getElementById('visaType').selectedIndex];
    var snum = (entry.substring(0, 2) == "ME" ? [18, 14, 5, 3, 0] : [12, 8, 5, 3, 2, 1, 0.5, 0])[document.getElementById('visaService').selectedIndex] + "";

    var sameDayadd = [0, 65][document.getElementById('consularService').selectedIndex]; //as of 5 June 2008 margin is 65 and 62.5 for ownVSD
    var visaSupport = document.getElementById('visaService');
    if ((visaSupport.options[visaSupport.selectedIndex].text == 'I have my own Visa Support') && sameDayadd > 0) sameDayadd -= 2.5;

    var dnum = document.getElementById('deliveryOption').selectedIndex;
    var cit = document.getElementById('passportCitzenship');
    cit = cit.options[cit.selectedIndex].text;

    var deliveryPrice = getDeliveryPrice();
    var consMinus = (in_array(cit, EUCountries) ? tbl[entry].EUMinus : [0, 0])[sameDayadd > 0 ? 1 : 0]; //first value from tbl[visaEntry].EUMinus for 7 days, second one for Same day
    var visaPrice = tbl[entry][snum] + sameDayadd - consMinus;

    var newPrices = { 'SE30': -13, 'SE90': -13, 'DE30': -25, 'DE90': -25, 'ME06': -60, 'ME12': -60, 'ME3Y': -60 }
    var newPricesCountries = ['Angola', 'Bangladesh', 'Vietnam', 'India', 'Cambodia', 'Pakistan', 'Syria', 'Turkey', 'Japan'];
    if (in_array(cit, newPricesCountries)) visaPrice += newPrices[entry];

    var riskyAddition = !in_array(cit, allowed) ? tbl[entry].risky : 0;

    var consServiceList = { 0: 'Standard service', 1: 'Same day service' };

    var consService = consServiceList[document.getElementById('consularService').selectedIndex];
    var serviceList = {
        '0': 'i have my own visa support',
        '12': '12 working days',
        '8': '8 working days',
        '5': '5 working days',
        '3': '3 working days',
        '2': '2 working days',
        '1': '1 working day',
        '0.5': 'express',
        '18': '18 working days',
        '14': '14 working days'
    };
    var vsdSerice = document.getElementById('visaService').options[document.getElementById('visaService').selectedIndex].text.toLowerCase();
    var purposeOfVisit = document.getElementById('purposeOfVisit').options[document.getElementById('purposeOfVisit').selectedIndex].text.toLowerCase();

    var consularServiceText = document.getElementById('consularService').options[document.getElementById('consularService').selectedIndex].text;

    if (consularServiceText.toLowerCase() == 'next day') consService = 'Same day service';

    var price = new allPrices("Russian " + entry, consService, vsdSerice, "No registration service needed", "I will collect from your office", cit, "Moscow", false, "SE30-29808-2FA42F7-SM", purposeOfVisit);

    // alert("Russian "+entry +' , '+consService+', '+vsdSerice+' ,' + cit+', '+purposeOfVisit)
    riskyAddition = price.riskAddition;
    var consularFee = price.priceConsularFee;
    var VACFee = price.priceVacFee;
    var priceTTA = price.priceTTA;
    var priceVSDCost = price.priceVSDCost;
    var priceServeceFee = price.priceServeceFee;

    price = price.fullPrice - riskyAddition;

    return { priceVSDCost: priceVSDCost, priceServeceFee: priceServeceFee, priceTTA: priceTTA, VACFee: VACFee, consularFee: consularFee, visaPrice: price, deliveryPrice: deliveryPrice, riskyAddition: riskyAddition, total: price + riskyAddition + (deliveryPrice == "POA" ? 0 : deliveryPrice) };
};

function trigger_container_price() 
{ 
    var cont = document.getElementById("priceContainer"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function trigger_container_date() 
{ 
    var cont = document.getElementById("datesContainer"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function trigger_container_price2() 
{ 
    var cont = document.getElementById("priceContainer2"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function trigger_container_date2() 
{ 
    var cont = document.getElementById("datesContainer2"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function trigger_container_price3() 
{ 
    var cont = document.getElementById("priceContainer3"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function trigger_container_date3() 
{ 
    var cont = document.getElementById("datesContainer3"); 
    cont.className = cont.className == "withDetails" ? "" : "withDetails";
}

function calc_date(vsd, con,add)
{
	todays_date = new Date();
	total = vsd + con ;
	total=total+add;
	while(total != 0)
	{
        if(todays_date.getDay() == 6) 
        {
            todays_date.setDate(todays_date.getDate() + 2);
        }
        if(todays_date.getDay() == 0) 
        {
			todays_date.setDate(todays_date.getDate() + 1);
		}
        total = total - 1;
        todays_date.setDate(todays_date.getDate() + 1);
	}
	if (todays_date.getDay() == 6) 
	{
        todays_date.setDate(todays_date.getDate() + 2);
    }
    if (todays_date.getDay() == 0) 
    {
		todays_date.setDate(todays_date.getDate() + 1);
	}
    return todays_date;
}

var visaFree = "Turkey,Azerbaijan,Armenia,Belarus,Kazakhstan,Kirghizia,Cuba,Moldova,Tajikistan,Thailand,Uzbekistan,Ukraine,Israel,Kyrgyzstan,Macedonia" 

function visanetInfoShow()
{
    var cityDescDiv = document.getElementById("cityDescDiv");
    var shim = document.getElementById("shim");
    cityDescDiv.style.display = ""; 
    if (shim) shim.style.display = ""; 
}

function visanetInfoHide()
{
    var cityDescDiv = document.getElementById("cityDescDiv");
    cityDescDiv.style.display="none";
    var shim = document.getElementById("shim");
    if(shim)shim.style.display="none";
}

var changeLabels =function() 
{
    var purposeOfVisit = document.getElementById('purposeOfVisit');
    var visaService = document.getElementById('visaService');
    var invitationLabel = document.getElementById('invitingOrg_field');
    invitationLabel = invitationLabel.getElementsByTagName('label')[0];
    
    if (((purposeOfVisit)&&(visaService)&&(invitationLabel))&&(visaService.options[visaService.selectedIndex].text=="I have my own Visa Support"))
    {
        if (purposeOfVisit.options[purposeOfVisit.selectedIndex].text == "Private")
        {
            invitationLabel.title = "Please fill in the last, first and middle names of your host and their address and telephone number";
        } 
        else 
        {
            invitationLabel.title = "Please fill in the name of the host organisation and town";
        }
    }
}

var setPriceFromCurrent = function (param) {
    //alert(param);
    powStatusChanged();

    var visaService = document.getElementById('visaService');
    var entry = document.getElementById('visaType');
    var delivery = document.getElementById('deliveryOption');
    var entryNum = entry.selectedIndex;
    var visaSupportServiceNumber = visaService.selectedIndex;
    var purposeOfVisit = document.getElementById('purposeOfVisit');
    var purposeOfVisitNumber = purposeOfVisit.options[purposeOfVisit.selectedIndex].text;

    if ((purposeOfVisitNumber.toLowerCase() == 'private') && (entry.options[entryNum].text.substring(0, 1) == "M")) {
        alert("Sorry, multiple entry option is not possible for 'Private' visas.");
        document.getElementById('purposeOfVisit').focus();
        return false;
    }
    if (param != "onload") purposeOfVisitChange();
    setSelectedByText('purposeOfVisit', purposeOfVisitNumber);

    var country = document.getElementById('passportCitzenship');
    country = country.options[country.selectedIndex].text;
    if (param != "onload") {
        //if(country=="Canada") window.sameday = "false"; else window.sameday = "true";
        populateConsularService(document.getElementById('consularService').selectedIndex);
    }
    var visanetServ = visaService.options[visaSupportServiceNumber].text.substring(0, 2);
    var isVisanet = false;
    var visitCity1 = document.getElementById("visitCity1");
    var visitCity2 = document.getElementById("visitCity2");
    var visitCity3 = document.getElementById("visitCity3");
    var visitArriveCityTo = document.getElementsByName("visitArriveCityTo")[0];
    var visitDepartCityFrom = document.getElementsByName("visitDepartCityFrom")[0];
    var city1Desc = document.getElementById("city1Desc");

    var visanettext = '<h3><strong>Why have you pre-populated the city to be visited?</strong></h3><p>As you have selected a service for processing your visa support documents that is 5 working days or quicker we need to prepare the documents listing Moscow.</p><p>Don’t worry, this is a requirement of this type of service and you do not have to actually visit Moscow, nor are you restricted to only visiting the cities you list.</p><p>You may, if you choose, also add an additional two cities that you intend to visit.</p>';
    var ewltext = '<h3><strong>Why have you pre-populated the city to be visited?</strong></h3><p>As you have selected a service for processing your visa support documents that is more than 5 working days we need to prepare the documents listing Moscow.</p><p>Don’t worry, this is a requirement of this type of service and you do not have to actually visit Moscow, nor are you restricted to only visiting the cities you list.</p><p>You may, if you choose, also add an additional three cities that you intend to visit.</p>';
    var telextext = "<h3><strong>Why have you pre-populated the city to be visited?</strong></h3><p>As you have selected a Telex service for processing your visa support document we need to prepare the documents listing Moscow and St Petersburg.</p><p>Don\'t worry, this is a requirement of this type of service and you do not have to actually visit St Petersburg or Moscow, nor are you restricted to only visiting the cities you list.</p><p>You may, if you choose, also add an additional two cities that you intend to visit.</p>";
    if ((visanetServ == "Ex") || (visanetServ == "1 ") || (visanetServ == "2 ") || (visanetServ == "3 ") || (visanetServ == "5 "))
        isVisanet = true;
    // default
    //city1Desc.style.display = "none";
    visitCity1.disabled = false;
    visitCity2.disabled = false;
    visitCity3.disabled = false;
    visitCity1.selectedIndex = 0;
    visitCity2.selectedIndex = 0;
    visitCity3.selectedIndex = 0;
    visitArriveCityTo.selectedIndex = 67;
    visitArriveCityTo.disabled = false;
    visitDepartCityFrom.selectedIndex = 67;
    visitDepartCityFrom.disabled = false;
    //-------------------------------
    var visaServiceText = visaService.options[visaService.selectedIndex].text;
    if (isVisanet == true) {
        visitCity1.selectedIndex = 68;
        visitCity1.disabled = true;

        document.getElementById('cityDescDiv').innerHTML = visanettext;
    }
    else {

        if (visaServiceText == "I have my own Visa Support")
        //if (visanetServ=='I ')
        {
            //city1Desc.style.display = "none"; 
        }
        //else if (visanetServ=='12') //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        else if (visaServiceText == "12 Working Days (TELEX)") {
            visitCity1.selectedIndex = 118; //Piter
            visitCity1.disabled = true;
            visitCity2.selectedIndex = 68; //Moscow
            visitCity2.disabled = true;
            visitArriveCityTo.selectedIndex = 117; //Piter             
            visitDepartCityFrom.selectedIndex = 117; //Piter             
            document.getElementById('cityDescDiv').innerHTML = telextext;
        }
        else {
            visitCity1.selectedIndex = 68;
            visitCity1.disabled = true;
            visitCity2.selectedIndex = 0;
            visitCity2.disabled = false;
            //city1Desc.style.display = "inline";
            document.getElementById('cityDescDiv').innerHTML = ewltext;
        }
    }


    var consularProcessingNumber = document.getElementById('consularService').selectedIndex;
    var prices = getPriceFromCurrent();

    var table = "<table><tbody><thead><tr><th>Service breakdown</th><th>Price</th></tr></thead>";
    table += "<tr><td>" + entry.options[entryNum].text + "</td><td align='right'>&pound;" + prices.visaPrice.toFixed(2) + "</td></tr>";

    var priceServeceFeeClear = prices.priceServeceFee / 1.15;
    var priceVATServeceFee = priceServeceFeeClear * 0.15;
    var priceVACFeeClear = prices.VACFee / 1.15;
    var priceVATVACFee = priceVACFeeClear * 0.15;
    /*table += "<tr><td>Service Charge (Exclude VAT)</td><td><b>&pound;" + priceServeceFeeClear.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>VAT (Service Charge)</td><td><b>&pound;" + priceVATServeceFee.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>Consular fee</td><td><b>&pound;" + prices.consularFee.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>VAC fee (Exclude VAT)</td><td><b>&pound;" + priceVACFeeClear.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>VAT (VAC fee)</td><td><b>&pound;" + priceVATVACFee.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>VSD Cost</td><td><b>&pound;" + prices.priceVSDCost.toFixed(2) + "</b></td></tr>";
    table += "<tr><td>TTA</td><td><b>&pound;" + prices.priceTTA.toFixed(2) + "</b></td></tr>";        
    */
    var deliveryFee = 0;
    if (document.getElementById('insurance').checked) deliveryFee = 3.6;
    if (document.getElementById('saturday').checked) deliveryFee += 2.7;

    table += "<tr><td align='right'>" + getDeliveryName() + "</td><td  align='right'>" + (delivery.selectedIndex == 3 ? "POA" : "&pound;" + (getDeliveryPrice()).toFixed(2)) + "</td></tr>";

    if (prices.riskyAddition > 0) table += "<tr><td>Extra support fee for " + country + "</td><td align='right'>&pound;" + prices.riskyAddition.toFixed(2) + "</td></tr>"

    table += "</tbody><tfoot><tr><td><strong>Total: </strong></td><td align='right'><strong>&pound;" + (prices.total).toFixed(2) + "</strong></td></tr>";
    table += "</tfoot></table>";

    var div = document.getElementById('expectedPrice');
    var div2 = document.getElementById('expectedPrice2');
    var div3 = document.getElementById('expectedPrice3');

    div.innerHTML = 'Price: <b>&pound;' + (prices.total).toFixed(2) + "</b>";
    //div2.innerHTML = 'Price: <b>&pound;' + (prices.total + deliveryFee).toFixed(2) + "</b>";
    //div3.innerHTML = 'Price: <b>&pound;' + (prices.total + deliveryFee).toFixed(2) + "</b>";
    div2.innerHTML = 'Price: <b>&pound;' + (prices.total).toFixed(2) + "</b>";
    div3.innerHTML = 'Price: <b>&pound;' + (prices.total).toFixed(2) + "</b>";


    div = document.getElementById('priceText');
    if (div) div.value = table;

    div = document.getElementById('priceTextDetail');
    if (div) div.innerHTML = table;

    var datesDiv = document.getElementById('datesContainer');
    var datesDiv1 = document.getElementById('expectedDate');

    var datesDiv2 = document.getElementById('datesContainer2');
    var datesDiv21 = document.getElementById('expectedDate2');

    var datesDiv3 = document.getElementById('datesContainer3');
    var datesDiv31 = document.getElementById('expectedDate3');

    var vsd;
    if (visaService.options[visaSupportServiceNumber].text.substring(0, 2) == "I ") vsd = 0;
    else if (visaService.options[visaSupportServiceNumber].text.substring(0, 2) == "Ex") vsd = 0;
    else vsd = visaService.options[visaSupportServiceNumber].text.substring(0, 2) * 1;

    var service0 = ["SE30", "SE90", "DE30", "DE90", "ME06", "ME12"][entryNum]
    if ((service0 == "SE30") || (service0 == "SE90") || (service0 == "DE30") || (service0 == "DE90")) {
        var service1 = ["12", "8", "5", "3", "2", "1", "0.5", "0"][visaService.selectedIndex];
    }
    else if ((service0 == "ME06") || (service0 == "ME12")) {
        var service1 = ["18", "14", "12", "0"][visaService.selectedIndex];

    }
    var service2 = ["5", "1"][consularProcessingNumber];

    /*******/
    var vsdProc = 0;
    var addProc = 0;
    var citizenship = document.getElementById("passportCitzenship");
    citizenship = citizenship.options[citizenship.selectedIndex].text;
    if ((service0 == "SE30") || (service0 == "SE90") || (service0 == "DE30") || (service0 == "DE90")) {
        switch (service1 + "-" + service2) {
            case "12-5": consProc = 13; vsdProc = 6; addProc = 0; break;
            case "12-1": consProc = 13; vsdProc = 2; addProc = 0; break;
            case "8-5": consProc = 9; vsdProc = 6; addProc = 0; break;
            case "8-1": consProc = 9; vsdProc = 2; addProc = 0; break;
            case "5-5": consProc = 6; vsdProc = 6; addProc = 0; break;
            case "5-1": consProc = 6; vsdProc = 2; addProc = 0; break;
            case "3-5": consProc = 4; vsdProc = 6; addProc = 0; break;
            case "3-1": consProc = 4; vsdProc = 2; addProc = 0; break;
            case "2-5": consProc = 3; vsdProc = 6; addProc = 0; break;
            case "2-1": consProc = 3; vsdProc = 2; addProc = 0; break;
            case "1-5": consProc = 2; vsdProc = 6; addProc = 0; break;
            case "1-1": consProc = 2; vsdProc = 2; addProc = 0; break;
            case "0.5-5": consProc = 0; vsdProc = 6; addProc = 1; break;
            case "0.5-1": consProc = 0; vsdProc = 2; addProc = 1; break;
            case "0-5": consProc = 0; vsdProc = 6; addProc = 1; break;
            case "0-1": consProc = 0; vsdProc = 2; addProc = 1; break;
        }
    }
    if ((service0 == "ME06") || (service0 == "ME12")) {
        switch (service1 + "-" + service2) {
            case "18-5": consProc = 20; vsdProc = 6; addProc = 0; break;
            case "18-1": consProc = 20; vsdProc = 2; addProc = 0; break;
            case "14-5": consProc = 16; vsdProc = 6; addProc = 0; break;
            case "14-1": consProc = 16; vsdProc = 2; addProc = 0; break;
            case "12-5": consProc = 13; vsdProc = 6; addProc = 0; break;
            case "12-1": consProc = 13; vsdProc = 2; addProc = 0; break;
            case "5-5": consProc = 8; vsdProc = 6; addProc = 1; break;
            case "5-1": consProc = 8; vsdProc = 2; addProc = 1; break;
            case "3-5": consProc = 6; vsdProc = 6; addProc = 1; break;
            case "3-1": consProc = 6; vsdProc = 2; addProc = 1; break;
            case "0-5": consProc = 0; vsdProc = 6; addProc = 1; break;
            case "0-1": consProc = 0; vsdProc = 2; addProc = 1; break;            
        }
    }

    if (window.sameday == "false") {
        switch (citizenship) {
            case "Australia": vsdProc = 14; break;
            case "Italy": vsdProc = 10; break;
            case "Netherlands": vsdProc = 10; break;
            case "United States": vsdProc = 14; break;
            // case "Canada": vsdProc = 15; break;      
            case "Turkmenistan": vsdProc = 14; break;
            case "France": vsdProc = 14; break;
        }
    }
    /*********/
    var expectedDate = new Date(formatDate(calc_date(consProc, vsdProc, addProc)));

    expectedDate.year = expectedDate.getFullYear();
    expectedDate.month = "January,February,March,April,May,June,July,August,September,October,November,December".split(',')[expectedDate.getMonth()];
    expectedDate.day = expectedDate.getDate();
    expectedDate.properDate = [expectedDate.day, expectedDate.month, expectedDate.year].join(' ');

    datesDiv1.innerHTML = 'Expected date of issue: <b>' + expectedDate.properDate + '</b>'
    datesDiv21.innerHTML = 'Expected date of issue: <b>' + expectedDate.properDate + '</b>'
    datesDiv31.innerHTML = 'Expected date of issue: <b>' + expectedDate.properDate + '</b>'

    window.expectedPDate = expectedDate.properDate;

    if (document.getElementById('dateText')) document.getElementById('dateText').value = table;

    changeImportantInfo();
    //    var passportCitzenship = document.getElementById('passportCitzenship');
    //    passportCitzenship = passportCitzenship.options[passportCitzenship.selectedIndex].text;
    //    if (in_array(passportCitzenship, visaFree.split(","))) {
    //        var texts = "";
    //        if (passportCitzenship == "Thailand") {
    //            texts = "Citizens of " + passportCitzenship + " do not require a visa for Russian Federation up to 30 days.";
    //        }
    //        else if (passportCitzenship == "Israel") {
    //            texts = "Isreali nationals may enter Russia as a tourist for visits of upto 90 days without a visa.";
    //        }
    //        else if (passportCitzenship == "Turkey") {
    //            texts = "Citizens of Turkey do not need a visa for trips of up to 30 days to the Russian Federation (the total time spent in the Russian Federation in the course of multiple visits must not exceed 90 days in any 180-day period).";
    //        }
    //        else {
    //            texts = "Citizens of " + passportCitzenship + " do not require a visa for Russian Federation.";
    //        }
    //        if (param != "onload")
    //            alert(texts);
    //    }
    showAddFields();
    changeLabels();

    //this fucking one place for this
    FillVisaTypeSelectElement();    
    FillVSDServicesForCitizenship();

};

function deliveryChange()
{
    if ((this.selectedIndex==4)||(this.selectedIndex==5)||(this.selectedIndex==6))
    {
        document.getElementById("deliveryRadio2").checked = true;
        showTr(document.getElementById("deliveryRadio2"));
        document.getElementById("otherAddressTR").style.display="none";
        document.getElementById("DeliverTo").style.display="none";
    }
    else
    {
        document.getElementById("DeliverTo").style.display="block";
        if (document.getElementById("deliveryRadio3").checked) showTr(document.getElementById("deliveryRadio3"));
    }
    showAdditional(this);
    setPriceFromCurrent();
}

var populateVisaSupportServices = function (visaTypeNumber) {
    var visaType_SelectHtmlElement = document.getElementById("visaType");
    var visaType = visaType_SelectHtmlElement.options[visaTypeNumber].text;

    var visaService = document.getElementById('visaService');

    var currentVSDService = visaService.options[visaService.selectedIndex].text;

    if ((visaType == TypesVisaEnum.SE30) || (visaType == TypesVisaEnum.SE90) || (visaType == TypesVisaEnum.DE30) || (visaType == TypesVisaEnum.DE90)) {

        visaService.options.length = 6;

        visaService.options[0].text = "12 Working Days";
        visaService.options[1].text = "8 Working Days";
        visaService.options[2].text = "5 Working Days";
        visaService.options[3].text = "3 Working Days";
        visaService.options[4].text = "2 Working Days";
        //visaService.options[5].text = "1 Working Day";        
        visaService.options[5].text = "I have my own Visa Support";

    }
    else { //multiple visas

        visaService.options.length = 5;
        visaService.options[0].text = "18 Working Days";
        visaService.options[1].text = "14 Working Days";
        visaService.options[2].text = "12 Working Days";
        visaService.options[3].text = "12 Working Days (TELEX)";
        visaService.options[4].text = "I have my own Visa Support";
    }
    setSelect(visaService, currentVSDService);
};

function openVisaTypeInfo() 
{ 
    var newWin=window.open("bvsdinfo.asp", "VSDService", "width=560, height=390, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=no"); 
    return false;
}

function openVisaSupportInfo() 
{ 
    var newWin=window.open("bvisasupportinfo.asp", "VSDService", "width=560, height=410, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=no"); 
    return false;
}

function openConsularInfo() 
{ 
    var newWin=window.open("bconsularinfo.asp", "VSDService", "width=560, height=240, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=no"); 
    return false;
}

function openDeliveryInfo() 
{ 
    var newWin=window.open("bdeliveryinfo.asp", "VSDService", "width=560, height=575, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=no"); 
    return false;
}

function openPurposeOfVisitInfo()
{
    var newWin=window.open("bvsdinfo4.asp", "VSDService", "width=560, height=700, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=no"); 
    return false;
}

function openTerms()
{ 
    var newWin=window.open("../termsandconds2.asp","terms", "width=500, height=500, location=no, menubar=no, status=no, toolbar=no, scrollbars=yes, resizable=yes"); 
    return false;
}

function showReturnClients()
{
    if (opened == 0) {
        document.getElementById("previousClientFieldset").style.display = "block";
        plusHeight(); opened=1; seconds = 80; amount = 0; 
        document.getElementById("previousClientMenu").firstChild.data="Click here to close the list of previous orders.";
        document.getElementById("previousClientMenu").focus();
    }
    else {document.getElementById("previousClientFieldset").style.display = "block"; minusHeight(); opened=0; seconds = 80; amount = 0; 
        document.getElementById("previousClientMenu").firstChild.data="If you are a returning client, please click here to recover your personal details from our database to pre-fill the form below.";
        document.getElementById("previousClientMenu").focus();
    }
    return false;
}

function minusHeight()
{
    var obj = document.getElementById("previousClients")
    var curHeight = (obj.style.height + '').replace('px', '') * 1;
        if (curHeight > amount) 
        {
            obj.style.height = (curHeight - amount)+"px";
            window.setTimeout(minusHeight, seconds);
            if(seconds>8)seconds=seconds-12;
            amount=amount+1;
        }
        else{ obj.style.height = (curHeight - curHeight)+"px";  document.getElementById("previousClientFieldset").style.display = "none"; }
}
    
function plusHeight(){
    var obj = document.getElementById("previousClients")
    var curHeight = (obj.style.height + '').replace('px', '') * 1;
    if (curHeight <= maxHeight) {
        obj.style.height = (curHeight + amount)+"px";
        window.setTimeout(plusHeight, seconds);
        if(seconds>8)seconds=seconds-12;
        amount=amount+1;
    } 
}
var englandCounties = ["Avon","Bedfordshire","Berkshire","Bristol","Buckinghamshire","Cambridgeshire","Cheshire","Cleveland","Cornwall","Cumbria","Derbyshire","Devon","Dorset","Durham","East Riding of Yorkshire","East Sussex","Essex","Gloucestershire","Greater Manchester","Hampshire","Herefordshire","Hertfordshire","Humberside","Isle of Wight","Isles of Scilly","Kent","Lancashire","Leicestershire","Lincolnshire","London","Merseyside","Middlesex","Norfolk","North Yorkshire","Northamptonshire","Northumberland","Nottinghamshire","Oxfordshire","Rutland","Shropshire","Somerset","South Yorkshire","Staffordshire","Suffolk","Surrey","Tyne and Wear","Warwickshire","West Midlands","West Sussex","West Yorkshire","Wiltshire","Worcestershire"];

function login()
{
    if (document.getElementById("passportInput").value=="")
    { 
        alert("Please enter your passport number."); 
        document.getElementById("passportInput").focus(); 
        return; 
    }
    if (document.getElementById("yobInput").selectedIndex==0)
    {
        alert("Please select your year of birth."); 
        document.getElementById("yobInput").focus();  
        return;
    }
    yob = document.getElementById("yobInput").options[document.getElementById("yobInput").selectedIndex].text;
    passport = document.getElementById("passportInput").value;
    var request = getRequest();
    var url  = '/inc/autofillAjax.asp' + "?email=" + yob;
    url+="&passport=" +passport;
    url+="&country=Russian";
    url+="&mode=business";
    url+="&random="+ Math.random();
    request.open("GET", url, true);
    request.onreadystatechange = function()
    { 
        if (request.readyState == 4) 
        {            
           // document.getElementById("debug").innerHTML=request.responseText;
           // return;
            eval(request.responseText);
            document.getElementById("previousClients").innerHTML=ajaxValue.divHTML;
            window.hugeObject=ajaxValue.hugeObject;
            maxHeight=(document.getElementById('previousClients').getElementsByTagName('li').length+1)*21;
            if (document.getElementById('previousClients').getElementsByTagName('li').length==0) maxHeight = "90";
            opened=0; 
            seconds = 80; 
            amount = 0;
            showReturnClients();
            try 
            {
                document.getElementById("loginButton").onclick = login;
            } 
            catch(e)
            {
            }        
       } 
  };
  request.send("e");
}

function getCountry(visaId){
    if(visaId.substring(0,2)=="SS") {result = "Russian"; }
    if(visaId.substring(0,2)=="SD") {result = "Russian"; }
    if(visaId.substring(0,2)=="TS") {result = "Russian"; }
    if(visaId.substring(0,2)=="TD") {result = "Russian"; }
    if(visaId.substring(0,2)=="SE") {result = "Russian"; }
    if(visaId.substring(0,2)=="DE") {result = "Russian"; }
    if(visaId.substring(0,2)=="ME") {result = "Russian"; }
    if(visaId.substring(0,1)=="B")  {result = "Belarusian"; }
    if(visaId.substring(0,2)=="CT") {result = "Chinese"; }
    if(visaId.substring(0,1)=="K")  {result = "Kazakh"; }
    if(visaId.substring(0,3)=="MTS") {result = "Mongolian";}
    return result;
}
function setSelect(selectInput, selectedValue){
    for(var i=0; i<selectInput.length;i++){if(selectInput.options[i].text==selectedValue){selectInput.selectedIndex = i; continue;}}
}

//Vladimir start
function clearPOWFields() {
 document.getElementById('POWName').value = ''; 
 document.getElementById('POWPosition').value = '';
 document.getElementById('POWAddress').value = '';
 document.getElementById('POWPostcode').value = '';
 document.getElementById('POWTelephone').value = '';
}

//Vladimir end
function fillRecord(visaId)
{
    var toClear = false;
    for (refnum in hugeObject[visaId]) 
    {
        if (hugeObject[visaId][refnum]!=null)
        {
            if (refnum=="gender") 
            {
                if (hugeObject[visaId][refnum]=="Male") document.getElementsByName(refnum)[0].checked=true;
                if (hugeObject[visaId][refnum]=="Female") document.getElementsByName(refnum)[1].checked=true;
                continue;
            }
            if (refnum=="dateOfBirth") //??????????????????
            {

                var dofb = dateParser["ddMMmmyyyy"](hugeObject[visaId][refnum]);
                if ((dofb == 'Invalid Date') || (isNaN(dofb)))
                    dofb = dateParser["ddmmyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("dobDay").selectedIndex= dofb.getDate();
                document.getElementById("dobMonth").selectedIndex= dofb.getMonth()+1;
                var now = new Date();
                document.getElementById("dobYear").selectedIndex= now.getFullYear()-dofb.getFullYear()+1;
                continue;
            }
            if (refnum=="passportIssued")  //??????????????????
            {
                var pasis =  dateParser["ddMMmmyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("passportDayIssued").selectedIndex= pasis.getDate();
                document.getElementById("passportMonthIssued").selectedIndex= pasis.getMonth()+1;
                var now = new Date();
                document.getElementById("passportYearIssued").selectedIndex= now.getFullYear()-pasis.getFullYear()+1;
                continue;
            }
            if (refnum=="passportIssuedBy")  //??????????????????
            {
                document.getElementById("passortIssuedBy").value=hugeObject[visaId][refnum];
                continue;
            }

            if (refnum=="passportExpires") //??????????????????
            {
                var pasex =  dateParser["ddMMmmyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("passportDayExpires").selectedIndex= pasex.getDate();
                document.getElementById("passportMonthExpires").selectedIndex= pasex.getMonth()+1;
                var now = new Date();
                document.getElementById("passportYearExpires").selectedIndex= pasex.getFullYear()-now.getFullYear()+1;
                continue;
            }
            if (refnum=="countryOfBirth") 
            {
                setSelect(document.getElementById("countryOfBirth"),hugeObject[visaId][refnum]);
                continue;
            }
            if (refnum=="passportCitzenship") 
            {
                setSelect(document.getElementsByName("passportCitzenship")[0],hugeObject[visaId][refnum]);
                continue;
            }
            if (refnum=="POWAddress") 
            {
                document.getElementsByName(refnum)[0].value=hugeObject[visaId][refnum].replace(/##/g,"\r\n");
                continue;
            }    
            if (refnum=="POWPostcode")
            {                
                document.getElementById('POWPostcode').value=hugeObject[visaId][refnum];
                continue;
            }
            if (refnum=="POWTelephone")
            {                
                document.getElementById('POWTelephone').value=hugeObject[visaId][refnum];
                continue;
            }
            if (refnum=="maritalStatus")
            {           
                setSelect(document.getElementById("maritalStatus"),hugeObject[visaId][refnum]);
                if (hugeObject[visaId][refnum]=="Married")
                {
                    document.getElementById("add_spousename").style.display="";                    
                }                
                continue;
            }
            if (refnum=="spouseName")
            {
               document.getElementById('spouseName').value=hugeObject[visaId][refnum];
               continue;
            }
            if (refnum=="spousePlaceOfBirth")
            {
               document.getElementById('spousePlaceOfBirth').value=hugeObject[visaId][refnum];
               continue;
           }
           if (refnum == "spouseCityOfBirth") {
               document.getElementById('spouseCityOfBirth').value = hugeObject[visaId][refnum];
               continue;
           }
            if (refnum=="spouseDob")
            {                
                var pasex =  dateParser["ddMMMMyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("spouseDobDay").selectedIndex= pasex.getDate();
                document.getElementById("spouseDobMonth").selectedIndex= pasex.getMonth()+1;
                var now = new Date();
                document.getElementById("spouseDobYear").selectedIndex= pasex.getFullYear()-now.getFullYear()+1;
                continue;
            }
            if (refnum == "fatherFirstName") {
                document.getElementById('fatherFirstName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum == "fatherMiddleName") {
                document.getElementById('fatherMiddleName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum == "fatherName") {
                document.getElementById('fatherSurName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum == "motherFirstName") {
                document.getElementById('motherFirstName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum == "motherMiddleName") {
                document.getElementById('motherMiddleName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum == "motherName") {
                document.getElementById('motherSurName').value = hugeObject[visaId][refnum];
                continue;
            }
            if (refnum=="visitRelatives")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visitRelativesYes').checked=true;
                    document.getElementById('add_visitRelatives').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visitRelativesNo').checked=true;
                }
                continue;                
            }
            //AHTUNG PIZDC!
            if (refnum=="visitRelativesName")            
            {                   
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visitRelatives');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {
                    
                    if ((mas[i].getAttribute("type")=="text")&&(mas[i].id=="visitRelativesName1"))
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }
                
                continue;    
            }
            if (refnum=="visitRelativesRelation")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var parentNode = document.getElementById('add_visitRelatives');
                mas=parentNode.getElementsByTagName("input");                
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if ((mas[i].getAttribute("type")=="text")&&(mas[i].id=="visitRelativesRelation1"))
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }
                continue;
            }
            if (refnum=="visitRelativesDob")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visitRelatives');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="visitRelativesDobDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="visitRelativesDobMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="visitRelativesDobYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;
            }
            if (refnum=="visitRelativesAddress")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visitRelatives');
                mas=parentNode.getElementsByTagName("textarea");
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visitRelativesAddress1")
                    {
                        mas[i].innerText=arr[k].replace(/##/g,"\r\n");
                        k++;
                    }
                }
                continue;
            }
            if (refnum=="visitArrested")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visitArrestedYes').checked=true;
                    document.getElementById('add_visitArrestedDetails').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visitArrestedNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visitArrestedCountry")            
            {                   
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visitArrestedDetails');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("select");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visitArrestedCountry1")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;    
            }
            if (refnum=="visitArrestedDates")            
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visitArrestedDetails');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="visitArrestedDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="visitArrestedMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="visitArrestedYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;             
            }            
            if (refnum=="visitAfflicted")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visitAfflictedYes').checked=true;                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visitAfflictedNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visaFalseInfo")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visaFalseInfoYes').checked=true;                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visaFalseInfoNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visaBefore")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visaBeforeYes').checked=true;
                    document.getElementById('add_visaBeforeDetails').style.display=""; 
                    document.getElementById('add_visitLastMonth').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visaBeforeNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visaIssueCountry")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visaBeforeDetails');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("select");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visaCountry1")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="visaCountryYear")
            {
                var str = hugeObject[visaId][refnum];
                var arr = str.split("||");
                var parentNode = document.getElementById('add_visaBeforeDetails');
                mas = parentNode.getElementsByTagName("select");
                var pasex;
                for (i = 0, k = 0; i < mas.length, k < arr.length; i++) {
                    if (mas[i].id == "visaCountryDay1") {
                        pasex = dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex = pasex.getDate();
                    }
                    else if (mas[i].id == "visaCountryMonth1") {
                        pasex = dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex = pasex.getMonth() + 1;
                    }
                    else if (mas[i].id == "visaCountryYear1") {
                        pasex = dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();
                        setSelect(mas[i], pasex.getFullYear());
                        k++;
                    }
                }
                continue;           
            }
            if (refnum=="visitLastDate")
            {
                var pasex =  dateParser["ddMMMMyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("visitLastDay").selectedIndex= pasex.getDate();
                document.getElementById("visitLastMonth").selectedIndex= pasex.getMonth()+1;
                var now = new Date();
                setSelect(document.getElementById("visitLastYear"),pasex.getFullYear());                
                continue;
            }
            if (refnum=="visitLastDateExit")
            {
                var pasex =  dateParser["ddMMMMyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("visitLastDayExit").selectedIndex= pasex.getDate();
                document.getElementById("visitLastMonthExit").selectedIndex= pasex.getMonth()+1;
                var now = new Date();
                setSelect(document.getElementById("visitLastYearExit"),pasex.getFullYear());                
                continue;
            }
            if (refnum=="visaRefused")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visaRefusedYes').checked=true;
                    document.getElementById('add_visaRefusedDatails').style.display="";            
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visaRefusedNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visaRefusedCountry")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visaRefusedDatails');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("select");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visaRefusedCountry1")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="visaRefusedDates")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visaRefusedDatails');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="visaRefusedDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="visaRefusedMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="visaRefusedYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;   
            }
            if (refnum=="visaCancelled")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visaCancelledYes').checked=true;
                    document.getElementById('add_visaCancelledDetails').style.display="";            
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visaCancelledNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visaCancelledCountry")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visaCancelledDetails');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("select");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visaCancelledCountry1")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="visaCancelledDates")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visaCancelledDetails');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="visaCancelledDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="visaCancelledMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="visaCancelledYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;   
            }
            if (refnum=="visitDeported")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visitDeportedYes').checked=true;
                    document.getElementById('add_visitDeportedDetails').style.display="";            
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visitDeportedNo').checked=true;
                }
                continue;                
            }
            if (refnum=="visitDeportedCountry")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_visitDeportedDetails');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("select");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="visitDeportedCountry1")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="visitDeportedDates")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_visitDeportedDetails');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="visitDeportedDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="visitDeportedMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="visitDeportedYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;   
            }
            if (refnum=="visaOverstayed")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('visaOverstayedYes').checked=true;                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('visaOverstayedNo').checked=true;
                }
                continue;                
            }
            if (refnum=="specialisedSkills")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('specialisedSkillsYes').checked=true;                    
                    document.getElementById('add_specialisedSkillsList').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('specialisedSkillsNo').checked=true;
                }
                continue;                
            }
            if (refnum=="specialisedSkillsList")            
            {
                document.getElementById('specialisedSkillsList').value=hugeObject[visaId][refnum];
                continue;                
            }
            if (refnum=="organisationsQ")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('organisationsYes').checked=true;                    
                    document.getElementById('organisationsDetails').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('organisationsNo').checked=true;
                }
                continue;                
            }
            if (refnum=="organisations")            
            {
                document.getElementById('organisations').value=hugeObject[visaId][refnum];
                continue;                
            }
            if (refnum=="militaryService")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('militaryYes').checked=true;                    
                    document.getElementById('add_militaryList').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('militaryNo').checked=true;
                }
                continue;                
            }
            if (refnum=="militaryList")            
            {
                document.getElementById('militaryList1').value=hugeObject[visaId][refnum];
                continue;                
            }
            if (refnum=="conflicts")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('conflictsYes').checked=true;                    
                    document.getElementById('add_conflictsDetails').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('conflictsNo').checked=true;
                }
                continue;                
            }
            if (refnum=="conflictsDetails")            
            {
                document.getElementById('conflictsDetails').value=hugeObject[visaId][refnum];
                continue;                
            }
            if (refnum=="visitCountry")            
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var N=arr.length-8;
                var i=0,k=0;
                var parentNode = document.getElementById('add_visitCountry');
                var mas=parentNode.getElementsByTagName("input");
                
                for (k=0;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }
                
                mas=parentNode.getElementsByTagName("select");
                k=0;
                N=arr.length;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].name=="visitCountry")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;                           
            }
            if (refnum=="visitCountryYear") 
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var parentNode = document.getElementById('add_visitCountry');
                mas=parentNode.getElementsByTagName("select");
                k=0;
                N=arr.length;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].name=="visitCountryYear")
                    {
                        setSelect(mas[i],arr[k]);
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="passportCountry") 
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                               
                if (arr[0]!=null)
                    setSelect(document.getElementById('passportCountry1'),arr[0]);
                if (arr[1]!=null)
                    setSelect(document.getElementById('passportCountry2'),arr[1]);
                if (arr[2]!=null)
                    setSelect(document.getElementById('passportCountry3'),arr[2]);
                continue;
            }
            if (refnum=="passportRus")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('passportRusYes').checked=true;                    
                    document.getElementById('add_citzLost').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('passportRusNo').checked=true;
                }
                continue;                
            }
            if (refnum=="citzLostDate")
            {
                var pasex =  dateParser["ddMMMMyyyy"](hugeObject[visaId][refnum]);
                document.getElementById("citzLostDay").selectedIndex= pasex.getDate();
                document.getElementById("citzLostMonth").selectedIndex= pasex.getMonth()+1;
                var now = new Date();
                setSelect(document.getElementById("citzLostYear"),pasex.getFullYear());                
                continue;
            }
            if (refnum=="citzLostReason")            
            {
                document.getElementById('citzLostReason').value=hugeObject[visaId][refnum];
                continue;                
            }
            if (refnum=="passportStolen")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('passportStolenYes').checked=true;                    
                    document.getElementById('add_conflictsDetails').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('passportStolenNo').checked=true;
                }
                continue;                
            }
            if (refnum=="previousJob")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('previousJobYes').checked=true;                    
                    document.getElementById('add_company_details').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('previousJobNo').checked=true;
                }
                continue;                
            }
            if (refnum=="companyName")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_company_details');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="companyName1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="companyPosition")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="companyPosition1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="companyStart")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="companyStartDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="companyStartMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="companyStartYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;
            }
            if (refnum=="companyEnd")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="companyEndDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="companyEndMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="companyEndYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;
            }
            if (refnum=="companyManager")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="companyManager1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="companyAddress")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("textarea");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="companyAddress1")
                    {
                        mas[i].innerText=arr[k].replace(/##/g,"\r\n");
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="companyTelephone")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_company_details');
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="companyTelephone1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="moreEducation")            
            {                
                if (hugeObject[visaId][refnum]=="Yes")
                {
                    document.getElementById('moreEducationYes').checked=true;                    
                    document.getElementById('add_education_details').style.display="";                    
                }
                else if (hugeObject[visaId][refnum]=="No")
                {
                    document.getElementById('moreEducationNo').checked=true;
                }
                continue;                
            }
            if (refnum=="educationName")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_education_details');
                var mas=parentNode.getElementsByTagName("input");
                N=arr.length;                
                for (k=1;k<N;k++)
                {
                    for (i=0;i<mas.length;i++)
                    {                           
                        if (mas[i].value=="Add next")
                        {
                            mas[i].click();                                                    
                            break;
                        }
                    }
                }                                    
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="educationName1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="educationCourse")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_education_details');                                                 
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="educationCourse1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;   
            }
            if (refnum=="educationStart")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_education_details');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="educationStartDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="educationStartMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="educationStartYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;
            }
            if (refnum=="educationEnd")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");                
                var parentNode = document.getElementById('add_education_details');
                mas=parentNode.getElementsByTagName("select");
                var pasex;                
                for (i=0,k=0;i<mas.length,k<arr.length;i++)
                {                    
                    if (mas[i].id=="educationEndDay1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getDate();
                    }
                    else if (mas[i].id=="educationEndMonth1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        mas[i].selectedIndex= pasex.getMonth()+1;                        
                    }                        
                    else if (mas[i].id=="educationEndYear1")
                    {                            
                        pasex =  dateParser["ddMMMMyyyy"](arr[k]);
                        var now = new Date();                        
                        setSelect(mas[i],pasex.getFullYear());
                        k++;                            
                    }
                }  
                continue;
            }
            if (refnum=="educationAddress")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_education_details');
                mas=parentNode.getElementsByTagName("textarea");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="educationAddress1")
                    {
                        mas[i].innerText=arr[k].replace(/##/g,"\r\n");
                        k++;
                    }
                }                
                continue;
            }
            if (refnum=="educationTelephone")
            {
                var str=hugeObject[visaId][refnum];
                var arr=str.split("||");
                var i=0, N,k=0;
                var parentNode = document.getElementById('add_education_details');
                mas=parentNode.getElementsByTagName("input");
                k=0;
                for (i=0,k=0;i<mas.length,k<N;i++)
                {                    
                    if (mas[i].id=="educationTelephone1")
                    {
                        mas[i].value=arr[k];
                        k++;
                    }
                }                
                continue;
            }
            
            
            if (refnum=="POWStatus") 
            {
                var POWStatusValue = hugeObject[visaId][refnum];
                if (POWStatusValue == "Unemployed" || POWStatusValue == "Homemaker" || POWStatusValue == "Retired" || POWStatusValue == "Infant") 
                {
                  toClear = true;
                }
                else 
                {
                  toClear = false;
                }     
        		var PS=document.getElementById('POWStatus');
                setSelect(PS, POWStatusValue);
                powStatusChanged();                 
                continue;
            }
            if (refnum=="homeAddress") 
            {
                if (hugeObject[visaId][refnum]!="")
                {
                    var myArray = hugeObject[visaId][refnum].split("##");
                    switch(getCountry(visaId))
                    {
                    case "Russian":
                        document.getElementsByName("homeAddress1")[0].value = myArray[0];
                        document.getElementsByName("homeAddress2")[0].value = myArray[1];
                        document.getElementsByName("homeAddressCity")[0].value = myArray[2];
                        var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                        if ((myArray[5]!="United Kingdom")||(myArray[5]==""))
                        {
                            homeAddressCounty.selectedIndex = 0; 
                            homeAddressCounty.disabled=true;
                        }
                        else
                        {
                            setSelect(homeAddressCounty,myArray[3]); 
                            homeAddressCounty.disabled=false;
                        }
                        if ((typeof myArray[5]=='undefined')&&(myArray[3]!=""))
                        {
                            homeAddressCounty.disabled=false; 
                            setSelect(homeAddressCounty,myArray[3]);
                        }
                        document.getElementsByName("homeAddressPostCode")[0].value = myArray[4];
                        setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[5]);
                        break;
                    case "Belarusian":
                        document.getElementsByName("homeAddress1")[0].value = myArray[0];
                        document.getElementsByName("homeAddressCity")[0].value = myArray[1];
                        var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                        if ((myArray[4]!="United Kingdom")&&(myArray[4]!=""))
                        {
                            homeAddressCounty.selectedIndex = 0; 
                            homeAddressCounty.disabled=true;
                         }
                        else
                        { 
                            homeAddressCounty.disabled=false; 
                            setSelect(homeAddressCounty,myArray[2]);
                        }
                        if ((typeof myArray[4]=='undefined')&&(myArray[2]!=""))
                        {
                            homeAddressCounty.disabled=false; 
                            setSelect(homeAddressCounty,myArray[2]);
                        }
                        document.getElementsByName("homeAddressPostCode")[0].value = myArray[3];
                        setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[4]);
                        break;
                    case "Chinese":
                        document.getElementsByName("homeAddress1")[0].value = myArray[0];
                        document.getElementsByName("homeAddress2")[0].value = myArray[1];
                        document.getElementsByName("homeAddressCity")[0].value = myArray[2];
                        var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                        if(myArray.length==6)
                        {
                            setSelect(homeAddressCounty,myArray[3]);
                            homeAddressCounty.disabled=false;
                            document.getElementsByName("homeAddressPostCode")[0].value = myArray[5];
                            setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[4]);
                        }
                        else
                        {
                            homeAddressCounty.selectedIndex = 0; 
                            homeAddressCounty.disabled=true;
                            document.getElementsByName("homeAddressPostCode")[0].value = myArray[4];
                            setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[3]);
                        }
                        break;
                    case "Kazakh":
                        if (myArray.length==6)
                        {
                            document.getElementsByName("homeAddress1")[0].value = myArray[0];
                            document.getElementsByName("homeAddressCity")[0].value = myArray[2];
                            var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                            setSelect(homeAddressCounty,myArray[3]);homeAddressCounty.disabled=false;
                            document.getElementsByName("homeAddressPostCode")[0].value = myArray[4];
                            setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[5]);
                        } 
                        else if (myArray.length==4)
                        {
                            document.getElementsByName("homeAddress1")[0].value = myArray[0];
                            document.getElementsByName("homeAddressCity")[0].value = myArray[1];
                            document.getElementsByName("homeAddressPostCode")[0].value = myArray[2];
                            setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[3]);
                            var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                            homeAddressCounty.disabled=true;
                        } 
                        else 
                        {
                            if (in_array(myArray[2],englandCounties)==false)
                            {
                                document.getElementsByName("homeAddress1")[0].value = myArray[0];
                                document.getElementsByName("homeAddress2")[0].value = myArray[1];
                                document.getElementsByName("homeAddressCity")[0].value = myArray[2];
                                document.getElementsByName("homeAddressPostCode")[0].value = myArray[3];
                                setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[4]);
                                var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                                homeAddressCounty.disabled=true;
                            }
                            if (in_array(myArray[2],englandCounties)==true)
                            {
                                document.getElementsByName("homeAddress1")[0].value = myArray[0];
                                document.getElementsByName("homeAddressCity")[0].value = myArray[1];
                                var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                                if ((myArray[4]!="United Kingdom")||(myArray[4]==""))
                                {
                                    homeAddressCounty.selectedIndex = 0; 
                                    homeAddressCounty.disabled=true;
                                }
                                else
                                {
                                    setSelect(homeAddressCounty,myArray[2]);
                                    homeAddressCounty.disabled=false;
                                }
                                if ((typeof myArray[4]=='undefined')&&(myArray[2]!=""))
                                {
                                    homeAddressCounty.disabled=false; 
                                    setSelect(homeAddressCounty,myArray[2]);
                                }
                                document.getElementsByName("homeAddressPostCode")[0].value = myArray[3];
                                setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[4]);
                            }
                        } 
                        break;
                    case "Mongolian":
                        document.getElementsByName("homeAddress1")[0].value = myArray[0];
                        document.getElementsByName("homeAddressCity")[0].value = myArray[1];
                        var homeAddressCounty = document.getElementsByName("homeAddressCounty")[0];
                        if ((myArray[3]!="United Kingdom")||(myArray[3]==""))
                        {
                            homeAddressCounty.selectedIndex = 0; 
                            homeAddressCounty.disabled=true;
                        }
                        else 
                        {
                            setSelect(homeAddressCounty,myArray[2]);
                            homeAddressCounty.disabled=false;
                        }
                        if ((typeof myArray[3]=='undefined')&&(myArray[2]!=""))
                        {
                            homeAddressCounty.disabled=false; 
                            setSelect(homeAddressCounty,myArray[2]);
                        }
                        document.getElementsByName("homeAddressPostCode")[0].value = myArray[4];
                        setSelect(document.getElementsByName("homeAddressCountry")[0],myArray[3]);
                        break;
                    }
                } 
                else
                {
                    document.getElementsByName("homeAddress1")[0].value = "";
                    document.getElementsByName("homeAddress2")[0].value="";
                    document.getElementsByName("homeAddressCity")[0].value="";
                    document.getElementsByName("homeAddressCounty")[0].selectedIndex=0;
                    document.getElementsByName("homeAddressPostCode")[0].value="";
                    document.getElementsByName("homeAddressCountry")[0].selectedIndex=window.__oldCitizenship+1;
                }  
                continue;
            }   
           document.getElementsByName(refnum)[0].value=hugeObject[visaId][refnum];
        }
        if (toClear)
         clearPOWFields();
    }
    seconds = 80; 
    amount = 0;
    minusHeight();
    seconds = 80; 
    amount = 0;
    opened = 0;
    document.getElementById("previousClientMenu").firstChild.data="If you are a returning client, please click here to recover your personal details from our database to pre-fill the form below.";
    document.getElementById("visaType").focus();
}

var visitArriveCitiesChanged = function() {
    var visitDepartCityFrom = document.getElementById("visitDepartCityFrom"); 
    visitDepartCityFrom = visitDepartCityFrom.options[visitDepartCityFrom.selectedIndex].text;
    var visitArriveCityTo = document.getElementById("visitArriveCityTo"); 
    visitArriveCityTo = visitArriveCityTo.options[visitArriveCityTo.selectedIndex].text;
    var vcity4 = document.getElementById("visitCity4");
    var lastCity = document.getElementById("lastCity");
    
    if (visitDepartCityFrom != visitArriveCityTo) {
        lastCity.style.display = "none";
        document.getElementById("visitCity4").selectedIndex = 0;
    } else lastCity.style.display = "";
};

function visaForm_validate(){
    var purposeOfVisit = document.getElementById("purposeOfVisit");
    var visaType = document.getElementById("visaType");
    var cit = document.getElementById("passportCitzenship").options[document.getElementById("passportCitzenship").selectedIndex].text;
    var newRules = false;
    if ((cit == 'United Kingdom') || (cit == 'United States') || (cit == 'Georgia') || (cit == 'Canada')) newRules = true;
    var pageNum = 0;
    
    if((purposeOfVisit.options[purposeOfVisit.selectedIndex].text.toLowerCase()=='private')&&(visaType.options[visaType.selectedIndex].text.substring(0,1)=="M")){
        pageNum = document.getElementById("purposeOfVisit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Sorry, multiple entry option is not possible for 'Private' visas.");
        document.getElementById('purposeOfVisit').focus(); 
        return false;
    }
    
    //validity for first entry dates  
    if(document.getElementById("visitDayOfEntry").selectedIndex == 0){
	    pageNum = document.getElementById("visitDayOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the DAY for " + "your entry to Russia date.");
	    hlite(document.getElementById("visitDayOfEntry"));
  	    return false;
    }
    if(document.getElementById("visitMonthOfEntry").selectedIndex == 0) {
	    pageNum = document.getElementById("visitMonthOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the MONTH for " + "your entry to Russia date.");
	    hlite(document.getElementById("visitMonthOfEntry"));
	    return false;
    }
    if(document.getElementById("visitYearOfEntry").selectedIndex == 0) {
	    pageNum = document.getElementById("visitYearOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please enter the YEAR for " + "your entry to Russia date.");
	    hlite(document.getElementById("visitYearOfEntry"));
	    return false;
    }
    if(!isDate(document.getElementById("visitDayOfEntry").selectedIndex,document.getElementById("visitMonthOfEntry").selectedIndex-1,document.getElementById("visitYearOfEntry").options[document.getElementById("visitYearOfEntry").selectedIndex].text)) {
        pageNum = document.getElementById("visitDayOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The requested start date of the visa is invalid, please check it and try again.");
        hlite(document.getElementById("visitDayOfEntry"));
        return false;
    }
    if(document.getElementById("visitDayOfExit").selectedIndex == 0){
	    pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the DAY for " + "your exit from Russia date.");
	    hlite(document.getElementById("visitDayOfExit"));
  	    return false;
    }
    if(document.getElementById("visitMonthOfExit").selectedIndex == 0) {
	    pageNum = document.getElementById("visitMonthOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the MONTH for " + "your exit from Russia date.");
	    hlite(document.getElementById("visitMonthOfExit"));
	    return false;
    }
    if(document.getElementById("visitYearOfExit").selectedIndex == 0) {
	    pageNum = document.getElementById("visitYearOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please enter the YEAR for " + "your exit from Russia date.");
	    hlite(document.getElementById("visitYearOfExit"));
	    return false;
    }
    if(!isDate(document.getElementById("visitDayOfExit").selectedIndex,document.getElementById("visitMonthOfExit").selectedIndex-1,document.getElementById("visitYearOfExit").options[document.getElementById("visitYearOfExit").selectedIndex].text)) {
        pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The requested end date of your visa is invalid, please check it and try again.");
        hlite(document.getElementById("visitDayOfExit"));
        return false;
    }
  
    var doent = document.getElementById("visitDayOfEntry").selectedIndex + " " + document.getElementById("visitMonthOfEntry").options[document.getElementById("visitMonthOfEntry").selectedIndex].text + " " + document.getElementById("visitYearOfEntry").options[document.getElementById("visitYearOfEntry").selectedIndex].text;
    var doext = document.getElementById("visitDayOfExit").selectedIndex + " " + document.getElementById("visitMonthOfExit").options[document.getElementById("visitMonthOfExit").selectedIndex].text + " " + document.getElementById("visitYearOfExit").options[document.getElementById("visitYearOfExit").selectedIndex].text;

    var daysvalid = 0;

    var visaService_SelectHtmlElement = document.getElementById("visaType");
    var visaType = visaService_SelectHtmlElement.options[visaService_SelectHtmlElement.selectedIndex].text;
    switch (visaType) {
        case TypesVisaEnum.SE30: daysvalid = 30; break;
        case TypesVisaEnum.SE90: daysvalid = 90; break;
        case TypesVisaEnum.DE30: daysvalid = 30; break;
        case TypesVisaEnum.DE90: daysvalid = 90; break;
        case TypesVisaEnum.ME06: daysvalid = 182; break;
        case TypesVisaEnum.ME12: daysvalid = 365; break;
        case TypesVisaEnum.ME3Y: daysvalid = 1092; break;
        default: daysvalid = 365;
    }
    
    if(Math.ceil(dateDifference(new Date(doent), new Date(doext)))>daysvalid){
        pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum");
        if ((pageNum) && (IsNumeric(pageNum))) {
            nextPage(pageNum);
        }
        var daysText = daysvalid + " days";
        if (daysvalid == 1092)
            daysText = "3 years";
        alert("The visa you have selected is only valid for a maximum of " + daysText + " and your dates of entry and exit exceed this." + "\r\n\r\n" + "Please either correct your dates or consider a different visa type."); 
	    hlite(document.getElementById("visitDayOfExit"));
	    return false;
    }
    if((new Date())>=(new Date(doent))) {
        pageNum = document.getElementById("visitDayOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Your visa entry date is earlier or equal than today, please correct this.");
        hlite(document.getElementById("visitDayOfEntry"));
        return false;
    }
    if((new Date(doent))>=(new Date(doext))) {
        pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Your date of exit is earlier than your date of entry, please correct this and try again.");
        hlite(document.getElementById("visitDayOfExit"));
        return false;
    }  
    //inviting organisation
    if(newRules){        
        if(fieldBiggerThanJS(document.getElementById("accommodationAddress"),500,"Name, address and phone number of a person or hotel in Russia that you plan to stay with")) {
            pageNum = document.getElementById("accommodationAddress").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("accommodationAddress"));
            return false;
        }        
    }
    //medical coverage
    if(document.getElementById("visitMedicalCoverage").selectedIndex==0){
        pageNum = document.getElementById("visitMedicalCoverage").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Please select if you have medical coverage for your trip to Russia and if so, which type.");
        hlite(document.getElementById("visitMedicalCoverage"));
        return false;
    }
    
    if(newRules){
        //who pays for the trip
        var visitPays = document.getElementById("visitPays");
        if(visitPays.selectedIndex==0){
            pageNum = visitPays.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select who pays for your trip and stay in Russia.");
            hlite(visitPays);
            return false;
        }
        if(visitPays.options[visitPays.selectedIndex].text=="Other"){
            if(nothingOrBigJS(document.getElementById("visitPaysOther"),100,"Who pays for your trip")) {
                pageNum = document.getElementById("visitPaysOther").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
                hlite(document.getElementById("visitPaysOther"));
                return false;
            }
        }
    }
    //children under 16
    if((!document.getElementById("visitChildrenYes").checked)&&(!document.getElementById("visitChildrenNo").checked)){
        pageNum = document.getElementById("visitChildrenYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Please select your whether you are travelling with children under 16.");
        hlite(document.getElementById("visitChildrenYes"));
        return false;
    }
    
    //if(newRules){
        //passport before date
        //Fixed by Vladimir        
         if((!document.getElementById("pasportBackYes").checked)&&(!document.getElementById("pasportBackNo").checked)){
            pageNum = document.getElementById("pasportBackYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select your whether you have any specific date you want your passport back.");
            hlite(document.getElementById("pasportBackYes"));
            return false;
        }
        if(document.getElementById("pasportBackYes").checked) {
            //validity for first entry dates  
            if(document.getElementById("pasportBackDay").selectedIndex == 0){
	            pageNum = document.getElementById("pasportBackDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	            alert("Please select the DAY when you want to get your passport back.");
	            hlite(document.getElementById("pasportBackDay"));
  	            return false;
            }
            if(document.getElementById("pasportBackMonth").selectedIndex == 0) {
	            pageNum = document.getElementById("pasportBackMonth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	            alert("Please select the MONTH when you want to get your passport back.");
	            hlite(document.getElementById("pasportBackMonth"));
	            return false;
            }
            if(document.getElementById("pasportBackYear").selectedIndex == 0) {
	            pageNum = document.getElementById("pasportBackYear").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	            alert("Please select the YEAR when you want to get your passport back.");
	            hlite(document.getElementById("pasportBackYear"));
	            return false;
            }
            if(!isDate(document.getElementById("pasportBackDay").selectedIndex,document.getElementById("pasportBackMonth").selectedIndex-1,document.getElementById("pasportBackYear").options[document.getElementById("pasportBackYear").selectedIndex].text)) {
                pageNum = document.getElementById("pasportBackDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
                alert("The requested date you want your passport back is invalid, please check it and try again.");
                hlite(document.getElementById("pasportBackDay"));
                return false;
            }
            var paspback = document.getElementById("pasportBackDay").selectedIndex + " " + document.getElementById("pasportBackMonth").options[document.getElementById("pasportBackMonth").selectedIndex].text + " " + document.getElementById("pasportBackYear").options[document.getElementById("pasportBackYear").selectedIndex].text;

            //first of all, we check if entry1 is not in the past
            if((new Date())>=(new Date(paspback))) {
                pageNum = document.getElementById("pasportBackDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
                alert("The requested date you want your passport back is earlier or equal than today, please correct this.");
                hlite(document.getElementById("pasportBackDay"));
                return false;
            }
        }
    //}
    
    
    
    //personal details
    if(nothingOrBigJS(document.getElementById("firstName"),50,"First Name")) {
        pageNum = document.getElementById("firstName").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("firstName"));
        return false;
    }
    if(fieldBiggerThanJS(document.getElementById("middleName"),50,"Middle Name")) {
        pageNum = document.getElementById("middleName").getAttribute("pagenum");
        if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("middleName"));
        return false;
    }
    if(nothingOrBigJS(document.getElementById("surName"),50,"Surname")) {
        pageNum = document.getElementById("surName").getAttribute("pagenum");
        if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("surName"));
        return false;
    }
    if(fieldBiggerThanJS(document.getElementById("previousNames"),50,"Other Names")){
        pageNum = document.getElementById("previousNames").getAttribute("pagenum");
        if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("previousNames"));
        return false;
    }
    if((!document.getElementById("male").checked)&&(!document.getElementById("female").checked)){
        pageNum = document.getElementById("male").getAttribute("pagenum");
        if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Plesase select your Gender.");
        hlite(document.getElementById("male"));
        return false;
    }
    if(document.getElementById("dobDay").selectedIndex == 0){
        pageNum = document.getElementById("dobDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the DAY for " + "your date of birth.");
	    hlite(document.getElementById("dobDay"));
  	    return false;
    }
    if(document.getElementById("dobMonth").selectedIndex == 0) {
        pageNum = document.getElementById("dobMonth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the MONTH for " + "your date of birth.");
	    hlite(document.getElementById("dobMonth"));
	    return false;
    }
    if(document.getElementById("dobYear").selectedIndex == 0) {
        pageNum = document.getElementById("dobYear").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please enter the YEAR for " + "your date of birth.");
	    hlite(document.getElementById("dobYear"));
	    return false;
    }
    if(!isDate(document.getElementById("dobDay").selectedIndex,document.getElementById("dobMonth").selectedIndex-1,document.getElementById("dobYear").options[document.getElementById("dobYear").selectedIndex].text)) {
        pageNum = document.getElementById("dobDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The date of birth you have entered is invalid. Please correct it.");
        hlite(document.getElementById("dobDay"));
        return false;
    }
    var dob = document.getElementById("dobDay").selectedIndex + " " + document.getElementById("dobMonth").options[document.getElementById("dobMonth").selectedIndex].text + " " + document.getElementById("dobYear").options[document.getElementById("dobYear").selectedIndex].text;
    if((new Date())<=(new Date(dob))) {
        pageNum = document.getElementById("dobDay").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Your date of birth is later than or equal to todays date, please correct this and then click the continue button again.");
        hlite(document.getElementById("dobDay"));
        return false;
    }
    if(document.getElementById("countryOfBirth").selectedIndex==0){
        pageNum = document.getElementById("countryOfBirth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Please select your country of birth.");
        hlite(document.getElementById("countryOfBirth"));
  	    return false;
    }
    if(nothingOrBigJS(document.getElementById("cityOfBirth"),50,"City of Birth")) {
        pageNum = document.getElementById("cityOfBirth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("cityOfBirth"));
        return false;
    }
    if(nothingOrBigJS(document.getElementById("homeAddress1"),50,"Home Address")) {
        pageNum = document.getElementById("homeAddress1").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeAddress1"));
        return false; 
    }
    if(fieldBiggerThanJS(document.getElementById("homeAddress2"),50,"Home Address 2")){
        pageNum = document.getElementById("homeAddress2").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeAddress2"));
        return false;
    }
    if(nothingOrBigJS(document.getElementById("homeAddressCity"),50,"City or Town")) {
        pageNum = document.getElementById("homeAddressCity").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeAddressCity"));
        return false;
    }
    var t = document.getElementById("state").options[document.getElementById("state").selectedIndex].text;
    var country = document.getElementById("homeAddressCountry").options[document.getElementById("homeAddressCountry").selectedIndex].text;
    if((country == "United Kingdom")&&((t == "")||(t.substring(0,2)== "--"))){
  	    pageNum = document.getElementById("state").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
  	    alert("Please select a 'county' for your home address.");
  	    hlite(document.getElementById("state"));
  	    return false;
    }
    if(nothingOrBigJS(document.getElementById("homeAddressPostCode"),10,"Post Code")) {
        pageNum = document.getElementById("homeAddressPostCode").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeAddressPostCode"));
        return false;
    }
    if(nothingOrBigJS(document.getElementById("homeTelephone"),20,"Home Telephone")) {
        pageNum = document.getElementById("homeTelephone").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeTelephone"));
        return false;
    }
    if(digitsNotOKJS(document.getElementById("homeTelephone"),"Home Telephone Number")) {
        pageNum = document.getElementById("homeTelephone").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("homeTelephone"));
        return false;
    }
    if(nothingOrBigJS(document.getElementById("email"),50,"Email Address")){
        pageNum = document.getElementById("email").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("email"));
        return false;
    }
    if(fieldEmptyJS(document.getElementById("emailConfirm"),"Email Confirm")){
        pageNum = document.getElementById("emailConfirm").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("emailConfirm"));
        return false;
    }
    if(trim(document.getElementById("email").value) != trim(document.getElementById("emailConfirm").value)) {
        pageNum = document.getElementById("email").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Your email and email confirm addresses do not match, please correct this.");
	    hlite(document.getElementById("email"));
	    return false;
    }
    //passport details
    if(nothingOrBigJS(document.getElementById("passportNumber"),20,"Passport Number")) {
        pageNum = document.getElementById("passportNumber").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        hlite(document.getElementById("passportNumber"));
        return false;
    }
  
    if(document.getElementById("passportDayIssued").selectedIndex == 0){
	    pageNum = document.getElementById("passportDayIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the DAY for " + "your passport issue date.");
	    hlite(document.getElementById("passportDayIssued"));
  	    return false;
    }
    if(document.getElementById("passportMonthIssued").selectedIndex == 0) {
	    pageNum = document.getElementById("passportMonthIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the MONTH for " + "your passport issue date.");
	    hlite(document.getElementById("passportMonthIssued"));
	    return false;
    }
    if(document.getElementById("passportYearIssued").selectedIndex == 0) {
        pageNum = document.getElementById("passportYearIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please enter the YEAR for " + "your passport issue date.");
	    hlite(document.getElementById("passportYearIssued"));
	    return false;
    }
    if(!isDate(document.getElementById("passportDayIssued").selectedIndex,document.getElementById("passportMonthIssued").selectedIndex-1,document.getElementById("passportYearIssued").options[document.getElementById("passportYearIssued").selectedIndex].text)) {
        pageNum = document.getElementById("passportDayIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The passport issued date you have entered is invalid. Please correct it.");
        hlite(document.getElementById("passportDayIssued"));
        return false;
    }

    if(document.getElementById("passportDayExpires").selectedIndex == 0){
	    pageNum = document.getElementById("passportDayExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the DAY for " + "your passport expiry date.");
	    hlite(document.getElementById("passportDayExpires"));
  	    return false;
    }
    if(document.getElementById("passportMonthExpires").selectedIndex == 0) {
        pageNum = document.getElementById("passportMonthExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please select the MONTH for " + "your passport expiry date.");
	    hlite(document.getElementById("passportMonthExpires"));
	    return false;
    }
    if(document.getElementById("passportYearExpires").selectedIndex == 0) {
        pageNum = document.getElementById("passportYearExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Please enter the YEAR for " + "your passport expiry date.");
	    hlite(document.getElementById("passportYearExpires"));
	    return false;
    }
    if(!isDate(document.getElementById("passportDayExpires").selectedIndex,document.getElementById("passportMonthExpires").selectedIndex-1,document.getElementById("passportYearExpires").options[document.getElementById("passportYearExpires").selectedIndex].text)) {
        pageNum = document.getElementById("passportDayExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The passport expiry date you have entered is invalid. Please correct it.");
        hlite(document.getElementById("passportDayExpires"));
        return false;
    }
    var piss = document.getElementById("passportDayIssued").selectedIndex + " " + document.getElementById("passportMonthIssued").options[document.getElementById("passportMonthIssued").selectedIndex].text + " " + document.getElementById("passportYearIssued").options[document.getElementById("passportYearIssued").selectedIndex].text;
    var pexp = document.getElementById("passportDayExpires").selectedIndex + " " + document.getElementById("passportMonthExpires").options[document.getElementById("passportMonthExpires").selectedIndex].text + " " + document.getElementById("passportYearExpires").options[document.getElementById("passportYearExpires").selectedIndex].text;
    
    if(!isDate(document.getElementById("passportDayExpires").selectedIndex,document.getElementById("passportMonthExpires").selectedIndex-1,document.getElementById("passportYearExpires").options[document.getElementById("passportYearExpires").selectedIndex].text)) {
        pageNum = document.getElementById("passportDayExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The date of issue of your passport is not valid, please check it again");
        hlite(document.getElementById("passportDayExpires"));
        return false;
    }
    if(!isDate(document.getElementById("passportDayExpires").selectedIndex,document.getElementById("passportMonthExpires").selectedIndex-1,document.getElementById("passportYearExpires").options[document.getElementById("passportYearExpires").selectedIndex].text)) {
        pageNum = document.getElementById("passportDayExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("The date of expiry of your passport is not valid, please check it again");
        hlite(document.getElementById("passportDayExpires"));
        return false;
    }
    if((new Date(pexp))<=(new Date(piss))) {
	    pageNum = document.getElementById("passportDayIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	    alert("Your passport issued date is later than or equal to you passport expiry date, please correct this.");
	    hlite(document.getElementById("passportDayIssued"));
	    return false;
    }
    if((new Date())<=(new Date(piss))) {
  	    pageNum = document.getElementById("passportDayIssued").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
  	    alert("Your passport issued date is later than today, please correct this.");
  	    hlite(document.getElementById("passportDayIssued"));
  	    return false;
    }
    if((new Date())>=(new Date(pexp))) {
        pageNum = document.getElementById("passportDayExpires").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("You have set your passport expiry date to the date in the past, please correct this");
        hlite(document.getElementById("passportDayExpires"));
        return false;
    }
    if(newRules){
        var passortIssuedBy = document.getElementById('passortIssuedBy');
        if((passortIssuedBy)&&(nothingOrBigJS(passortIssuedBy,500,"Passport issued by"))) {
            pageNum = passortIssuedBy.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(passortIssuedBy);
            return false;
        }
    }
    //work details  
    var POWStatus = document.getElementById('POWStatus');
    POWStatus = POWStatus.options[POWStatus.selectedIndex].text;
    
    if(document.getElementById('POWStatus').selectedIndex<1) {
        pageNum = document.getElementById("POWStatus").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("You haven't selected your current employment status. Please correct this and try again.");
        hlite(document.getElementById("POWStatus"));
        return false;
    }
    
    if((POWStatus!='Unemployed')&&(POWStatus!='Retired')&&(POWStatus!='Infant')&&(POWStatus!='Homemaker')){
        if(nothingOrBigJS(document.getElementById("POWName"),100,"Place of Work or Study")){
            pageNum = document.getElementById("POWName").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("POWName"));
            return false;
        }
        if(nothingOrBigJS(document.getElementById("POWPosition"),100,"Place of Work or Study Position")){
            pageNum = document.getElementById("POWPosition").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("POWPosition"));
            return false;
        }
        if(nothingOrBigJS(document.getElementById("POWAddress"),4000,"Place of Work or Study Address")){
            pageNum = document.getElementById("POWAddress").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("POWAddress"));
            return false;
        }
        
        if(document.getElementById('POWAddressCountry').selectedIndex<1) {
            pageNum = document.getElementById("POWAddressCountry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("You haven't selected your Place of Work or Study Country. Please correct this and try again.");
            hlite(document.getElementById("POWAddressCountry"));
            return false;
        }
        if(nothingOrBigJS(document.getElementById("POWPostcode"),20,"Place of Work or Study Postcode")){
            pageNum = document.getElementById("POWPostcode").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("POWPostcode"));
            return false;
        }
        if(nothingOrBigJS(document.getElementById("POWTelephone"),20,"Place of Work or Study Telephone")){
            pageNum = document.getElementById("POWTelephone").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(document.getElementById("POWTelephone"));
            return false;
        }
    }
    
    
    //***** page 2 *****
    
    //marital status
    var maritalStatus = document.getElementById('maritalStatus');
    if((newRules)&&(maritalStatus)&&(maritalStatus.options[maritalStatus.selectedIndex].text.toLowerCase() == 'married')){
        var spouseName = document.getElementById('spouseName');
        var spouseDobDay = document.getElementById('spouseDobDay');
        var spouseDobMonth = document.getElementById('spouseDobMonth');
        var spouseDobYear = document.getElementById('spouseDobYear');
        var spousePlaceOfBirth = document.getElementById('spousePlaceOfBirth');
    
        if((spouseName)&&(nothingOrBigJS(spouseName,100,"Spouse full name"))){
            pageNum = spouseName.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(spouseName);
            return false;
        }
        if((spousePlaceOfBirth)&&(nothingOrBigJS(spousePlaceOfBirth,100,"Spouse place of birth"))) {
            pageNum = spousePlaceOfBirth.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            hlite(spousePlaceOfBirth);
            return false;
        }    
        if(spouseDobDay.selectedIndex == 0){
            pageNum = spouseDobDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	        alert("Please select the DAY for " + "your spouse date of birth.");
	        hlite(spouseDobDay);
  	        return false;
        }
        if(spouseDobMonth.selectedIndex == 0) {
            pageNum = spouseDobMonth.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	        alert("Please select the MONTH for " + "your spouse date of birth.");
	        hlite(spouseDobMonth);
	        return false;
        }
        if(spouseDobYear.selectedIndex == 0) {
            pageNum = spouseDobYear.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
	        alert("Please enter the YEAR for " + "your spouse date of birth.");
	        hlite(spouseDobYear);
	        return false;
        }
        if(!isDate(spouseDobDay.selectedIndex,spouseDobMonth.selectedIndex-1,spouseDobYear.options[spouseDobYear.selectedIndex].text)) {
            pageNum = spouseDobDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("The spouse date of birth you have entered is invalid. Please correct it.");
            hlite(spouseDobDay);
            return false;
        }
        var dobspouse = spouseDobDay.selectedIndex + " " + spouseDobMonth.options[spouseDobMonth.selectedIndex].text + " " + spouseDobYear.options[spouseDobYear.selectedIndex].text;
        if((new Date())<=(new Date(dobspouse))) {
            pageNum = spouseDobDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Your spouse date of birth is later than or equal to todays date, please correct this and then click the continue button again.");
            hlite(spouseDobDay);
            return false;
        }
        
    }

    if (newRules) {
        //parents details
        var fatherName = document.getElementById('fatherFirstName');
        var fatherSurname = document.getElementById('fatherSurName');
        var motherName = document.getElementById('motherFirstName');
        var motherSurname = document.getElementById('motherSurName');

        if ((fatherName) && (nothingOrBigJS(fatherName, 200, "Father's full name"))) {
            pageNum = fatherName.getAttribute("pagenum"); if ((pageNum) && (IsNumeric(pageNum))) { nextPage(pageNum); }
            hlite(fatherName);
            return false;
        }
        if ((fatherSurname) && (nothingOrBigJS(fatherSurname, 200, "Father's surname"))) {
            pageNum = fatherName.getAttribute("pagenum"); if ((pageNum) && (IsNumeric(pageNum))) { nextPage(pageNum); }
            hlite(fatherSurname);
            return false;
        }
        if ((motherName) && (nothingOrBigJS(motherName, 200, "Mother's full name"))) {
            pageNum = motherName.getAttribute("pagenum"); if ((pageNum) && (IsNumeric(pageNum))) { nextPage(pageNum); }
            hlite(motherName);
            return false;
        }
        if ((motherSurname) && (nothingOrBigJS(motherSurname, 200, "Mother's surname"))) {
            pageNum = motherSurname.getAttribute("pagenum"); if ((pageNum) && (IsNumeric(pageNum))) { nextPage(pageNum); }
            hlite(motherSurname);
            return false;
        }
    }
        
    //relatives living in russia
    if((!document.getElementById("visitRelativesYes").checked)&&(!document.getElementById("visitRelativesNo").checked)){
        pageNum = document.getElementById("visitRelativesYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
        alert("Please select whether you have blood relatives in Russia.");
        hlite(document.getElementById("visitRelativesYes"));
        return false;
    }
    
    if(newRules){        
        if(document.getElementById("visitRelativesYes").checked){
            var add_visitRelatives = document.getElementById('add_visitRelatives');
            var divs = add_visitRelatives.getElementsByTagName('div');
            
            for(var i=0,ralativeName,fullDate,ralativeRelation,ralativeDobD,ralativeDobM,ralativeDobY,relativeAddress,inputs,selects,textareas; i<divs.length; i++){
                inputs = divs[i].getElementsByTagName('input');
                selects = divs[i].getElementsByTagName('select');
                textareas = divs[i].getElementsByTagName('textarea');
            
                if(inputs[0]){ ralativeName = inputs[0]; 
                    if(nothingOrBigJS(ralativeName,100,"Relative Name")) {
                        pageNum = inputs[0].getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeName); return false;
                    } 
                }
                if(inputs[1]){ ralativeRelation = inputs[1]; 
                    if(nothingOrBigJS(ralativeRelation,100,"Relation to you")) {
                        pageNum = inputs[1].getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeRelation); return false;
                    } 
                }
                if((selects[0])&&(selects[1])&&(selects[2])){
                    ralativeDobD = selects[0];
                    ralativeDobM = selects[1];
                    ralativeDobY = selects[2];
                    
                    if(ralativeDobD.selectedIndex == 0){
                        pageNum = ralativeDobD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeDobD);
	                    alert("Please select your relative's DAY of birth.");
	                    hlite(ralativeDobD);
  	                    return false;
                    }
                    if(ralativeDobM.selectedIndex == 0) {
	                    pageNum = ralativeDobM.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeDobM);
	                    alert("Please select your relative's MONTH of birth.");
	                    hlite(ralativeDobM);
	                    return false;
                    }
                    if(ralativeDobY.selectedIndex == 0) {
	                    pageNum = ralativeDobY.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeDobY);
	                    alert("Please select your relative's YEAR of birth.");
	                    hlite(ralativeDobY);
	                    return false;
                    }
                    if(!isDate(ralativeDobD.selectedIndex,ralativeDobM.selectedIndex-1,ralativeDobY.options[ralativeDobY.selectedIndex].text)) {
                        pageNum = ralativeDobD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeDobD);
                        alert("Your relative's date of birth is invalid. Please correct it.");
                        hlite(ralativeDobD);
                        return false;
                    }
                    fullDate = ralativeDobD.selectedIndex + " " + ralativeDobM.options[ralativeDobM.selectedIndex].text + " " + ralativeDobY.options[ralativeDobY.selectedIndex].text;
                    if((new Date())<=(new Date(fullDate))) {
                        pageNum = ralativeDobD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(ralativeDobD);
                        alert("Your ralative's date of birth is later than or equal to todays date, please correct this and then click the continue button again.");
                        hlite(ralativeDobD);
                        return false;
                    }
                }
                if(textareas[0]){ 
                    relativeAddress = textareas[0]; 
                    if(nothingOrBigJS(relativeAddress,500,"Your ralative address")) {
                        pageNum = relativeAddress.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(relativeAddress);
                        return false; 
                    }
                } 
            }
        }
        //have you ever been arrested
        if((!document.getElementById("visitArrestedYes").checked)&&(!document.getElementById("visitArrestedNo").checked)){
            pageNum = document.getElementById("visitArrestedYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been arrested.");
            hlite(document.getElementById("visitArrestedYes"));
            return false;
        }
        if(document.getElementById('visitArrestedYes').checked){
            var add_visitArrestedDetails = document.getElementById('add_visitArrestedDetails');
            divs = add_visitArrestedDetails.getElementsByTagName('div');
            
            for(var i=0,arrestedCountry,fullDate,arrestedD,arrestedM,arrestedY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
            
                if(selects[0]){ 
                    arrestedCountry = selects[0]; 
                    arrestedD = selects[1]; 
                    arrestedM = selects[2]; 
                    arrestedY = selects[3]; 
                    
                    if((arrestedCountry.selectedIndex==0)||(arrestedD.selectedIndex==0)||(arrestedM.selectedIndex==0)||(arrestedY.selectedIndex==0)) {
                        pageNum = arrestedCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(arrestedCountry);
                        alert("You didn't fill in all the required information about when and where you have been arrested. Please correct this and try again.");
                        hlite(arrestedCountry);
                        return false;
                    }
                    if(!isDate(arrestedD.selectedIndex,arrestedM.selectedIndex-1,arrestedY.options[arrestedY.selectedIndex].text)) {
                        pageNum = arrestedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(arrestedD);
                        alert("Your arrest date is invalid. Please correct it.");
                        hlite(arrestedD);
                        return false;
                    }
                    fullDate = arrestedD.selectedIndex + " " + arrestedM.options[arrestedM.selectedIndex].text + " " + arrestedY.options[arrestedY.selectedIndex].text;
                    if((new Date())<=(new Date(fullDate))) {
                        pageNum = arrestedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(arrestedD);
                        alert("Your arrest date is later than or equal to todays date, please correct this and then click the continue button again.");
                        hlite(arrestedD);
                        return false;
                    }
                }
            }
        }
        //have you ever had a communicatable disease
        if((!document.getElementById("visitAfflictedYes").checked)&&(!document.getElementById("visitAfflictedNo").checked)){
            pageNum = document.getElementById("visitAfflictedYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been afflicted with a communicable disease of public health significance.");
            hlite(document.getElementById("visitAfflictedYes"));
            return false;
        }
        //Have you ever tried to obtain or assisted others to obtain a Russian visa or enter Russia by providing misleading or false information
        if((!document.getElementById("visaFalseInfoYes").checked)&&(!document.getElementById("visaFalseInfoNo").checked)){
            pageNum = document.getElementById("visaFalseInfoYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever tried to obtain or assisted others to obtain a Russian visa or enter Russia by providing misleading or false information.");
            hlite(document.getElementById("visaFalseInfoYes"));
            return false;
        }
        //have you ever been issued a russin visa
        if((!document.getElementById("visaBeforeYes").checked)&&(!document.getElementById("visaBeforeNo").checked)){
            pageNum = document.getElementById("visaBeforeYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been issued a Russian visa.");
            hlite(document.getElementById("visaBeforeYes"));
            return false;
        }
        if(document.getElementById('visaBeforeYes').checked){
            var add_visaBeforeDetails = document.getElementById('add_visaBeforeDetails');
            divs = add_visaBeforeDetails.getElementsByTagName('div');
            for(var i=0,issuedCountry,fullDate,issuedY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
                if(selects[0]){ 
                    issuedCountry = selects[0]; 
                    issuedY = selects[1]; 
                    if((issuedCountry.selectedIndex==0)||(issuedY.selectedIndex==0)) {
                        pageNum = issuedCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(issuedCountry);
                        alert("You didn't fill in all the required information about when and where you have been issued a Russian visa. Please correct this and try again.");
                        hlite(issuedCountry);
                        return false;
                    }
                }
            }
        }
        //have you ever been refused a visa
        if((!document.getElementById("visaRefusedYes").checked)&&(!document.getElementById("visaRefusedNo").checked)){
            pageNum = document.getElementById("visaRefusedYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been refused a Russian visa.");
            hlite(document.getElementById("visaRefusedYes"));
            return false;
        }
        if(document.getElementById('visaRefusedYes').checked){
            var add_visaRefused = document.getElementById('add_visaRefused');
            divs = add_visaRefused.getElementsByTagName('div');
            for(var i=0,refusedCountry,fullDate,refusedD,refusedM,refusedY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
                if(selects[0]){ 
                    refusedCountry = selects[0]; 
                    refusedD = selects[1]; 
                    refusedM = selects[2]; 
                    refusedY = selects[3]; 
                    if((refusedCountry.selectedIndex==0)||(refusedD.selectedIndex==0)||(refusedM.selectedIndex==0)||(refusedY.selectedIndex==0)) {
                        pageNum = refusedCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(refusedCountry);
                        alert("You didn't fill in all the required information about when and where you have been refused a Russian visa. Please correct this and try again.");
                        hlite(refusedCountry);
                        return false;
                    }
                    if(!isDate(refusedD.selectedIndex,refusedM.selectedIndex-1,refusedY.options[refusedY.selectedIndex].text)) {
                        pageNum = refusedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(refusedD);
                        alert("The date when a Russian visa was refused is invalid. Please correct it.");
                        hlite(refusedD);
                        return false;
                    }
                    fullDate = refusedD.selectedIndex + " " + refusedM.options[refusedM.selectedIndex].text + " " + refusedY.options[refusedY.selectedIndex].text;
                    if((new Date())<=(new Date(fullDate))) {
                        pageNum = refusedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(refusedD);
                        alert("The date when a Russian visa was refused is later than or equal to todays date, please correct this and then click the continue button again.");
                        hlite(refusedD);
                        return false;
                    }
                }
            }
        }
        //have your visa been cancelled
        if((!document.getElementById("visaCancelledYes").checked)&&(!document.getElementById("visaCancelledNo").checked)){
            pageNum = document.getElementById("visaCancelledYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether your visa has ever been cancelled.");
            hlite(document.getElementById("visaCancelledYes"));
            return false;
        }
        if(document.getElementById('visaCancelledYes').checked){
            var add_visaCancelled = document.getElementById('add_visaCancelled');
            divs = add_visaCancelled.getElementsByTagName('div');
            for(var i=0,cancelledCountry,fullDate,cancelledD,cancelledM,cancelledY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
                if(selects[0]){ 
                    cancelledCountry = selects[0]; 
                    cancelledD = selects[1]; 
                    cancelledM = selects[2]; 
                    cancelledY = selects[3]; 
                    if((cancelledCountry.selectedIndex==0)||(cancelledD.selectedIndex==0)||(cancelledM.selectedIndex==0)||(cancelledY.selectedIndex==0)) {
                        pageNum = cancelledCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(cancelledCountry);
                        alert("You didn't fill in all the required information about when and where your Russian visa was cancelled. Please correct this and try again.");
                        hlite(cancelledCountry);
                        return false;
                    }
                    if(!isDate(cancelledD.selectedIndex,cancelledM.selectedIndex-1,cancelledY.options[cancelledY.selectedIndex].text)) {
                        pageNum = cancelledD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(cancelledD);
                        alert("The date when your Russian visa was cancelled is invalid. Please correct it.");
                        hlite(cancelledD);
                        return false;
                    }
                    fullDate = cancelledD.selectedIndex + " " + cancelledM.options[cancelledM.selectedIndex].text + " " + cancelledY.options[cancelledY.selectedIndex].text;
                    if((new Date())<=(new Date(fullDate))) {
                        pageNum = cancelledD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(cancelledD);
                        alert("The date when your Russian visa was cancelled is later than or equal to todays date, please correct this and then click the continue button again.");
                        hlite(cancelledD);
                        return false;
                    }
                }
            }
        }
        //have you have been deported from Russia
        if((!document.getElementById("visitDeportedYes").checked)&&(!document.getElementById("visitDeportedNo").checked)){
            pageNum = document.getElementById("visitDeportedYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been deported a Russian visa.");
            hlite(document.getElementById("visitDeportedYes"));
            return false;
        }
        if(document.getElementById('visitDeportedYes').checked){
            var add_visitDeported = document.getElementById('add_visitDeported');
            divs = add_visitDeported.getElementsByTagName('div');
            for(var i=0,deportedCountry,fullDate,deportedD,deportedM,deportedY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
                if(selects[0]){ 
                    deportedCountry = selects[0]; 
                    deportedD = selects[1]; 
                    deportedM = selects[2]; 
                    deportedY = selects[3]; 
                    if((deportedCountry.selectedIndex==0)||(deportedD.selectedIndex==0)||(deportedM.selectedIndex==0)||(deportedY.selectedIndex==0)) {
                        pageNum = deportedCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(deportedCountry);
                        alert("You didn't fill in all the required information about when and where you have been deported. Please correct this and try again.");
                        hlite(deportedCountry);
                        return false;
                    }
                    if(!isDate(deportedD.selectedIndex,deportedM.selectedIndex-1,deportedY.options[deportedY.selectedIndex].text)) {
                        pageNum = deportedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(deportedD);
                        alert("The date when you have been deported from Russia is invalid. Please correct it.");
                        hlite(deportedD);
                        return false;
                    }
                    fullDate = deportedD.selectedIndex + " " + deportedM.options[deportedM.selectedIndex].text + " " + deportedY.options[deportedY.selectedIndex].text;
                    if((new Date())<=(new Date(fullDate))) {
                        pageNum = deportedD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(deportedD);
                        alert("The date when you have been deported from Russia is later than or equal to todays date, please correct this and then click the continue button again.");
                        hlite(deportedD);
                        return false;
                    }
                }
            }
        }
        //have you overstayed in russia
        if((!document.getElementById("visaOverstayedYes").checked)&&(!document.getElementById("visaOverstayedNo").checked)){
            pageNum = document.getElementById("visaOverstayedYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever overstayed your Russian visa or stayed unlawfully in Russia.");
            hlite(document.getElementById("visaOverstayedYes"));
            return false;
        } 
    }
    //date of last visit
    if(((document.getElementById("visitLastMonth").selectedIndex == 0)&&(document.getElementById("visitLastYear").selectedIndex != 0))||
       ((document.getElementById("visitLastMonth").selectedIndex != 0)&&(document.getElementById("visitLastYear").selectedIndex == 0))){
        if(document.getElementById("visitLastMonth")){
  	        if(document.getElementById("visitLastMonth").selectedIndex == 0){
  		        pageNum = document.getElementById("visitLastMonth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  		        alert("Please select the month of your last visit.");
  		        hlite(document.getElementById("visitLastMonth"));
  		        return false;
  	        }
	        if(document.getElementById("visitLastYear").selectedIndex == 0){
	            pageNum = document.getElementById("visitLastYear").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  	            alert("Please select the year of your last visit.");
  		        hlite(document.getElementById("visitLastYear"));
  		        return false;
  	        }
  	        var lastvisitDate = "01 " + document.getElementById("visitLastMonth").options[document.getElementById("visitLastMonth").selectedIndex].text + " " + document.getElementById("visitLastYear").options[document.getElementById("visitLastYear").selectedIndex].text;
  	        if((new Date())<=(new Date(lastvisitDate))) {
                pageNum = document.getElementById("visitLastMonth").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("The last visit date is later than today, please correct this.");
                hlite(document.getElementById("visitLastMonth"));
                return false;
            }
        }
    }
    
    //how many time you have been to Russia
        var visitTimesSelect = document.getElementById("visitTimesSelect");
        if(visitTimesSelect.options[visitTimesSelect.selectedIndex].text>0){
         //must check that last visit dates correct
         var visitFields = new Array ("visitLastDay","visitLastMonth","visitLastYear","visitLastDayExit","visitLastMonthExit","visitLastYearExit");
         var i=0;
         var posi=0;
         var isCorrect = true;
         for (i=0;i<6;i++)
          if (document.getElementById(visitFields[i]).selectedIndex == 0) { 
           isCorrect = false; 
           posi = i;
           break;
           }
         if(!isCorrect) {
          alert('Please select the date of your last visit entry and date of your last visit exit');
          hlite(document.getElementById(visitFields[i]));
          return false;
          }         
        }
    
    if(newRules){
        //special skills
        if((!document.getElementById("specialisedSkillsYes").checked)&&(!document.getElementById("specialisedSkillsNo").checked)){
            pageNum = document.getElementById("specialisedSkillsYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have any specialised skills, training or experience related to fire-arms and explosives or to nuclear matters, biological or chemical substance.");
            hlite(document.getElementById("specialisedSkillsYes"));
            return false;
        } 
        if((document.getElementById('specialisedSkillsYes').checked)&&(nothingOrBigJS(document.getElementById('specialisedSkillsList'),500,"Specialised skills, training or experience"))){
            pageNum = document.getElementById("specialisedSkillsYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  		    hlite(document.getElementById("specialisedSkillsList"));
  		    return false;
  		}    
  		//organisations you are a member of
        if((!document.getElementById("organisationsYes").checked)&&(!document.getElementById("organisationsNo").checked)){
            pageNum = document.getElementById("organisationsYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you are/were a member of any professional, civil or charity organisations.");
            hlite(document.getElementById("organisationsYes"));
            return false;
        } 
        if((document.getElementById('organisationsYes').checked)&&(nothingOrBigJS(document.getElementById('organisations'),500,"Professional, civil or charity organisations you are a member of"))){
            pageNum = document.getElementById("organisationsYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  		    hlite(document.getElementById("organisations"));
  		    return false;
  		}
  		//military service
  		if((!document.getElementById("militaryYes").checked)&&(!document.getElementById("militaryNo").checked)){
            pageNum = document.getElementById("militaryYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever performed military service.");
            hlite(document.getElementById("militaryYes"));
            return false;
        } 
  		if((document.getElementById('militaryYes').checked)&&(nothingOrBigJS(document.getElementById('militaryList1'),500,"Military service you performed"))){
            pageNum = document.getElementById("militaryYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  		    hlite(document.getElementById("militaryList1"));
  		    return false;
  		}
  		//Have you ever been involved in any armed conflicts, either as a member of the military service or a victim
  		if((!document.getElementById("conflictsYes").checked)&&(!document.getElementById("conflictsNo").checked)){
            pageNum = document.getElementById("conflictsYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have ever been involved in any armed conflicts, either as a member of the military service or a victim.");
            hlite(document.getElementById("conflictsYes"));
            return false;
        } 
        if((document.getElementById('conflictsYes').checked)&&(nothingOrBigJS(document.getElementById('conflictsDetails'),500,"Whether you have ever been involved in any armed conflicts"))){
            pageNum = document.getElementById("conflictsDetails").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  		    hlite(document.getElementById("conflictsDetails"));
  		    return false;
  		}
  		//Countries you have visited in the last 10 years
        var add_visitCountry = document.getElementById('add_visitCountry');
        divs = add_visitCountry.getElementsByTagName('div');
        var visitCountry1 = document.getElementById('visitCountry1');
        var visitCountry2 = document.getElementById('visitCountry2');
        var visitCountry3 = document.getElementById('visitCountry3');
        var visitCountry4 = document.getElementById('visitCountry4');
        var visitCountry5 = document.getElementById('visitCountry5');
        var visitCountry6 = document.getElementById('visitCountry6');
        var visitCountry7 = document.getElementById('visitCountry7');
        var visitCountry8 = document.getElementById('visitCountry8');
        
        if((visitCountry1.selectedIndex==0)&&(visitCountry2.selectedIndex==0)&&(visitCountry3.selectedIndex==0)
            &&(visitCountry4.selectedIndex==0)&&(visitCountry5.selectedIndex==0)&&(visitCountry6.selectedIndex==0)
            &&(visitCountry7.selectedIndex==0)&&(visitCountry8.selectedIndex==0)&&(visitedCountriesQ == false)){
            if(confirm("You haven't selected any countries you visited in the last 10 years. Click OK to continue or CANCEL to add this information.")) visitedCountriesQ = true;
            else {hlite(visitCountry1); return false;}
        } else {
            for(var i=0,visitedCountry,fullDate,visitedY,selects; i<divs.length; i++){
                selects = divs[i].getElementsByTagName('select');
                if((selects[0])&&(selects[1])){ 
                    visitedCountry = selects[0]; 
                    visitedY = selects[1]; 
                    if(((visitedCountry.selectedIndex!=0)&&(visitedY.selectedIndex==0))||((visitedCountry.selectedIndex==0)&&(visitedY.selectedIndex!=0))) {
                        pageNum = visitedCountry.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                        alert("You didn't fill in all the required information about when and what counties you have visited in the last 10 years.");
                        hlite(visitedCountry);
                        return false;
                    }
                }
            }        
        }
        //Countries which have ever issued you a passport
        var passportCountry1 = document.getElementById('passportCountry1');
        var passportCountry2 = document.getElementById('passportCountry2');
        var passportCountry3 = document.getElementById('passportCountry3');
        if((passportCountry1.selectedIndex==0)&&(passportCountry2.selectedIndex==0)&&(passportCountry3.selectedIndex==0)){
            pageNum = passportCountry1.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  	        alert("Please specify at least one country that issued you a passport.");
  		    hlite(passportCountry1);
  		    return false;
  		}
  		var curCit = document.getElementById('passportCitzenship');
  		curCit = curCit.options[curCit.selectedIndex].text;
  		if((curCit!=passportCountry1.options[passportCountry1.selectedIndex].text)&&(curCit!=passportCountry2.options[passportCountry2.selectedIndex].text)&&(curCit!=passportCountry3.options[passportCountry3.selectedIndex].text)){
  		    pageNum = passportCountry1.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  	        alert("You haven't specified your current citizenship in the list of countries which have ever issued you a passport. Please correct this and try again.");
  		    hlite(passportCountry1);
  		    return false;
  		}
  		//Did you formerly have USSR or Russian citizenship
  		if((!document.getElementById("passportRusYes").checked)&&(!document.getElementById("passportRusNo").checked)){
            pageNum = document.getElementById("passportRusYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you have you have formerly had USSR or Russian citizenship.");
            hlite(document.getElementById("passportRusYes"));
            return false;
        } 
        if(document.getElementById('passportRusYes').checked){
            var citzLostDay = document.getElementById('citzLostDay');
            var citzLostMonth = document.getElementById('citzLostMonth');
            var citzLostYear = document.getElementById('citzLostYear');
            var citzLostReason = document.getElementById('citzLostReason');
            
            if(citzLostDay.selectedIndex == 0){
                pageNum = citzLostDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("Please select when you lost Russian citizenship.");
                hlite(citzLostDay);
                return false;
            }
            if(citzLostMonth.selectedIndex == 0) {
                pageNum = citzLostMonth.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("Please select when you lost Russian citizenship.");
                hlite(citzLostMonth);
                return false;
            }
            if(citzLostYear.selectedIndex == 0) {
                pageNum = citzLostYear.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("Please select when you lost Russian citizenship.");
                hlite(citzLostYear);
                return false;
            }
            if(!isDate(citzLostDay.selectedIndex,citzLostMonth.selectedIndex-1,citzLostYear.options[citzLostYear.selectedIndex].text)) {
                pageNum = citzLostDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("The date you lost Russian citizenship is invalid. Please correct it.");
                hlite(citzLostDay);
                return false;
            }
            fullDate = citzLostDay.selectedIndex + " " + citzLostMonth.options[citzLostMonth.selectedIndex].text + " " + citzLostYear.options[citzLostYear.selectedIndex].text;
            if((new Date())<=(new Date(fullDate))) {
                pageNum = citzLostDay.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                alert("The date you lost Russian citizenship is later than or equal to todays date, please correct this and then click the continue button again.");
                hlite(citzLostDay);
                return false;
            }
            if(nothingOrBigJS(document.getElementById('citzLostReason'),500,"The reason you lost Russian citizenship")){
                pageNum = document.getElementById('citzLostReason').getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                hlite(document.getElementById('citzLostReason'));
                return false;
            }
        }
        //Has your passport ever been lost or stolen
        if((!document.getElementById("passportStolenYes").checked)&&(!document.getElementById("passportStolenNo").checked)){
            pageNum = document.getElementById("passportStolenYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether your passport has ever been lost or stolen.");
            hlite(document.getElementById("passportStolenYes"));
            return false;
        } 
        
        //last 2 places of work
        if((!document.getElementById("previousJobYes").checked)&&(!document.getElementById("previousJobNo").checked)){
            pageNum = document.getElementById("previousJobYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you worked before you current job.");
            hlite(document.getElementById("previousJobYes"));
            return false;
        } 
        if(document.getElementById('previousJobYes').checked){
            var add_company = document.getElementById('add_company');
            var divs = add_company.getElementsByTagName('div');
            //if(lastWorkQ==false){
                var companyName1 = document.getElementById('companyName1');
                var companyPosition1 = document.getElementById('companyPosition1');
                var companyStartDay1 = document.getElementById('companyStartDay1');
                var companyStartMonth1 = document.getElementById('companyStartMonth1');
                var companyStartYear1 = document.getElementById('companyStartYear1');
                var companyEndDay1 = document.getElementById('companyEndDay1');
                var companyEndMonth1 = document.getElementById('companyEndMonth1');
                var companyEndYear1 = document.getElementById('companyEndYear1');
                var companyManager1 = document.getElementById('companyManager1');
                var companyAddress1 = document.getElementById('companyAddress1');
                var companyTelephone1 = document.getElementById('companyTelephone1');
                
                
                /*if((trim(companyName1.value)=="")&&(trim(companyPosition1.value)=="")&&(trim(companyManager1.value)=="")&&(trim(companyAddress1.value)=="")&&(trim(companyTelephone1.value)=="")
                    &&(companyStartDay1.selectedIndex<1)&&(companyStartMonth1.selectedIndex<1)&&(companyStartYear1.selectedIndex<1)
                    &&(companyEndDay1.selectedIndex<1)&&(companyEndMonth1.selectedIndex<1)&&(companyEndYear1.selectedIndex<1)) {
                        if(confirm("You haven't filled in any infornation about your last place of work.\r\n\r\nIf you want to continue and leave it blank, click OK button. Otherwise click CANCEL to go back to this question.")){
                            lastWorkQ = true;
                        }    
                }*/
                //if(lastWorkQ==false){
                    for(var i=0,companyName,fullDate,companyPosition,companyStartD, companyStartM,companyStartY,companyEndD, companyEndM,companyEndY,companyManager,companyAddress,companyPhone,inputs,selects,textareas; i<divs.length; i++){
                        inputs = divs[i].getElementsByTagName('input');
                        selects = divs[i].getElementsByTagName('select');
                        textareas = divs[i].getElementsByTagName('textarea');
                    
                        if(inputs[0]){ companyName = inputs[0]; 
                            if(nothingOrBigJS(companyName,100,"Company Name")) {
                                pageNum = companyName.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(companyName); return false;
                            } 
                        }
                        if(inputs[1]){ companyPosition = inputs[1]; 
                            if(nothingOrBigJS(companyPosition,100,"Company Position")) {
                                pageNum = companyPosition.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(companyPosition); return false;
                            } 
                        }
                        if((selects[0])&&(selects[1])&&(selects[2])){
                            companyStartD = selects[0];
                            companyStartM = selects[1];
                            companyStartY = selects[2];
                            
                            if(companyStartD.selectedIndex == 0){
                                pageNum = companyStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your last job start DAY.");
	                            hlite(companyStartD);
  	                            return false;
                            }
                            if(companyStartM.selectedIndex == 0) {
	                            pageNum = companyStartM.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your last job start MONTH.");
	                            hlite(companyStartM);
	                            return false;
                            }
                            if(companyStartY.selectedIndex == 0) {
	                            pageNum = companyStartY.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
	                            alert("Please select your last job start YEAR.");
	                            hlite(companyStartY);
	                            return false;
                            }
                            if(!isDate(companyStartD.selectedIndex,companyStartM.selectedIndex-1,companyStartY.options[companyStartY.selectedIndex].text)) {
                                pageNum = companyStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                                alert("Your last job start date is invalid. Please correct it.");
                                hlite(companyStartD);
                                return false;
                            }
                            fullDate = companyStartD.selectedIndex + " " + companyStartM.options[companyStartM.selectedIndex].text + " " + companyStartY.options[companyStartY.selectedIndex].text;
                            if((new Date())<=(new Date(fullDate))) {
                                pageNum = companyStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
                                alert("Your last job start date is later than or equal to todays date, please correct this and then click the continue button again.");
                                hlite(companyStartD);
                                return false;
                            }
                            
                        }
                        //companyEndD, companyEndM,companyEndY
                        if((selects[3])&&(selects[4])&&(selects[5])){
                            companyEndD = selects[3];
                            companyEndM = selects[4];
                            companyEndY = selects[5];
                            
                            if(companyEndD.selectedIndex == 0){
                                pageNum = companyEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your last job end DAY.");
	                            hlite(companyEndD);
  	                            return false;
                            }
                            if(companyEndM.selectedIndex == 0) {
	                            pageNum = companyEndM.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your last job end MONTH.");
	                            hlite(companyEndM);
	                            return false;
                            }
                            if(companyEndY.selectedIndex == 0) {
	                            pageNum = companyEndY.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
	                            alert("Please select your last job end YEAR.");
	                            hlite(companyEndY);
	                            return false;
                            }
                            if(!isDate(companyEndD.selectedIndex,companyEndM.selectedIndex-1,companyEndY.options[companyEndY.selectedIndex].text)) {
                                pageNum = companyEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                                alert("Your last job end date is invalid. Please correct it.");
                                hlite(companyEndD);
                                return false;
                            }
                            fullDate = companyEndD.selectedIndex + " " + companyEndM.options[companyEndM.selectedIndex].text + " " + companyEndY.options[companyEndY.selectedIndex].text;
                            if((new Date())<=(new Date(fullDate))) {
                                pageNum = companyEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
                                alert("Your last job end date is later than or equal to todays date, please correct this and then click the continue button again.");
                                hlite(companyEndD);
                                return false;
                            }
                        }
                        if(inputs[2]){ companyManager = inputs[2]; 
                            if(nothingOrBigJS(companyManager,100,"Manager Name")) {
                                pageNum = companyManager.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(companyManager); return false;
                            } 
                        }
                        if(textareas[0]){ 
                            companyAddress = textareas[0]; 
                            if(nothingOrBigJS(companyAddress,500,"Your last place of work address")) {
                                pageNum = companyAddress.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(companyAddress);
                                return false; 
                            }
                        } 
                        if(inputs[3]){ companyPhone = inputs[3]; 
                            if(nothingOrBigJS(companyPhone,20,"Company Telephone Number")) {
                                pageNum = companyPhone.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(companyPhone); return false;
                            } 
                        }
                    }
                //}
            //}
        }
        //you attend any further education establishments
        if((!document.getElementById("moreEducationYes").checked)&&(!document.getElementById("moreEducationNo").checked)){
            pageNum = document.getElementById("moreEducationYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether you you attended any further education establishments.");
            hlite(document.getElementById("moreEducationYes"));
            return false;
        } 
        if(document.getElementById('moreEducationYes').checked){
            var add_education = document.getElementById('add_education');
            var divs = add_education.getElementsByTagName('div');
            //if(lastEducationQ==false){
                var educationName1 = document.getElementById('educationName1');
                var educationCourse1 = document.getElementById('educationCourse1');
                var educationStartDay1 = document.getElementById('educationStartDay1');
                var educationStartMonth1 = document.getElementById('educationStartMonth1');
                var educationStartYear1 = document.getElementById('educationStartYear1');
                var educationEndDay1 = document.getElementById('educationEndDay1');
                var educationEndMonth1 = document.getElementById('educationEndMonth1');
                var educationEndYear1 = document.getElementById('educationEndYear1');
                var educationAddress1 = document.getElementById('educationAddress1');
                var educationTelephone1 = document.getElementById('educationTelephone1');
                
                //if((trim(educationName1.value)=="")&&(trim(educationCourse1.value)=="")&&(trim(educationAddress1.value)=="")&&(trim(educationTelephone1.value)=="")&&(educationStartDay1.selectedIndex<1)&&(educationStartMonth1.selectedIndex<1)&&(educationStartYear1.selectedIndex<1)&&(educationEndDay1.selectedIndex<1)&&(educationEndMonth1.selectedIndex<1)&&(educationEndYear1.selectedIndex<1)) {
                //        if(confirm("You haven't filled in any infornation about your further education.\r\n\r\nIf you want to continue and leave it blank, click OK button. Otherwise click CANCEL to go back to this question.")){
                //            lastEducationQ = true;
                //        }    
                //}
                //if(lastEducationQ==false){
                    for(var i=0,educationName,fullDate,educationCourse,educationStartD,educationStartM,educationStartY,educationEndD,educationEndM,educationEndY,educationAddress,educationPhone,inputs,selects,textareas; i<divs.length; i++){
                        inputs = divs[i].getElementsByTagName('input');
                        selects = divs[i].getElementsByTagName('select');
                        textareas = divs[i].getElementsByTagName('textarea');
                    
                        if(inputs[0]){ educationName = inputs[0]; 
                            if(nothingOrBigJS(educationName,100,"Education Name")) {
                                pageNum = educationName.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(educationName); return false;
                            } 
                        }
                        if(inputs[1]){ educationCourse = inputs[1]; 
                            if(nothingOrBigJS(educationCourse,100,"Course of Study")) {
                                pageNum = educationCourse.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(educationCourse); return false;
                            } 
                        }
                        
                        if((selects[0])&&(selects[1])&&(selects[2])){
                            educationStartD = selects[0];
                            educationStartM = selects[1];
                            educationStartY = selects[2];
                            
                            if(educationStartD.selectedIndex == 0){
                                pageNum = educationStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your study start DAY.");
	                            hlite(educationStartD);
  	                            return false;
                            }
                            if(educationStartM.selectedIndex == 0) {
	                            pageNum = educationStartM.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your study start MONTH.");
	                            hlite(educationStartM);
	                            return false;
                            }
                            if(educationStartY.selectedIndex == 0) {
	                            pageNum = educationStartY.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
	                            alert("Please select your study start YEAR.");
	                            hlite(educationStartY);
	                            return false;
                            }
                            if(!isDate(educationStartD.selectedIndex,educationStartM.selectedIndex-1,educationStartY.options[educationStartY.selectedIndex].text)) {
                                pageNum = educationStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                                alert("Your study start date is invalid. Please correct it.");
                                hlite(educationStartD);
                                return false;
                            }
                            fullDate = educationStartD.selectedIndex + " " + educationStartM.options[educationStartM.selectedIndex].text + " " + educationStartY.options[educationStartY.selectedIndex].text;
                            if((new Date())<=(new Date(fullDate))) {
                                pageNum = educationStartD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
                                alert("Your study start date is later than or equal to todays date, please correct this and then click the continue button again.");
                                hlite(educationStartD);
                                return false;
                            }
                        }
                        //educationEndD,educationEndM,educationEndY
                        if((selects[3])&&(selects[4])&&(selects[5])){
                            educationEndD = selects[3];
                            educationEndM = selects[4];
                            educationEndY = selects[5];
                            
                            if(educationEndD.selectedIndex == 0){
                                pageNum = educationEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your study end DAY.");
	                            hlite(educationEndD);
  	                            return false;
                            }
                            if(educationEndM.selectedIndex == 0) {
	                            pageNum = educationEndM.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	                            alert("Please select your study end MONTH.");
	                            hlite(educationEndM);
	                            return false;
                            }
                            if(educationEndY.selectedIndex == 0) {
	                            pageNum = educationEndY.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
	                            alert("Please select your study end YEAR.");
	                            hlite(educationEndY);
	                            return false;
                            }
                            if(!isDate(educationEndD.selectedIndex,educationEndM.selectedIndex-1,educationEndY.options[educationEndY.selectedIndex].text)) {
                                pageNum = educationEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
                                alert("Your study end date is invalid. Please correct it.");
                                hlite(educationEndD);
                                return false;
                            }
                            fullDate = educationEndD.selectedIndex + " " + educationEndM.options[educationEndM.selectedIndex].text + " " + educationEndY.options[educationEndY.selectedIndex].text;
                            if((new Date())<=(new Date(fullDate))) {
                                pageNum = educationEndD.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);}
                                alert("Your study end date is later than or equal to todays date, please correct this and then click the continue button again.");
                                hlite(educationEndD);
                                return false;
                            }
                        }
                        //educationAddress,educationPhone
                        if(textareas[0]){ 
                            educationAddress = textareas[0]; 
                            if(nothingOrBigJS(educationAddress,500,"Your study address")) {
                                pageNum = educationAddress.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(educationAddress);
                                return false; 
                            }
                        } 
                        if(inputs[2]){ educationPhone = inputs[2]; 
                            if(nothingOrBigJS(educationPhone,100,"Study Telephone Number")) {
                                pageNum = educationPhone.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(educationPhone); return false;
                            } 
                        }
                    }
                //}
            //}
        }
        //completed personally by you
        if((!document.getElementById("personallyCompletedNo").checked)&&(!document.getElementById("personallyCompletedYes").checked)){
            pageNum = document.getElementById("personallyCompletedNo").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))) {nextPage(pageNum);}
            alert("Please select whether this application has been completed personally by you.");
            hlite(document.getElementById("personallyCompletedNo"));
            return false;
        } 
        if(document.getElementById('personallyCompletedNo').checked){
            var personCompletedSurname = document.getElementById('personCompletedSurname');
            var personCompletedName = document.getElementById('personCompletedName');
            var personCompletedRel = document.getElementById('personCompletedRel');
            var personCompletedAddr = document.getElementById('personCompletedAddr');
            
            if(nothingOrBigJS(personCompletedSurname,100,"Surname of the person who completed application")) {
                pageNum = personCompletedSurname.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(personCompletedSurname); return false;
            } 
            if(nothingOrBigJS(personCompletedName,100,"Name of the person who completed application")) {
                pageNum = personCompletedName.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(personCompletedName); return false;
            }
            if(nothingOrBigJS(personCompletedRel,100,"Relationship to applicant")) {
                pageNum = personCompletedRel.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(personCompletedRel); return false;
            }
            if(nothingOrBigJS(personCompletedAddr,500,"Applicant's address")) {
                pageNum = personCompletedAddr.getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} hlite(personCompletedAddr); return false;
            }
        }
    }
    //passport must be valid for at least 6 months after visa end date
     var pasExpDate = new Date(pexp);
     var exitDate = new Date(doext);
     exitDate.setDate(exitDate.getDate()+180);
     if((pasExpDate)<(exitDate)) {
  	    pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
  	    alert("Your passport expires within 6 months of your proposed date of exit from Russia." +"\r\n"+"Either change your dates of travel or obtain a new passport.");
  	    hlite(document.getElementById("visitDayOfExit"));
  	    return false;
     }
     
    var expected = window.expectedPDate;
    var expectedDate; try{expectedDate = new Date(expected);}catch(e){expectedDate = new Date();}
    
    if(Math.ceil(dateDifference(expectedDate, new Date(doent)))<0){
        if(!confirm("We expect this visa to be issued on " + formatDate(expectedDate) + ", which is after your requested visa start date of " + formatDate(new Date(doent)) +".\r\n\r\n"+ "Do you wish to continue?")){
	        pageNum = document.getElementById("visitDayOfExit").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	        hlite(document.getElementById("visitDayOfExit"));
	        return false;
	    }
    }
    
    var today = new Date();
    var plus47 = new Date();
    var minus45 = new Date(doent);
    plus47.setDate(plus47.getDate()+47);
    minus45.setDate(minus45.getDate()-45);
    
    if(new Date(doent)>plus47){
        if(!confirm("You can not apply for a business visa more than 45 days before your proposed \r\n date of entry into Russia. \r\n\r\n If you wish to proceed we will hold your application until the earliest date we can start processing it - " + formatDate(minus45) +".\r\n\r\n Do you wish to continue?")){
            pageNum = document.getElementById("visitDayOfEntry").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
	        hlite(document.getElementById("visitDayOfEntry"));
	        return false;
        }
    }
   
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate()+47);
    var exitDate = new Date(doent);
    
    if(document.getElementById("comments").value.indexOf("'")!=-1){
        pageNum = document.getElementById("comments").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
        alert("The 'Comments' field may not contain '" +"\r\n"+ "Please correct this and try again.")
	    document.getElementById("comments").focus();
	    return false;
    }
    
    if(!document.getElementById("tandcYes").checked){
        pageNum = document.getElementById("tandcYes").getAttribute("pagenum"); if((pageNum)&&(IsNumeric(pageNum))){nextPage(pageNum);} 
        alert("Please indicate that you have read the terms and conditions.");
        document.getElementById("tandcYes").focus();
        return false;
    }
    if(exitDate>todayDate) {
        document.getElementById("comments").value += "45 DAY RULE - EARLIEST PROCESSING START DATE: " + formatDate(exitDate.setDate(exitDate.getDate()-45)) + "\r\n\r\n";
    }
  
    document.getElementsByName("B1")[0].disabled = true;
    //document.getElementsByName("B2")[0].disabled = true;
    document.getElementsByName("B1")[0].value = "Please wait ...";
    document.getElementsByTagName("form")[0].submit();
    
    return false;
    
}
var adFields = {
'add_maritalStatus':{},
'add_spousename': { fieldReq: 'maritalStatus', fieldValue: 'Married,Divorced,Separated' },
'add_spousename': { fieldReq: 'maritalStatus', fieldValue: 'Married,Divorced,Separated' },
'add_spousedob': { fieldReq: 'maritalStatus', fieldValue: 'Married,Divorced,Separated' },
'add_spousepob': { fieldReq: 'maritalStatus', fieldValue: 'Married,Divorced,Separated' },

'add_emigrationDetails':{fieldReq:'countryOfBirth', fieldValue:'Armenia,Azerbaijan,Belarus,Georgia,Estonia,Kazakhstan,Latvia,Lithuania,Moldova,Russian Federation,Ukraine,Uzbekistan,Turkmenistan,Kyrgyzstan,Tajikistan,Kyrgyzstan,USSR,'},
'add_emigratedCountry':{fieldReq:'countryOfBirth', fieldValue:'Armenia,Azerbaijan,Belarus,Georgia,Estonia,Kazakhstan,Latvia,Lithuania,Moldova,Russian Federation,Ukraine,Uzbekistan,Turkmenistan,Kyrgyzstan,Tajikistan,Kyrgyzstan,USSR,'},

'add_parents':{},
'add_passortIssuedBy':{},
'add_passportRus':{},
'add_citzLost':{fieldReq:'passportRusYes', fieldValue:'true'},
'add_citzLostReason':{fieldReq:'passportRusYes', fieldValue:'true'},
'add_passportStolen':{},

'add_company':{},
'add_company_details':{fieldReq:'previousJobYes', fieldValue:'true'},

'add_visaBefore':{},
'add_visitPays':{},
'add_visitPaysOther':{fieldReq:'visitPays', fieldValue:'Other'},
'add_visaBeforeDetails':{fieldReq:'visaBeforeYes', fieldValue:'true'},
'add_visitCountry':{},
'personallyCompleted':{},
'add_passportCountry':{},
'add_visitArrested':{},
'add_conflicts':{},
'add_visaRefused':{},
'add_personCompletedDetails':{fieldReq:'personallyCompletedYes', fieldValue:'false'},
'add_visaCancelledDetails':{fieldReq:'visaCancelledYes', fieldValue:'true'},
'add_visaFalseInfo':{},
'add_visaOverstayed':{},
'add_visitDeportedDetails':{fieldReq:'visitDeportedYes', fieldValue:'true'},
'add_organisations':{},
'organisationsDetails':{fieldReq:'organisationsYes', fieldValue:'true'},
'add_specialisedSkills':{},
'add_specialisedSkillsList':{fieldReq:'specialisedSkillsYes', fieldValue:'true'},
'add_militaryList':{fieldReq:'militaryYes', fieldValue:'true'},
'add_conflictsDetails':{fieldReq:'conflictsYes', fieldValue:'true'},
'add_visitRelatives':{fieldReq:'visitRelativesYes', fieldValue:'true'},
'add_personCompleted':{},
'add_visitArrested':{},
'add_visaRefused':{},
'add_visaRefusedDatails':{fieldReq:'visaRefusedYes', fieldValue:'true'},
'add_visitDeported':{},
'add_visaCancelled':{},
'add_military':{},
'add_visitArrestedDetails':{fieldReq:'visitArrestedYes', fieldValue:'true'},
'add_visitAfflicted':{},
'add_education':{},

//Uncommented by Vladimir
//'add_pasportBack':{},

'pasportBackDetails':{fieldReq:'pasportBackYes', fieldValue:'true'},

'add_education_details':{fieldReq:'moreEducationYes', fieldValue:'true'},
'add_invitingOrg':{}
};


function powStatusChanged(obj)
{
    var POWDetails = document.getElementById('POWDetails');
    var obj= document.getElementById('POWStatus');
    
    var selVal = obj.options[obj.selectedIndex].text;
    var purposeOfVisit=document.getElementById('purposeOfVisit');
    purposeOfVisit=purposeOfVisit.options[purposeOfVisit.selectedIndex].text;    
    document.theVisaForm.B1.disabled=false;
    if((selVal=='Unemployed')||(selVal=='Retired')||(selVal=='Infant')||(selVal=='Homemaker')||(selVal==''))
    {
        POWDetails.style.display = 'none';
        document.getElementById('POWName').disabled=true;
        document.getElementById('POWPosition').disabled=true;
        document.getElementById('POWAddress').disabled=true;
        document.getElementById('POWAddressCountry').disabled=true;
        document.getElementById('POWPostcode').disabled=true;
        document.getElementById('POWTelephone').disabled=true;
    }
    else 
    {
        POWDetails.style.display = '';
        document.getElementById('POWName').disabled=false;
        document.getElementById('POWPosition').disabled=false;
        document.getElementById('POWAddress').disabled=false;
        document.getElementById('POWAddressCountry').disabled=false;
        document.getElementById('POWPostcode').disabled=false;
        document.getElementById('POWTelephone').disabled=false;
    }
    
    if (((selVal=="Retired")||(selVal=="In Education")||(selVal=="Homemaker")||(selVal=="Unemployed"))&&(purposeOfVisit=="Business"))
    {
        alert("You are applying for a business visa, but indicated that you are currently "+selVal.toLowerCase()+", and it is not possible to get a business visa in this case.  You may wish to consider a cultural visa instead.");
        //document.theVisaForm.B1.disabled=true;
        return;
    }    
    
}

function showNext(buttonObj, maxNumber, alertText)
{
    var parentNode = buttonObj.parentNode.nodeName == "DIV" ? buttonObj.parentNode: buttonObj.parentNode.parentNode.parentNode;
    var divToClone = parentNode.getElementsByTagName("div");
    var cloneNumber = divToClone.length;
    var cloneNum = 0;
    
    if((maxNumber>0)&&(maxNumber<=cloneNumber)){alert("You dont't need to list more than "+maxNumber+" "+alertText+"."); return false;}
    if(divToClone[0]){
        cloneNum = divToClone.length-1;
        var newNode = divToClone[cloneNum].cloneNode(true);
        parentNode.appendChild(newNode);
        var inputs = newNode.getElementsByTagName('input'); 
        
        divToClone = parentNode.getElementsByTagName("div");
        for(var i=0; i<divToClone.length; ++i){ 
            inputs = divToClone[i].getElementsByTagName('input'); 
            
            for(var j=0; j<inputs.length; j++){ 
                if(inputs[j].className=="rightTop"){
                    inputs[j].style.width = "78px";
                    if(i==divToClone.length-1) {
                        inputs[j].value = "Add next";
                        inputs[j].onclick = function(){showNext(this,0,'');};
                    } else {
                        inputs[j].value = "Delete";
                        inputs[j].onclick = function(){ var parent = this.parentNode.parentNode; if(confirm("Are you sure you want to remove this item?"))parent.parentNode.removeChild(parent); }
                    }
                }
            }
            if(i==divToClone.length-1) {
                inputs2 = divToClone[i].getElementsByTagName('textarea'); for(var k=0; k<inputs2.length; k++) inputs2[k].value = '';
                inputs = divToClone[i].getElementsByTagName('input'); for(var k=0; k<inputs.length; k++) if(inputs[k].className!="rightTop")inputs[k].value = '';
            }
        }
    }
}

function showAddFields()
{

     var passportCitzenship = document.getElementById('passportCitzenship');
     var citizenship = passportCitzenship.options[passportCitzenship.selectedIndex].text;
     
     //Vladimir's variables start
     var isPasportBackYesChecked = document.getElementById('pasportBackYes').checked;
     var details = document.getElementById('pasportBackDetails');
     
     
     //Vladimir's variables end
     var countryOfBirth = document.getElementById("countryOfBirth");
     countryOfBirth = countryOfBirth.options[countryOfBirth.selectedIndex].text;

     var VSD = document.getElementById('visaService');
     VSD = VSD.options[VSD.selectedIndex].value;

     var companyToVisit = document.getElementById('invitingOrg_field');
     var companyToVisitRefnum = document.getElementById('invitingOrg_field2');
     var companyToVisitConfirmation = document.getElementById('invitingOrg_field3');

     if (VSD == "I have my own Visa Support") {
         companyToVisit.style.display = '';
         companyToVisitRefnum.style.display = '';
         companyToVisitConfirmation.style.display = '';
     }
     else {
         companyToVisit.style.display = 'none';
         companyToVisitRefnum.style.display = 'none';
         companyToVisitConfirmation.style.display = 'none';
     }

     if ((citizenship != 'United Kingdom') && (citizenship != 'United States') && (citizenship != 'Georgia') && (citizenship != 'Canada'))
     {
         for (var i in adFields)
         {             
             if (document.getElementById(i)) 
             {
                 
                 if (((i == "add_emigratedCountry") || (i == "add_emigrationDetails")) && (countryOfBirth != citizenship) && (countryOfBirth != "")) {
                     var birth_country = null;
                     var arr_values = null;
                     var el = null;
                     if (i == "add_emigratedCountry") {
                         el = document.getElementById(adFields.add_emigratedCountry.fieldReq);                         
                         arr_values = adFields.add_emigratedCountry.fieldValue;
                     }
                     else if (i == "add_emigrationDetails") {
                         el = document.getElementById(adFields.add_emigrationDetails.fieldReq);
                         arr_values = adFields.add_emigrationDetails.fieldValue;
                     }
                     birth_country = el.options[el.selectedIndex].text;
                     var index = arr_values.indexOf(birth_country);
                     if (index != -1) {
                         document.getElementById(i).style.display = "";
                     }
                     else {
                         document.getElementById(i).style.display = "none";
                     }
                 }
                 else 
                 {
                     document.getElementById(i).style.display = "none";
                 } 
                 
                 
             }
        } 

        document.getElementById('WorkHolder').style.display = 'none';
        document.getElementById('commentHolder').className += " firstParagraph";        
        document.getElementById('add_visitLastMonth').style.display = '';
        document.getElementById('add_visitTimes').style.display = '';
        
        //Vladimir fix Start
      if (isPasportBackYesChecked)
      {
          details.style.display='';
      }
      else 
      {
          details.style.display='none';
      }
        //Vladimir fix end 

  }
  else
  {
        document.getElementById('add_visitTimes').style.display = 'none';
    
        document.getElementById('WorkHolder').style.display = '';
        
        if(document.getElementById('visaBeforeYes').checked)document.getElementById('add_visitLastMonth').style.display = '';else document.getElementById('add_visitLastMonth').style.display = 'none';
        
        document.getElementById('commentHolder').className = document.getElementById('commentHolder').className.replace(" firstParagraph",'');
    
        var obj,reqVals, fieldVal, field, displayVal, onclickEvent;
        for(var i in adFields){
            obj = adFields[i];
            if(typeof(obj.onclick)!='undefined')if(document.getElementById(i)) {document.getElementById(i).onclick = obj.onclick;}
            
            if((typeof(obj.fieldReq)!='undefined')&&(typeof(obj.fieldValue)!='undefined')){
                reqVals = obj.fieldValue.split(',');
                field = document.getElementById(obj.fieldReq);
                if(field){
                    if(field.nodeName == 'SELECT') fieldVal = field.options[field.selectedIndex].text;
                    else {if(field.value == "Yes"){ if(field.checked) fieldVal = "true"; else fieldVal = "false";  }else { fieldVal = field.value; }}
                    
                }
                if(reqVals.length>0){ if((in_array(fieldVal,reqVals)!=false)&&(fieldVal!="")) displayVal = 'block'; else displayVal = 'none';}
            }else displayVal = 'block';
            if(document.getElementById(i)) {document.getElementById(i).style.display = displayVal;}
            if(document.getElementById('personallyCompletedNo').checked) { document.getElementById('add_personCompletedDetails').style.display = ''; } else document.getElementById('add_personCompletedDetails').style.display = 'none'; 
        } 
    }
    
}
var TypesVisaEnum = {
    SE30: "Single Entry valid for 1 month",
    SE90: "Single Entry valid for 3 months",
    DE30: "Double Entry valid for 1 month",
    DE90: "Double Entry valid for 3 months",
    ME06: "Multiple Entry valid for 6 months",
    ME12: "Multiple Entry valid for 12 months",
    ME3Y: "Multiple Entry valid for 3 years"
};

var VSDServicesTypesEnum = {
    ownVSD: "I have my own Visa Support",
    _12WD: "12 Working Days",
    _8WD: "8 Working Days",
    _5WD: "5 Working Days",
    _3WD: "3 Working Days",
    _2WD: "2 Working Days",
    _1WD: "1 Working Days",
    _18WD: "18 Working Days",
    _14WD: "14 Working Days",
    _12WDT: "12 Working Days (TELEX)"
};

var ConsularServiceEnum = {
    _6Days: "6 days",
    NextDay: "Next Day"
};

var VSDServicesForVisaTypes =
[
    {
        VisaType: TypesVisaEnum.SE30,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._8WD,
                        VSDServicesTypesEnum._5WD,
                        VSDServicesTypesEnum._3WD,
                        VSDServicesTypesEnum._2WD,
                        VSDServicesTypesEnum._1WD,
                     ]
    },
    {
        VisaType: TypesVisaEnum.SE90,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._8WD,
                        VSDServicesTypesEnum._5WD,
                        VSDServicesTypesEnum._3WD,
                        VSDServicesTypesEnum._2WD,
                        VSDServicesTypesEnum._1WD,
                     ]
    },
    {
        VisaType: TypesVisaEnum.DE30,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._8WD,
                        VSDServicesTypesEnum._5WD,
                        VSDServicesTypesEnum._3WD,
                        VSDServicesTypesEnum._2WD,
                        VSDServicesTypesEnum._1WD,
                     ]
    },
    {
        VisaType: TypesVisaEnum.DE90,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._8WD,
                        VSDServicesTypesEnum._5WD,
                        VSDServicesTypesEnum._3WD,
                        VSDServicesTypesEnum._2WD,
                        VSDServicesTypesEnum._1WD,
                     ]
    },
    {
        VisaType: TypesVisaEnum.ME06,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._18WD,
                        VSDServicesTypesEnum._14WD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._12WDT                        
                     ]
    },
    {
        VisaType: TypesVisaEnum.ME12,
        VSDServices: [
                        VSDServicesTypesEnum.ownVSD,
                        VSDServicesTypesEnum._18WD,
                        VSDServicesTypesEnum._14WD,
                        VSDServicesTypesEnum._12WD,
                        VSDServicesTypesEnum._12WDT
                     ]
    }
];

var AvailableServicesForCountry =
[
    {
        Country: "Turkey",
        ForVisaTypes: [
                        {
                            VisaType: TypesVisaEnum.SE90,
                            ForConsularServices: [
                                                    {
                                                        Service: ConsularServiceEnum.NextDay,
                                                        AvailableVSDServices: [
                                                                                VSDServicesTypesEnum.ownVSD,
                                                                                VSDServicesTypesEnum._12WD,
                                                                                VSDServicesTypesEnum._8WD
                                                                              ]
                                                    }
                                                 ]
                        },
                        {
                            VisaType: TypesVisaEnum.DE90,
                            ForConsularServices: [
                                                    {
                                                        Service: ConsularServiceEnum.NextDay,
                                                        AvailableVSDServices: [
                                                                                VSDServicesTypesEnum.ownVSD,
                                                                                VSDServicesTypesEnum._12WD,
                                                                                VSDServicesTypesEnum._8WD
                                                                              ]
                                                    }
                                                 ]
                        },
                        {
                            VisaType: TypesVisaEnum.ME06,
                            ForConsularServices: [
                                                    {
                                                        Service: ConsularServiceEnum.NextDay,
                                                        AvailableVSDServices: [
                                                                                VSDServicesTypesEnum.ownVSD,
                                                                                VSDServicesTypesEnum._18WD,
                                                                                VSDServicesTypesEnum._14WD
                                                                              ]
                                                    }
                                                 ]
                        },
                        {
                            VisaType: TypesVisaEnum.ME12,
                            ForConsularServices: [
                                                    {
                                                        Service: ConsularServiceEnum.NextDay,
                                                        AvailableVSDServices: [
                                                                                VSDServicesTypesEnum.ownVSD,
                                                                                VSDServicesTypesEnum._18WD,
                                                                                VSDServicesTypesEnum._14WD
                                                                              ]
                                                    }
                                                 ]
                        }
                      ]       
                
    }
];

function GetVSDServicesFor(visaType) {
    for (var i = 0; i < VSDServicesForVisaTypes.length; i++) {
        if (VSDServicesForVisaTypes[i].VisaType == visaType)
            return VSDServicesForVisaTypes[i].VSDServices;
    }    
}


function GetAvailableVSDServices(forCountry, forVisaType, forConsularService) {
    var defaultAvailable = GetVSDServicesFor(forVisaType);
    for (var i = 0; i < AvailableServicesForCountry.length; i++) {
        if (AvailableServicesForCountry[i].Country == forCountry) {
            var forVisaTypes = AvailableServicesForCountry[i].ForVisaTypes;
            for (var j = 0; j < forVisaTypes.length; j++) {
                if (forVisaTypes[j].VisaType == forVisaType) {
                    var forConsularServices = forVisaTypes[j].ForConsularServices;
                    for (var k = 0; k < forConsularServices.length; k++) {
                        if (forConsularServices[k].Service == forConsularService) {
                            return forConsularServices[k].AvailableVSDServices;                                                        
                        }
                    }
                    return defaultAvailable;
                }
            }
            return defaultAvailable;
        }
    }
    return defaultAvailable;
}

function IsAvailableVSDService(VSDService, forCountry, forVisaType, forConsularService) {
    var isAvaileble = true;
    for (var i = 0; i < AvailableServicesForCountry.length; i++) {
        if (AvailableServicesForCountry[i].Country == forCountry) {
            var forVisaTypes = AvailableServicesForCountry[i].ForVisaTypes;
            for (var j = 0; j < forVisaTypes.length; j++) {
                if (forVisaTypes[j].VisaType == forVisaType) {
                    var forConsularServices = forVisaTypes[j].ForConsularServices;
                    for (var k = 0; k < forConsularServices.length; k++) {
                        if (forConsularServices[k].Service == forConsularService) {
                            var availableVSDServices = forConsularServices[k].AvailableVSDServices;                            
                            for (m = 0; m < availableVSDServices.length; m++) {
                                if (availableVSDServices[m] == VSDService)
                                    return true;
                            }                            
                            return false;
                        }
                    }
                    return false;
                }
            }
            return false;
        }
    }
    return false;
}

function IsSetupFor(country) {
    for (var i = 0; i < AvailableServicesForCountry.length; i++) {
        if (AvailableServicesForCountry[i].Country == country) {
            return true;
        }
    }
    return false;
}

function FillVSDServicesForCitizenship() {

    var passportCitzenshipHtmlElement = document.getElementById("passportCitzenship");
    var country = passportCitzenshipHtmlElement.options[passportCitzenshipHtmlElement.selectedIndex].text;

    var visaTypeHtmlElement = document.getElementById("visaType");
    var visaType = visaTypeHtmlElement.options[visaTypeHtmlElement.selectedIndex].text;
    var consularServiceHtmlElement = document.getElementById("consularService");
    var consularService = consularServiceHtmlElement.options[consularServiceHtmlElement.selectedIndex].text;

    var isSetup = IsSetupFor(country);
    if (!isSetup)
        return;

    var vsdServices = GetAvailableVSDServices(country, visaType, consularService);

    var VSDServiceHtmlElement = document.getElementById('visaService');
    FillSelectElement(VSDServiceHtmlElement, vsdServices);   
}

function IsAvailableVisaType_ForCitizenship(visaType) {
    var passportCitzenship_SelectHtmlElement = document.getElementById("passportCitzenship");
    var country = passportCitzenship_SelectHtmlElement.options[passportCitzenship_SelectHtmlElement.selectedIndex].text;

    var isSetup = IsSetupFor(country);
    if (!isSetup) {
        return true;
    }

    var forVisaTypes = [];
    for (var i = 0; i < AvailableServicesForCountry.length; i++) {
        if (AvailableServicesForCountry[i].Country == country) {
            forVisaTypes = AvailableServicesForCountry[i].ForVisaTypes;
            break;
        }
    }

    for (var i = 0; i < forVisaTypes.length; i++) {
        if (forVisaTypes[i] == visaType) {
            return true;
        }
    }

    return false;
}

function RemoveAllOptions(selectHtmlElement) {
    for (var i = 0; i < selectHtmlElement.childNodes.length; i++) {
        selectHtmlElement.removeChild(selectHtmlElement.childNodes[i]);
    }
}

function FillSelectElement(selectHtmlElement, values) {
    selectHtmlElement.options.length = values.length;
    for (var j = 0; j < values.length; j++) {
        selectHtmlElement.options[j].text = values[j];
    }            
}








