addLoadEvent(prepareForms);

 function prepareForms() {
    if (!document.getElementById) return false;
     if (!document.getElementsByTagName) return false;
    var dF = document.forms[0];
    resetFields(dF);
    numSubmitTrue=0
    passed=false;
    dF.onsubmit = function() { // anon func
    validateForm(this);
    if(numSubmitTrue==2)return true; //return true causes 'onSubmit" to reload YourGridRef page
    if(numSubmitTrue==0) return false;//return false causes 'onsubmit' to validate the form and no more
     if (passed && numSubmitTrue ==1) {
         reLabel();
         return false; 
     } //end of if
   } // eof anon
} //eof prepareForms


function reLabel(){
newLabl=document.getElementById("submitReset");
newLabl.setAttribute("value","Click here to RESET before submitting another grid reference.");
newLabl.style.backgroundColor ="#99eeee";
newLabl.style.fontSize="11pt";
newLabl.style.fontWeight="bold";
} //eof reLabel

function resetFields(dF) { //Set element in focus to empty if value of element equals default value
  for (var i=0; i<dF.elements.length; i++) {
    var element = dF.elements[i];
    if (element.type == "submit") continue;
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == this.defaultValue) {
      this.value = "";
     }
    }
    // put back defaullt values if element value is empty when out of focus
    element.onblur = function(){ 
     if (this.value == "") {
      this.value = this.defaultValue;
     }
   }
  }
} //eof resetFields


function validateForm(cetForm) {
   if(numSubmitTrue==1){numSubmitTrue=2;
   return;
   }
   passed=false;
   eVal = cetForm.easting.value; 
   eLen = eVal.length
   nVal = cetForm.northing.value;
   nLen = nVal.length;
   eFocus =true; nFocus=true;
  var selIndex = cetForm.letterCode.selectedIndex;
   var lVal = cetForm.letterCode.options[selIndex].text; // use 'text' here, not 'value' in order to accomodate I.E. 
   var min =2;
   var max =3;  
   if(!isNumeric(eVal)){ // if 1
       missive("Easting must contain digits, no spaces.");
       cetForm.easting.focus();
  } // end of if 1
  else
   if(!isLengthBetween(eLen, min,max)){ // if 2
       missive("Easting must have at least 2 digits.");
       cetForm.easting.focus();
   } // end of if 2
   else
    if(!isNumeric(nVal)){ // if 3
  missive("Northing must contain digits only, Try double clicking first.");
  cetForm.northing.focus();
   } // end of if 3
   else
   if(!isLengthBetween(nLen, min,max)){ // if 4
       missive("Northing must have at least 2 digits.");
       cetForm.northing.focus();
   } // end of if 4
   else
   if(!isSame(eLen,nLen)){ // if 5
       missive("Easting and northing must have same no of digits.");
       cetForm.northing.focus();
   } // end of if 5 
   else
  { 
  kk = Math.pow(10,(eLen-2));
  var eBasic = parseInt(eVal,10);
  var nBasic = parseInt(nVal,10);
  var eCorrected = eval(eBasic/kk);
  var nCorrected = eval(nBasic/kk);
  
  if(!inRadar(lVal,eCorrected,nCorrected)){ // if 6
      if(eFocus){ // if 7
          cetForm.easting.focus();
      } //end of if 7
      if(nFocus){ //if 8
           cetForm.northing.focus();
      } //end of if 8
  } // end of if 6
 } //end of else
 if(!eFocus && !nFocus){ //if 9
     passed=true;
     numSubmitTrue += 1;
     missive("Grid reference: "+lVal+eVal+nVal);
     revealOSMapBtn(); //Netscape needs this action to be repeated otherwise area map is not fully revealed
     revealOSMapBtn(); //Repetition - see line above
     gridRefPlot(lVal,eCorrected,nCorrected); 
 } //end of if 9
 return passed;
} // eof validateForm
  
  
  function revealOSMapBtn(){
      osMapBtnElem = document.getElementById("osMapBtn");
       osMapBtnElem.style.visibility = "visible";
   }  //eof revealOSMapBtn
   
   
  function missive(txtMessage){
     removeMessage();
     writeMessage(txtMessage);
     if (!passed)blinkWindow();
  } // eof missive  
  
  
   function writeMessage(txtMessage){
   var para =document.createElement('p');
   para.appendChild(document.createTextNode(txtMessage));
   para.setAttribute("id","note");
   errdiv = document.getElementById("errordiv");
   errdiv.appendChild(para);
   } //eof writeMessage
   
   
   function removeMessage(){
   if(!document.getElementById("note")) return false;// only exists after first writeMessage
   var errMessage = document.getElementById("note");
   var container = errMessage.parentNode;
   container.removeChild(errMessage);
   } //eof removeMessage
   
   
   
  function inRadar(lVal,eCor,nCor){
  eFocus =false; nFocus=false;
  var msg = new Array;
  msg[0] = "Easting must be at least ";
  msg[1] = "Northing must be at least ";
  msg[2] = "Easting must not exceed ";
  msg[3] =  "Northing must not exceed ";
  msg[4] = "Location not on maps. ";
  
  if(lVal=="SC"){ //if 1
     if(eCor < 84){ //if 2
         missive(msg[4]+msg[0]+84*kk);
         eFocus=true;
         return false;
     }// end of if2
     if(nCor< 68){ //if 3
         missive(msg[4]+msg[1] +68*kk);
         nFocus=true;
         return false;
     } //emnd of if 3
  } // end of if 1
    
  if(lVal=="SD"){ //if 4
      if(nCor< 68){ // if 5
          missive(msg[4]+msg[1]+68*kk);
          nFocus=true;
          return false;
      } // end of if 5
  } // end of if 4  
    
   if(lVal=="SE"){ // if 6
        if(eCor > 10){ // if 7
             missive(msg[4]+msg[2]+10*kk);
             eFocus=true;
             return false;
         } // end of if 7
         if(nCor< 68){ //if 8
            missive(msg[4]+msg[1]+68*kk);
            nFocus=true;
            return false;
        } // end of if 8
   } // end of if 6
   
   if(lVal=="NX"){ //if 9
        if(eCor < 84){ // if 10
            missive(msg[4]+msg[0]+84*kk);
           eFocus=true;
           return false;
        } // end of if10
        if(nCor>77){ // if 11
          missive(msg[4]+msg[3]+77*kk);
          nFocus=true;
          return false;
       } // end of if 11
  } // end of if 9
   
  if(lVal=="NY"){ // if 12
       if(nCor>77){ // if 13
          missive(msg[4]+msg[3]+77*kk);
          nFocus=true;
         return false;
      } // end of if 13
  } // end of if 12
   
  if(lVal=="NZ"){ // if 14
      if(eCor >10){ // end of if 15
         missive(msg[4]+msg[2]+10*kk);
         eFocus=true;
         return false;
      } // end of if 15
      if(nCor> 77){ // if 16
         missive(msg[4]+msg[3]+77*kk);
         nFocus=true
         return false;
     } // end of if 16
  } // end of if 14
  return true;
} //eof inRadar
   
   


function isNumeric(str) { //returns true if string only contains characters 0 - 9
var re = /[\D]/g;
if (re.test(str)) return false;
return true;
} //eof isNumeric


function isLengthBetween(len,min,max){ //returns true if string length is between 'min' and 'max'
return (len >= min)&&(len <= max);
} //eof islengthBetween


function isSame(len1,len2){ //returns true if lengths are equal.
return (len1 == len2);
} //eof isSame
 
 
 function gridRefPlot(mapCodeStr,eCorrected,nCorrected){
 
  //Check for faulty map codes and if OK adjust values of eastings and northings accordingly. There should be no faults as options limit choice.
      if ((mapCodeStr != "NX" ) && (mapCodeStr != "NY" ) && (mapCodeStr != "NZ" ) && (mapCodeStr != "SC" ) && (mapCodeStr != "SD" ) && (mapCodeStr != "SE" )){ 
      return false; //poorMapRef;
      }else{
      if(mapCodeStr == "NX" ) {nCorrected = nCorrected + 100;}
      if(mapCodeStr == "NY" ) {nCorrected = nCorrected + 100; eCorrected = eCorrected + 100;}
      if(mapCodeStr == "NZ" ) {nCorrected = nCorrected + 100; eCorrected = eCorrected + 200;}
      if(mapCodeStr == "SD" ) {eCorrected = eCorrected + 100;}
      if(mapCodeStr == "SE" ) {eCorrected = eCorrected + 200;}
    } //end of else
      
    //now decide which map to use
      hRefer ="images/walkareamap21d.jpg";
      mapNo = 21;
      if((nCorrected > 130) && (eCorrected > 150)){ hRefer="images/walkareamap12a.jpg"; mapNo = 12;}
      if((nCorrected > 130) && (eCorrected <= 150)){ hRefer="images/walkareamap11a.jpg"; mapNo = 11;}
      if((nCorrected <=130) && (eCorrected > 150)){ hRefer="images/walkareamap22e.jpg"; mapNo = 22;}
      
      //display appropiate map
      newPic(hRefer);
      
      //correction for screen n and map n being plotted in opposite directions by adding 200 to ensure +ve value
      nCorrected = 200 - nCorrected;
      //scale correction factor
       // set scale correction factors
      // nFactor is set at 7.99 initially and is changed if necessary in table below. eFactor (easterly) varies.See below.
     
     var nFactor=7.99;
      
      
     //adjust offsets according to map selected.  Values for Firefox/SeaMonkey, Opera, IE, Safari/Chrome are set if present. Anything else uses the Firefox setting.
       browserFound=false;
      if(window.globalStorage){ // Corrections for Firefox and SeaMonkey
       browserFound=true;
      if(mapNo == 11 ){var eOffset = -568; var nOffset = -185;var eFactor = 8.54;}//-568, -185, 8.54 *
      if(mapNo == 12 ){var eOffset = -988; var nOffset = -186;var eFactor = 8.50;}//-988, -186, 8.50 *
      if(mapNo == 21 ){var eOffset = -562; var nOffset = -551;var eFactor = 8.50;nFactor=7.93;}//-562, -555. 8.40 *
      if(mapNo == 22 ){var eOffset = -955; var nOffset = -573;var eFactor = 8.33;nFactor=8.14;}//-956, -556, 8.33 *
     }
      else if(document.addEventListener && window.opera && !browserFound){ // Corrections for Opera
      browserFound=true;
      if(mapNo == 11 ){var eOffset = -568; var nOffset = -183;var eFactor = 8.54;}//-568, -183 , 8.54*
      if(mapNo == 12 ){var eOffset = -989; var nOffset = -185;var eFactor = 8.50;}//-989, -185, 8.50 *
      if(mapNo == 21 ){var eOffset = -561; var nOffset = -552;var eFactor = 8.50;nFactor=7.95;}//-561, -552, 8.40 *
      if(mapNo == 22 ){var eOffset = -954; var nOffset = -572;var eFactor = 8.33;nFactor=8.15;}//-954, -554, 8.33 *
     }
      else if((document.all)&&(!browserFound)){ //Corrections for I.E
      browserFound=true;
      if(mapNo == 11 ){var eOffset = -568; var nOffset = -183;var eFactor = 8.54;}//-568, -183, 8.54 *
      if(mapNo == 12 ){var eOffset = -989; var nOffset = -183;var eFactor = 8.50;}//-989, -183, 8.50 *
      if(mapNo == 21 ){var eOffset = -562; var nOffset = -552;var eFactor = 8.50;nFactor=7.95;}//-560, -552, 8.40 *
      if(mapNo == 22 ){var eOffset = -955; var nOffset = -572;var eFactor = 8.33;nFactor=8.15;}//-955, -555, 8.33 *
     }
      else if((window.devicePixelRatio)&&(!browserFound)){ //Corrections for Safari and Chrome
      browserFound=true;
      if(mapNo == 11 ){var eOffset = -568; var nOffset = -185;var eFactor = 8.54;}//-568, -183, 8.54 *
      if(mapNo == 12 ){var eOffset = -990; var nOffset = -183;var eFactor = 8.50;}//-990, -183, 8.50 *
      if(mapNo == 21 ){var eOffset = -562; var nOffset = -552;var eFactor = 8.50;nFactor=7.95;}//-562, -552, 8.50 *
      if(mapNo == 22 ){var eOffset = -955; var nOffset = -572;var eFactor = 8.33;nFactor=8.15;}//-955, -555, 8.33 *
     }
      else{ //set other browsers as for Firefox
      if(mapNo == 11 ){var eOffset = -568; var nOffset = -185;var eFactor = 8.54;}//-568, -185, 8.54 *
      if(mapNo == 12 ){var eOffset = -988; var nOffset = -186;var eFactor = 8.50;}//-988, -186, 8.50 *
      if(mapNo == 21 ){var eOffset = -562; var nOffset = -551;var eFactor = 8.50;nFactor=7.93;}//-562, -555. 8.40 *
      if(mapNo == 22 ){var eOffset = -955; var nOffset = -573;var eFactor = 8.33;nFactor=8.14;}//-956, -556, 8.33 *
     } //end else
      
      eCorrected = eCorrected * eFactor;
      eCorrected = eCorrected + eOffset;
      nCorrected = nCorrected * nFactor;
      nCorrected = nCorrected + nOffset;
      noBlink=true;
     //Plot a spot at approx position of grid ref.
       plotSpot(eCorrected,nCorrected);
  } //eof gridRefPlot


  function newPic(source){
    var picPoint = document.getElementById("place"); // place of old picture to be replaced
    if(picPoint.nodeName !="IMG") return true;
    picPoint.setAttribute("src",source);
  } //eof newPic


function plotSpot(x,y) {
   // if (longTbl == true) return false;
   if (!document.getElementById("spot")) return false;
   elemSpot = document.getElementById("spot");
   elemSpot.style.position ="absolute";
   elemSpot.style.left = x + "px";
   elemSpot.style.top = y + "px";
   elemSpot.style.color ="#000000";
   elemSpot.style.fontWeight = "bold";
   elemSpot.style.fontFamily ='Arial';
   elemSpot.style.display = "inline";
   if (noBlink){
       blink(); // set blink once
       noBlink = false;
   }
 } //end of plotSpot
 

 function blink() {
    blTimer = null; // blink timer
    blOn = true; // blink state
    blnkrs = new Array; // array of spans
    var blCount = 0;
    blnkrs[blCount] = elemSpot;
    blCount++;
    hue1 ="#0044ff"; //colours of the spot
    hue2 ="#ff0000";
    hue3="#00ff00";
    hue4="#000000"
    hue=hue1;
    num=0;
    /* time in m.secs between blinks
     500 = 1/2 second*/
    blinkTimer(500);
}//eof blink


function blinkTimer(ival) {
    blinkIt();
    blTimer = window.setTimeout('blinkTimer(' + ival + ')', ival);
} // eof blinkTimer

function blinkIt() {
    for (var i = 0; i < blnkrs.length; i++) {
        if (blOn == true) {
            blnkrs[i].style.visibility = "hidden";
       }
       else {
            blnkrs[i].style.visibility = "visible";
            blnkrs[i].style.color =hue;
       }
    }//end of for i
    blOn =!blOn;
    if (num==2){
        hue=hue1;
    }
    if (num ==4){
        hue=hue2;
    }
    if( num ==6){
        hue= hue3;
    }
    if(num>7){
        hue = hue4;
        num=0;
    }
    num++;
}//eof blink

function blinkWindow(){
   wallPaper =new Array;
   wallPaper[0]="ff";
   wallPaper[1]="f7";
   wallPaper[2]="ef";
   wallPaper[3]="e7";
   wallPaper[4]="df";
   wallPaper[5]="d7";
   wallPaper[6]="cf";
   wallPaper[7]="c7";
   winBlink =document.getElementById("note");
   fadeIn(7);
 }  //eof blinkWindow

function fadeIn(hueNo){
   if(hueNo >=0){
      winColor="#"+"ff"+wallPaper[hueNo]+wallPaper[hueNo];
      hueNo -=1;
      setTimeout("fadeIn("+hueNo+")",50);
   }else{ //hueNo= -1
       setTimeout("fadeOut(0)",50);
   } //end of else
   winBlink.style.backgroundColor=winColor;
} //eof fadeIn


function fadeOut(hueNo){
   if(hueNo <8){
      winColor="#"+"ff"+wallPaper[hueNo]+wallPaper[hueNo];
      hueNo +=1;
      setTimeout("fadeOut("+hueNo+")",50);
  }else{ //hueNo>7
      setTimeout("fadeIn(7)",50);
  } //end of else
  winBlink.style.backgroundColor=winColor;
} //eof fadeOut


function seeOS(){ //function called from walk.html by clicking paragraph containing 'Find whichOS map is applicable.'
    if(mapNo == 11){hRefer="images/OS11.jpg";}
    if(mapNo ==12){hRefer="images/OS12.jpg";}
    if(mapNo == 21){hRefer="images/OS21.jpg";}
    if(mapNo == 22){hRefer="images/OS22.jpg";}
    newPic(hRefer);
    osMapBtnElem.style.visibility = "hidden"; //remove "look for OS Map" button
} //eof seeOS
 
