// this file contains all the JS for validating and manipulating search form contents

//## SEARCH FORM VALIDATION/MODIFICATION ##
//
//Simple Search:
//
//1. Change date to be select boxes as per Adv Search. Only accept "full" dates i.e 01/01/2004 and not //2004, 01// etc
//2. Change and/or labels to be
//	"all of these" - AND
//	"any of these" - OR
//
//Adv Search:
//
//1. Only accept "full" dates i.e 01/01/2004 and not //2004, 01// etc
//2. Change and/or labels to be
//	"all of these" - AND
//	"any of these" - OR
//3. "Contract Type" to work as per regions. i.e. you cannot select "all" with any of the other options. Choosing all of the other options will deselect them and automatically select "all".
//4. CPV codes. Make sure it can handle space and comma seperated data and that it will strip out any descriptions with have been inserted. Also validate submitted CPV codes against javascript array of valid codes. 1234 will be valid against 12345678. i.e. Allow stemming
//5. Source to work as per regions. i.e. you cannot select "all" with any of the other options. Choosing all of the other options will deselect them and automatically select "all".
//6. Nature of contract as per regions. i.e. you cannot select "all" with any of the other options. Choosing all of the other options will deselect them and automatically select "all".
//7. Records per page. Add "50" option.
//8. Sort by. Add country option.
//9. Source:
//	Ojec - country must be EEC (if any)
//	Contrax Weekly - Country must be UK or Ireland (if any)
//	MoD Defence - Country must be UK (if any). No OJEC ref
//	DCI - No Nature of Contract. No OJEC ref
//	US Federal - No CPV Codes. No OJEC ref. No Nature of Contract. Country (if any) must be USA.
//10. Change "omit keywords" to "words to exclude"

//####################################### START DATE VALIDATION CODE #########################################
/**
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : dd/mm/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
    return true
}
//############################# END DATE VALIDATION CODE######################################################

function regionHighlight(){
    // Deselects country if any associated regions are selected.
    var total=document.form1.country.options.length;
    var uk;
    var ukEngland;
    var ukScotland;
    var ukWales;
    var ukNIreland;
    for(i=0;i<total;i++){
        switch(document.form1.country.options[i].value){
            case "region_ukengland":
                if(document.form1.country.options[i].selected)
                    ukEngland=true;
                break;
            case "region_ukscotland":
                if(document.form1.country.options[i].selected)
                    ukScotland=true;
                break;
            case "region_ukwales":
                if(document.form1.country.options[i].selected)
                    ukWales=true;
                break;
            case "region_uknireland":
                if(document.form1.country.options[i].selected)
                    ukNIreland=true;
                break;
            case "gb":
                if(document.form1.country.options[i].selected)
                    uk=true;
                break;
        }
    }
    for(i=0;i<total;i++){
        if(ukEngland || ukWales || ukNIreland || ukScotland){
            if (document.form1.country.options[i].value=='gb'){
                document.form1.country.options[i].selected=false;
            }
        }
    }
}

function regionSelect(countrySelect){
    // Automatically selects countrys based on uk regions in country
    // select list i.e. select Northern Ireland and Republic then
    // "Ireland" will auto select with other two deselecting

    var total=countrySelect.options.length;
    var uk;
    var ukEngland;
    var ukScotland;
    var ukWales;
    var ukNIreland;

    for(i=0;i<total;i++){
        switch(countrySelect.options[i].value){
            case "region_ukengland":
                if(countrySelect.options[i].selected)
                    ukEngland=true;
                break;
            case "region_ukscotland":
                if(countrySelect.options[i].selected)
                    ukScotland=true;
                break;
            case "region_ukwales":
                if(countrySelect.options[i].selected)
                    ukWales=true;
                break;
            case "region_uknireland":
                if(countrySelect.options[i].selected)
                    ukNIreland=true;
                break;
            case "gb":
                if(countrySelect.options[i].selected)
                    uk=true;
                break;
        }
    }

    if((ukScotland && ukWales && ukEngland && ukNIreland) || uk){
        for(i=0;i<total;i++){
            switch(countrySelect.options[i].value){
                case "region_ukengland":
                case "region_ukscotland":
                case "region_ukwales":
                case "region_uknireland":
                    countrySelect.options[i].selected=false;
                    break;
                case "gb":
                    countrySelect.options[i].selected=true;
                    break;
            }
        }
    }
}



function validate(){
    // Function to validate form values etc
    // Grab any form params we are gonna use
    //var fromday=document.form1.fromday.value;
    //var frommon=document.form1.frommon.value;
    //var fromyear=document.form1.fromyear.value;
	
	// quick fix by iain Q - fromday, frommon etc. no longer exist	
	var fromday = "";
	var frommon = "";
	var fromyear = "";
	
	if (document.form1.aed) {
		var fromDateArray = document.form1.aed.value.split("/");
		fromday =  fromDateArray[0] || "";
		frommon = fromDateArray[1] || "";
		fromyear = fromDateArray[2] || "";
	}	
	
	
	// end iains fix

    // check from date simple AND adv
    if((fromday && (!frommon || !fromyear))||(frommon && (!fromday && !fromyear))||(fromyear && (!fromday && !frommon))){
       alert("You must enter a complete and valid date\ni.e. 01/01/2005");
       return false;
    }


    //If from date entered, check that it is a valid date
    if (fromday && frommon && fromyear) {
        var dateString = fromday + "\/" + frommon + "\/" + fromyear;
        if (isDate(dateString)==false){
		    return false;
	    }
    }
    // Pad single digit date elements
    if(fromday.length<2)
        fromday="0"+fromday;

    if(frommon.length<2)
        frommon="0"+frommon;

    var myFromDate = fromyear+frommon+fromday;

    // Compare to system time


    if(myFromDate>systemTime){
        alert("You may only search for contracts with Entry Dates up to and including the current date.");
        return false;
    }


	var today;
	var tomon;
	var toyear;
	
	if (document.form1.aed2) {
		var toDateArray = document.form1.aed2.value.split("/");
		today =  toDateArray[0] || "";
		tomon = toDateArray[1] || "";
		toyear = toDateArray[2] || "";
	}

   // if (document.form1.today){ // Must be adv search
    if (today) {
       // var today=document.form1.today.value;
        //var tomon=document.form1.tomon.value;
       // var toyear=document.form1.toyear.value;

        // check to date
        if((today && (!tomon || !toyear))||(tomon && (!today && !toyear))||(toyear && (!today && !tomon))){
            alert("You must enter a complete and valid date\ni.e. 01/01/2005");
            return false;
        }
        if(today.length<2)
            today="0"+today;

        if(tomon.length<2)
            tomon="0"+tomon;

        var myToDate = toyear+tomon+today;

        if(myToDate>systemTime){
            alert("You may only search for contracts with Entry Dates up to and including the current date.");
            return false;
        }

        //If complete to date entered, check that it is a valid date
        if (today && tomon && toyear) {
            var dateString = today + "\/" + tomon + "\/" + toyear;
            if (isDate(dateString)==false){
		        return false;
	        }
        }
        
        // Do some checks based upon source field
        var total_sources= 0; // document.form1.source.options.length; // this is a temporary fix
        for(i=0; i<total_sources; i++){
            switch(document.form1.source.options[i].value){
                case "Intercon":
                    if(document.form1.source.options[i].selected){
                        // If it's intercon then at countries may only be EU
                        var pattern=/be|de|fr|it|lu|nl|dk|ie|gb|gr|es|pt|at|fi|se|region_uk_england|region_uk_scotland|region_uk_wales|region_uk_northern_ireland/;
                        for(z=0; z<document.form1.list2.options.length; z++){
                            var theCountry=document.form1.list2.options[z].value;
                            var selected=document.form1.list2.options[z].selected;
                            var matches=theCountry.match(pattern);

                            if(!matches && selected){
                                alert("You cannot search for OJEC/TED/EC Tenders contracts\nin non-EEC countries");
                                return false;
                            }

                        }
                    }
                    break;
                case "Contrax":
                    // var archive=/archive.cgi/;
                    //  && !(document.referrer.match(archive))
                    if(document.form1.source.options[i].selected){
                    // If it's Contrax Weekly then countries may only be gb, ie, nie
                        var pattern=/gb|nie|ie|region_uk_england|region_uk_scotland|region_uk_wales|region_uk_northern_ireland/;
                        for(z=0; z<document.form1.list2.options.length; z++){
                            var theCountry=document.form1.list2.options[z].value;
                            var selected=document.form1.list2.options[z].selected;
                            var matches=theCountry.match(pattern);

                           // if(!matches && selected){
                              if(!matches){
                                alert("You cannot search for Contrax Weekly contracts\noutwith the UK or Ireland.");
                                return false;
                            }

                        }
                    }

                    break;
                case "Bulletin":
                    if(document.form1.source.options[i].selected){
                        // If it's MoD Defence Contracts Bulletin then countries may only be gb
                        // and no ojec_ref must be present.
                        var pattern=/gb|nie|region_uk_england|region_uk_scotland|region_uk_wales|region_uk_northern_ireland/;
                        for(z=0; z<document.form1.list2.options.length; z++){
                            var theCountry=document.form1.list2.options[z].value;
                            var selected=document.form1.list2.options[z].selected;
                            var matches=theCountry.match(pattern);

                            if(!matches && selected){
                                alert("You cannot search for MoD Defence Contracts Bulletin contracts\noutwith the UK.");
                                return false;
                            }

                        }
                        if(document.form1.refer.value){
                            alert("You cannot specify an OJEC Reference when looking for\nMoD Defence Contracts Bulletin contracts.");
                            return false;
                        }
                    }
                    break;
                case "International":
                    if(document.form1.source.options[i].selected){
                        if(document.form1.refer.value){
                            alert("You cannot specify an OJEC Reference when looking for\nDefence Contracts International contracts.");
                            return false;
                        }
                    }
                    break;
                case "FedCon":
                    if(document.form1.source.options[i].selected){
                        if(document.form1.refer.value){
                            alert("You cannot specify an OJEC Reference when looking for\nUS Federal contracts.");
                            return false;
                        }
                        if(document.form1.nc.selectedIndex!=-1){// Nothing selected
                            alert("You cannot specify a Nature of Contract when looking for\nUS Federal contracts.");
                            return false;
                        }
                        if(document.form1.cpv_nos.value){// Nothing selected
                            alert("You cannot specify CPV codes when looking for\nUS Federal contracts.");
                            return false;
                        }
                        var pattern=/us/;
                        for(z=0; z<document.form1.list2.options.length; z++){
                            var theCountry=document.form1.list2.options[z].value;
                            var selected=document.form1.list2.options[z].selected;
                            var matches=theCountry.match(pattern);

                            if(!matches && selected){
                                alert("You cannot search for US Federal contracts\noutwith the US.");
                                return false;
                            }

                        }
                    }
                    break;
            }
        }
    }

    // To deal with new style country picker
    if(document.form1.list2){
        var totCountries = document.form1.list2.options.length;
        var countries="";
        for (i=0; i < totCountries; i++){
   	        if (document.form1.list2.options[i].value != ""){
   	            countries += " "+document.form1.list2.options[i].value;
   	        }
        }
        document.form1.country.value = countries;
        // alert(document.form1.country.value);
        // end of new country picker
    }
    setTimeout( displaySplashLoader, 500 ); // delay in milliseconds

    return true;
}

function procSelect(procSelect){
    // if 'notices' && 'awards' are selected then deselect and highlight 'all'

    var total=procSelect.options.length;
    var all_procs;
    var notices;
    var awards;

    for(i=0;i<total;i++){
        switch(procSelect.options[i].value){
            case "All":
                if(procSelect.options[i].selected)
                    all_procs=true;
                break;
            case "notice":
                if(procSelect.options[i].selected)
                    notices=true;
                break;
            case "award":
                if(procSelect.options[i].selected)
                    awards=true;
                break;
        }
    }

    if((notices && awards) || all_procs){
        for(i=0;i<total;i++){
            switch(procSelect.options[i].value){
                case "award":
                case "notice":
                    procSelect.options[i].selected=false;
                    break;
                case "All":
                    procSelect.options[i].selected=true;
                    break;
            }
        }
    }
}
function sourceSelect(sourceSelect){
    // If "OJEC/TED/EC Tenders"+"Contrax Weekly"+"MoD Defence Contracts Bulletin"+"Defence Contracts International"+"US Federal"
    // are selected deselect and highlight all
    // This one is a bit different cos the values are different for archive.cgi pages - cue regex

    var total=sourceSelect.options.length;
    var all_sources;
    var intercon; // not in archive
    var contrax;
    var bulletin;
    var international;
    var fedcon; // not in archive
    var uk_ojec; // archive only
    var government; // archive only
    var notices;
    var awards;
    var pattern=/archive\.cgi/; // Pattern to "match" archive pages
    var url=location.href;
    var matches_archive=url.match(pattern);

    if(matches_archive!=null){ // must be from archive.cgi
        for(i=0;i<total;i++){
            switch(sourceSelect.options[i].value){
                case "All":
                    if(sourceSelect.options[i].selected)
                        all_sources=true;
                    break;
                case "Contrax":
                    if(sourceSelect.options[i].selected)
                        contrax=true;
                    break;
                case "Government":
                    if(sourceSelect.options[i].selected)
                        government=true;
                    break;
                case "Bulletin":
                    if(sourceSelect.options[i].selected)
                        bulletin=true;
                    break;
                case "uk_ojec":
                    if(sourceSelect.options[i].selected)
                        bulletin=true;
                    break;
            }
        }

        if((contrax && government && bulletin && uk_ojec) || all_sources){
            for(i=0;i<total;i++){
                switch(sourceSelect.options[i].value){
                    case "Contrax":
                    case "Government":
                    case "Bulletin":
                    case "UK_OJEC":
                        sourceSelect.options[i].selected=false;
                        break;
                    case "All":
                        sourceSelect.options[i].selected=true;
                        break;
                }
            }
        }
    }
    else{ // not archive
        for(i=0;i<total;i++){
            switch(sourceSelect.options[i].value){
                case "All":
                    if(sourceSelect.options[i].selected)
                        all_sources=true;
                    break;
                case "Contrax":
                    if(sourceSelect.options[i].selected)
                        contrax=true;
                    break;
                case "Intercon":
                    if(sourceSelect.options[i].selected)
                        intercon=true;
                    break;
                case "Bulletin":
                    if(sourceSelect.options[i].selected)
                        bulletin=true;
                    break;
                case "International":
                    if(sourceSelect.options[i].selected)
                        international=true;
                    break;
                case "FedCon":
                    if(sourceSelect.options[i].selected)
                        fedcon=true;
                    break;
            }
        }

        if((intercon && contrax && bulletin && international && fedcon) || all_sources){
            for(i=0;i<total;i++){
                switch(sourceSelect.options[i].value){
                    case "Contrax":
                    case "Intercon":
                    case "Bulletin":
                    case "FedCon":
                    case "International":
                        sourceSelect.options[i].selected=false;
                        break;
                    case "All":
                        sourceSelect.options[i].selected=true;
                        break;
                }
            }
        }
    }
}
function ncSelect(ncSelect){
    // Nature of Contract
    // If "All", "Works", "Supply" and "Service" are selected then deselect and select "All"

    var total=ncSelect.options.length;
    var all_ncs;
    var works;
    var supply;
    var service;
    var research

    for(i=0;i<total;i++){
        switch(ncSelect.options[i].value){
            case "All":
                if(ncSelect.options[i].selected)
                    all_ncs=true;
                break;
            case "Works":
                if(ncSelect.options[i].selected)
                    works=true;
                break;
            case "Supply":
                if(ncSelect.options[i].selected)
                    supply=true;
                break;
            case "Service":
                if(ncSelect.options[i].selected)
                    service=true;
                break;
            
            case "Research":
            if(ncSelect.options[i].selected)
                    research=true;
                break;
                
        }
    }

    if((works && supply && service && research) || all_ncs){
        for(i=0;i<total;i++){
            switch(ncSelect.options[i].value){
                case "Works":
                case "Supply":
                case "Service":
                case "Research":
                    ncSelect.options[i].selected=false;
                    break;
                case "All":
                    ncSelect.options[i].selected=true;
                    break;
            }
        }
    }
}

