
function isSupported(){
  if(document.all || document.getElementByID){
  	return true;
  }
  return false;
}


function browserCheck(){
	var ns4 = document.layers
	var ie4 = (document.all && !document.getElementByID)
	var ie5 = (document.all && document.getElementByID)
	var ie6 = (document.all && document.getElementByID)
	var ns6 = (!document.all && document.getElementByID)
	var ns7 = (!document.all && document.getElementByID)
	//if (navigator.appName=='Netscape'){supported=false} 
	if (ns4)
	{
	   return false;
	}
	return true
	
}
	
var Open = "";
var Closed = "";


if(document.images){
	Open = new Image()
	Closed = new Image()
	Open.src = "http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/images/buttons/arrow_close.gif"	
	Closed.src = "http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/images/buttons/arrow_open.gif"

}


function showhide(what,what2){
   if(browserCheck()){
        var currentdiv, currentimage;
        
        if(document.getElementById){
           currentdiv = document.getElementById(what);
           currentimage = document.getElementById(what2);
        }
        
        if(document.all){
           currentdiv = document.all(what);
           currentimage = document.all(what2);
        }
        
	if (currentdiv.style.display=='none'){
		currentdiv.style.display='';
		currentimage.src=Open.src
	}
	else{
		currentdiv.style.display='none'
		currentimage.src=Closed.src
	}
   }else{
        alert('This link does not work in your browser.\nPlease click on the \'Browse Categories\' link above.');
   }
}



function validateDateFields(fromDate, toDate){
 
   var status = "true"
   
   var frm = fromDate;
   var to = toDate
   
   
   //validate date fields
   // -- start
   
   if(to != ""){
	   toDate = checkDate(to, 1);
	   if(!toDate){
		document.form.to.focus();
		status = "false";
	   }
	   if(frm == ""){
	        alert("If you enter a 'To' date you must also enter a 'From' date.");
	        status = "false";
	   }
   }
   
   if(frm != ""){
	   fromDate = checkDate(frm, 2);
	    if(to == ""){
		alert("If you enter a 'From' date you must also enter a 'To' date.")
		status = "false";
	   }
   }
   
    if ( ( frm == "" ) && ( to == "" ) ) {
        fromDate = "";
        toDate = "";
        status = "true";
    }
    
   if(fromDate>toDate){
   	alert("The 'From' date cannot be greater than the 'To' date.");
   	status = "false";
   }
   
   //alert("fromDate = " + fromDate + " toDate = " + toDate);
   
   if(!fromDate || !toDate){ status="false";}
   if ( ( frm == "" ) && ( to == "" ) ){ status="true";}
   
   if(status == "false")
      return false;
   else
      return true;
   // -- end
}  

function checkDate(s, n){
	//var s=v.a.value;
	var dte

	if (dte = isDate(s, n)) {
		return dte
		//alert("The inputted date value is valid! - " + dte);
	} else {
	    if(err==false){
		alert("Please input date in the format DD/MM/YYYY or YYYY.");
	    	return false;
	    }
    	}
    	
	return false;
}

var err=false;
/**********************************************************************/
/*Function name :isDate(s,f) */
/*Usage of this function :To check s is a valid format */
/*Input parameter required:s=input string */
/* f=input string format */
/* =1,in mm/dd/yyyy format */
/* else in dd/mm/yyyy */
/*Return value :if is a valid date return 1 */
/* else return 0 */
/*Function required :isPositiveInteger() */
/**********************************************************************/
function isDate(s, n){
	var a1=s.split("/");
	var e=true;
	var date = "";

	if (a1.length!=3)
	{
	    var regexp = /^(\d{4})$/;
	    if(regexp.test(s)==true){
	        if(n==1) date = date + s + "1231";
	    	if(n==2) date = date + s + "0101";
	    	e=true
	    	return date
	    }else{
			e=false;
		}
	}else{
	    var regexp = /^(\d{2})\/(\d{2})\/(\d{4})$/;

		if(regexp.test(s)==true){
			if (a1.length==3)
				var na=a1;

			if (isPositiveInteger(na[0]) && isPositiveInteger(na[1]) && isPositiveInteger(na[2])){
				var d=na[0],m=na[1];y=na[2];

				if((!validateDay(d,m)) ||(!validateMonth(m))){
				  e=false;
				}else{
					date= y + m + d
					e=true
					return date;
				}
			}else{
				e=false;
			}
		}else{e=false;}
	}
	return e
}


/*************************************************************************/
/*Function name :isPositiveInteger(theString) */
/*Usage of this function :test for an +ve integer */
/*Input parameter required:thedata=string for test whether is +ve integer*/
/*Return value :if is +ve integer,return true */
/* else return false */
/*function require :isDigit */
/*************************************************************************/
function isPositiveInteger(theString)
{
var theData = new String(theString)

if (!isDigit(theData.charAt(0)))
if (!(theData.charAt(0)== '+'))
return false

for (var i = 1; i < theData.length; i++)
if (!isDigit(theData.charAt(i)))
return false
return true
}

/**********************************************************************/
/*Function name :isDigit(theDigit) */
/*Usage of this function :test for an digit */
/*Input parameter required:thedata=string for test whether is digit */
/*Return value :if is digit,return true */
/* else return false */
/**********************************************************************/
function isDigit(theDigit)
{
var digitArray = new Array('0','1','2','3','4','5','6','7','8','9'),j;

for (j = 0; j < digitArray.length; j++)
{if (theDigit == digitArray[j])
return true
}
return false

}

//check for leap years
function validateDay(day, month) {

      if(month==02){
      	   if (!inDayRangeForFeb(day)) {
	  		 alert("Enter a number between 1 and 28 (or 29 for leap years).");
	  		 err=true;
	  		 return false
		  }

      }else{
		  if (!inDayRange(day)) {
			 alert("Enter a number between 1 and 31.");
			 err=true;
			 return false
		  }
	  }
  return true
}

function inDayRange(inputStr) {
	var num = inputStr;
	if (num < 1 || num > 31) {
		return false
	}
	return true
}

function inDayRangeForFeb(inputStr) {
	var num = inputStr;
	if (num < 1 || num > 29) {
		return false
	}
	return true
}

function validateMonth(month) {
      if (!inMonthRange(month)) {
         alert("Enter a number between 1 (January) and 12 (December).");
         err=true;
         return false
      }
  return true
}

function inMonthRange(inputStr) {
	var num = inputStr;
	if (num < 1 || num > 12) {
		return false
	}
	return true
}

function querystring(key)  // returns the corresponding value for the key in querystring
{
  var ary = location.search.substring(1).split("&");

  for ( var i=0; i<ary.length; i++ )
  {
    if ( ary[i].split("=")[0].toUpperCase() == key.toUpperCase() )
       return ary[i].split("=")[1];
  }

  return("")
}

var altpressed="false";
var submitpressed="false";
var alertpressed=0;
var count=0;

if(!document.layers){
  document.onkeydown = function checkCR(evt) {
    if(document.all){
       if ((event.altLeft)||(event.altKey)) {
        //alert("alt key pressed");
        altpressed="true";
       }
    }
    
    var evt  = (evt) ? evt : ((event) ? event : null);

    var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
    
    if(altpressed=="false"){
	    if (evt.keyCode == '13')  {  
	        if (navigator.appName=='Netscape'){if(alertpressed==1){ count=1; alertpressed=0; return false;}}
	        
		if(document.searchboxform.Query.value != (("Type keywords") || (""))){
		    ValidateSearchBoxForm(); return false;
		}else{
		
		submitpressed="true";
		if(querystring("searchType")=="powersearch"){processPowerSearchForm(); return false;}
		if(querystring("searchType")=="quicksearch" || ""){ValidateSearchBoxForm(); return false;}
		if(
		
		
		querystring("searchType")==""){ValidateSearchBoxForm(); return false;}
		if(querystring("searchType")=="browserefine"){processBrowseRefineForm(); return false;}
		if(querystring("searchType")=="browse"){return false;}
		}
	    }
    }else{
      //capture submit key and reset altpressed
      if (evt.keyCode == '13')  {
        altpressed="false";
      }
    }
  }
}


if(!browserCheck()){
document.onkeyup = alertkey;

//FIRST, TELL THE BROWSERS TO REACT TO THE EVENT
if( document.captureEvents ) {
    //non IE
    if( Event.KEYUP ) {
        //NS 4, NS 6+, Mozilla 0.9+
        document.captureEvents( Event.KEYUP );
    }
}


//NOW CREATE THE EVENT HANDLER FUNCTION TO PROCESS THE EVENT
function alertkey(e) {
    if( !e ) {
        //if the browser did not pass the event information to the
        //function, we will have to obtain it from the event register
        if( window.event ) {
            //DOM
            e = window.event;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF REFERENCING THE EVENT
            return;
        }
    }
    if( typeof( e.which ) == 'number' ) {
        //NS 4, NS 6+, Mozilla 0.9+, Opera
        e = e.which;
    } else {
        if( typeof( e.keyCode ) == 'number'  ) {
            //IE, NS 6+, Mozilla 0.9+
            e = e.keyCode;
        } else {
            //TOTAL FAILURE, WE HAVE NO WAY OF OBTAINING THE KEY CODE
            return;
        }
    }
        if (e == '13') {
                if(alertpressed==1){alertpressed=0; return false;}
		if(document.searchboxform.Query.value != (("Type keywords") || (""))){
		    ValidateSearchBoxForm(); return false;
		}else{
		submitpressed="true";
		if(querystring("searchType")=="powersearch"){processPowerSearchForm(); return false;}
		if(querystring("searchType")=="quicksearch" || ""){ValidateSearchBoxForm(); return false;}
		if(querystring("searchType")==""){ValidateSearchBoxForm(); return false;}
		if(querystring("searchType")=="browserefine"){processBrowseRefineForm(); return false;}
		if(querystring("searchType")=="browse"){return false;}
    	}
    }
        
}

}


function ValidateSearchBoxForm(val){
	//alert("val = " + val);
	var formfield = document.searchboxform.Query.value;
	if(querystring("searchType")=="quicksearch" || querystring("searchType")=="" || querystring("searchType")=="powersearch" || querystring("searchType")=="browse" || querystring("searchType")=="browserefine" || querystring("searchType")=="browsable"){
		if( formfield == "Type keywords" || formfield == ""){
			alertpressed=1;
			alert("Please enter a value for the quick search query field.");

			if(val==1){
				return false;
			}else{
				return document.searchboxform.Query.focus();
			}
		}else{	 
			var qry = escape(document.searchboxform.Query.value);
			var dtes = document.searchboxform.daterange.options[document.searchboxform.daterange.selectedIndex].value

			//JRP - 20030310
			//check for asterisks
			if (!isValidWildcard(qry)){
				alert('At least two characters must be entered before a wildcard.');

				if(val==1){
					return false;
				}else{
					return document.searchboxform.Query.focus();
				}
			}else if (!containsNoInvalidChars(qry)){
				if(val==1){
					return false;
				}else{
					return document.searchboxform.Query.focus();
				}
			}else{
				if(document.layers) {
					if(dtes!=""){
						window.location="http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/documentsonline/search-progress.asp?searchType=quicksearch&pagenumber=1&queryType=1&catid=*&query="  + qry + "&" + dtes
					}else{
						location.href="http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/documentsonline/search-progress.asp?searchType=quicksearch&pagenumber=1&queryType=1&catid=*&query="  + qry
					}
				}else{
					if(dtes!=""){
						location.href="http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/documentsonline/search-progress.asp?searchType=quicksearch&pagenumber=1&queryType=1&catid=*&query="  + qry + "&" + dtes
					}else{
						location.href="http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/documentsonline/search-progress.asp?searchType=quicksearch&pagenumber=1&queryType=1&catid=*&query="  + qry
					}
				}
			}
		}
	}

	return false;
}

//---------------------------------------------------------

function PRO_openPopupWindow(theURL, winName, intWidth, intHeight, features, centralise) {
	features = features + ",width=" + intWidth + ",height=" + intHeight;

	if (centralise == "yes") {
		var intAvailWidth = 640, intAvailHeight = 480;
		var intMargin = 10;
		var intTop = intMargin, intLeft = intMargin;
		if (typeof(screen) == "object") {
			intAvailWidth = screen.availWidth;
			intAvailHeight = screen.availHeight;
		}
		intTop = Math.round(intAvailHeight/2 - intHeight/2);
		if (intTop < intMargin) intTop = intMargin;
		intLeft = Math.round(intAvailWidth/2 - intWidth/2);
		if (intLeft < intMargin) intLeft = intMargin;
		features = features + ",left=" + intLeft + ",top=" + intTop;
	}
	
  var newWin = window.open(theURL,winName,features);
  if (newWin.focus) newWin.focus();
  document.MM_returnValue = false;
}

//---------------------------------------------------------

function PRO_displayInMainWindow(theURL, closeThis) {
	var thisWindow = window;

	if (thisWindow.opener) {
		thisWindow.opener.location.href = theURL;
		thisWindow.opener.focus();
		if (closeThis) {
			thisWindow.close();
		}
	} else {
		thisWindow.location.href = theURL;
	}
	document.MM_returnValue = false;
}

//---------------------------------------------------------

function closeWindow() {
	self.close();
}

//---------------------------------------------------------

//JRP - 20030310
//function returns false if the string contains a wildcard without the requisite number of characters before it
function isValidWildcard(string){
	//number of chars required before a wildcard
	var charsBeforeWildcard = 2;
	
	//unescaped version of string
	var unescapedString = unescape(string);
	
	//splits the words of the search string into an array
	var arrWords = unescapedString.split(' ');
	
	//cache of a string in the array
	var currentString;
	
	//step through each string in the array
	for(var i=0; i<arrWords.length; i++){
		currentString = arrWords[i];
		
		//step through the current string looking for a wildcard
		for(var j=0; j<currentString.length; j++)
			if((currentString.charAt(j)=='*') && (j<charsBeforeWildcard))
				return false;
	}
	
	return true;
}

//JRP - 20030313
//function return false if any invalid characters are found
function containsNoInvalidChars(string){
	//string of invalid chars
	var invalidChars = '&|<>';
	
	//unescaped version of string
	var unescapedString = unescape(string);
	
	for(var i=0;i<unescapedString.length;i++){
		for(var j=0; j<invalidChars.length;j++){
			if(unescapedString.charAt(i)==invalidChars.charAt(j)){
				alert('Search text cannot contain character \'' + invalidChars.charAt(j) + '\'');
				
				return false;
			}
		}
	}
	
	return true;
}

//---------------------------------------------------------
/***********************************
   PERSONALISATION
***********************************/

        
        var xmlHttp; 
        var requestURL = 'http://collections.europarchive.org/tna/20090630141827/http://www.nationalarchives.gov.uk/mypage/personalisation/personalisation.aspx'; 
        var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
        var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
        var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
        //netscape, safari, mozilla behave the same??? 
        var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 
        
        function Personalisation()
        { 
            //Read the requestURL 
            var url = requestURL;
            
            //Create the xmlHttp object to use in the request 
            //stateChangeHandler will fire when the state has changed, i.e. data is received back 
            // This is non-blocking (asynchronous)
            xmlHttp = GetXmlHttpObject(stateChangeHandler); 
            
            //Send the xmlHttp get to the specified url
            xmlHttp_Get(xmlHttp, url); 
        }
        
        //stateChangeHandler will fire when the state has changed, i.e. data is received back 
        // This is non-blocking (asynchronous) 
        function stateChangeHandler() 
        { 
            //readyState of 4 or 'complete' represents that data has been returned 
            if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
            { 
                //Gather the results from the callback 
                var str = xmlHttp.responseText; 
                
                //write Personalisation header 
                document.getElementById('personal').innerHTML = str;
            } 
        } 

        // XMLHttp send GET request 
        function xmlHttp_Get(xmlhttp, url) 
        { 
            xmlhttp.open('GET', url, true); 
            xmlhttp.send(null); 
        } 

        function GetXmlHttpObject(handler)
        {   
            var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

            //Depending on the browser, try to create the xmlHttp object 
            if (is_ie)
            { 
               //The object to create depends on version of IE 
                //If it isn't ie5, then default to the Msxml2.XMLHTTP object 
                var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 
                 
                //Attempt to create the object 
                try{ 
                    objXmlHttp = new ActiveXObject(strObjName); 
                    objXmlHttp.onreadystatechange = handler; 
                } 
                catch(e){ 
                //Object creation errored 
                    alert('IE detected, but object could not be created. \nVerify that active scripting and activeX controls are enabled\nPlease notify gshanidze@nationalarchives.gov.uk'); 
                    return; 
                } 
            } 
            else if (is_opera){ 
                //Opera has some issues with xmlHttp object functionality 
                alert('Opera detected. The page may not behave as expected.\nPlease notify gshanidze@nationalarchives.gov.uk'); 
                return; 
            } 
            else{ 
                // Mozilla | Netscape | Safari 
                objXmlHttp = new XMLHttpRequest(); 
                objXmlHttp.onload = handler; 
                objXmlHttp.onerror = handler; 
            } 
            
            //Return the instantiated object 
            return objXmlHttp; 
        }



