/* gmap.js
     Javascript functions for UoMn MapServer querying and navigation
   S.W. Adcock,  February 2008
*/

/* Element id values   */

LOADING = "loading";      /* div element to display during initial
                             loading of the page                      */
DIV_MAP = "div_map";      /* div element that encloses the main part
                             of the page - the map and the associated
                             form.                                    */
IMG_MAP = "mapa";         /* img element that displays the map        */

var english = true;

/* ------------------------------------------------------------------ */

function validate(lon, lat, nts)
{
  lon = lon.trim();
  lat = lat.trim();
  nts = nts.trim();

  if ( lon == '' && lat == '' && nts == '' ) return true;

  if ( lon == '' && lat == '' && nts != '' ) return true;

  if ( ( lon == '' && lat != '' ) ||  ( lon != '' && lat == '' ) )
  {
    alert('Longitude and latitude must both be specified');
    return false;
  }

  if ( ( lon != '' || lat != '' ) &&  ( nts != '' ) )
  {
    alert('Cannot specify both longitude/latitude and NTS');
    return false;
  }

  if (isNaN(lat))
  {
    alert('Latitude is not a valid decimal number');
    return false;
  }
  else
  {
    if (lat < 42 || lat > 90 )
    {
      alert('Latitude must lie in the range 42 - 90 degrees');
      return false;
    }
  }

  if (isNaN(lon))
  {
    alert('Longitude is not a valid decimal number');
    return false;
  }
  else
  {
    if (lon < -142 || lon > -50 )
    {
      alert('Longitude must lie in the range -50 to -142 degrees');
      return false;
    }
  }

  return true;
}

/* ------------------------------------------------------------------ */

function doneLoading()
{
  if ( document.forms[0] == null )
  {
    alert ("Server PHP error.  Aborting!");
    return false;
  }

  hideDiv(LOADING);

  var langPage = getLanguage();
  changeText(LOADING, "Querying...", "Interrogation...");

  var iZoom = parseInt(document.forms[0].zoomit.value);
  if ( iZoom == -2  || iZoom == 3 )
  {
    document.forms[0].zoomit.value = "0";
  }
  nav_set(parseInt(document.forms[0].zoomit.value));
  size_set(parseInt(document.forms[0].sizeit.value));

  /* For the smallest map, display the page using strict
     CLF formatting.  For the larger maps, relax the constraint
     on the page width                                                */
  var iSize = parseInt(document.forms[0].sizeit.value);
  if ( iSize == 1 )
  {
    setDivClass(DIV_MAP,'page');
  }
  else
  {
    setDivClass(DIV_MAP,'formMap');
  }

  /* set the display options for the NTS 250K and 50K layers          */
  setNTSDisplay();

}

/* ------------------------------------------------------------------ */

function hideDiv(id)
{
  var obj=null;
  obj=document.getElementById(id);
  if (obj) obj.style.display='none';
}

/* ------------------------------------------------------------------ */

function showDiv(id)
{
  var obj=null;
  obj=document.getElementById(id);
  if (obj) obj.style.display='block';
}

/* ------------------------------------------------------------------ */

function setDivClass(id, sClass)
{
  var obj=null;
  obj=document.getElementById(id);
  if(obj) obj.className = sClass;
}

/* ------------------------------------------------------------------ */

function setCursor(id, sCursor)
{
  var obj=null;
  obj=document.getElementById(id);
  if(obj) obj.style.cursor = sCursor;
}

/* ------------------------------------------------------------------ */

function nav_set(iZoom)
{
  document.forms[0].zoomin.src = "./images/icon_zoomin.gif";
  document.forms[0].zoomout.src = "./images/icon_zoomout.gif";
  document.forms[0].pan.src = "./images/icon_recentre.gif";
  document.forms[0].query.src = "./images/icon_info.gif";

  // set the icon and cursor display properties
  switch (iZoom)
  {
    case 1:
      document.forms[0].zoomin.src = "./images/icon_zoomin_s.gif";
      setCursor(IMG_MAP,"crosshair");
      break;
    case -1:
      document.forms[0].zoomout.src = "./images/icon_zoomout_s.gif";
      setCursor(IMG_MAP,"default");   // arrow
      break;
    case 0:
      document.forms[0].pan.src = "./images/icon_recentre_s.gif";
      setCursor(IMG_MAP,"move");
      break;
    case 2:
      document.forms[0].query.src = "./images/icon_info_s.gif";
      setCursor(IMG_MAP,"help");
      break;
    case -2:
      break;
    case 3:
      document.forms[0].pan.src = "./images/icon_recentre_s.gif";
      setCursor(IMG_MAP,"move");
      break;
    default:
      document.forms[0].pan.src = "./images/icon_recentre_s.gif";
      setCursor(IMG_MAP,"move");
      document.forms[0].zoomit.value="0";
  }

  // initialise the mouse event-handlers (functions in selbox.js)
  switch (iZoom)
  {
    case 2:           // query
    case 1:           // zoom in
      pointClose();
      boxInit();
      break;
    case 0:           // pan
    case -1:          // zoom out
      boxClose();
      pointInit();
      break;
    case 3:           // zoom to specified scale
    case -2:          // return to full extent
    default:
      pointClose();
      boxClose();
  }

  return;
}

/* ------------------------------------------------------------------ */

function map_zoomscale()
{
  document.forms[0].zoomit.value = "3";
  nav_set(3);
  formSubmit(false);
}

/* ------------------------------------------------------------------ */

function map_zoomin()
{
  document.forms[0].zoomit.value="1";
  nav_set(1);
}

/* ------------------------------------------------------------------ */

function map_zoomout()
{
  document.forms[0].zoomit.value="-1";
  nav_set(-1);
}

/* ------------------------------------------------------------------ */

function map_pan()
{
  document.forms[0].zoomit.value="0";
  nav_set(0);
}

/* ------------------------------------------------------------------ */

function map_query()
{
  document.forms[0].zoomit.value="2";
  nav_set(2);
}

/* ------------------------------------------------------------------ */

function map_unzoom()
{
  document.forms[0].zoomit.value="-2";
  nav_set(-2);
  formSubmit(false);
}

/* ------------------------------------------------------------------ */

function map_size(iSize)
{
  if ( iSize != parseInt(document.forms[0].sizeit.value))
  {
    document.forms[0].sizeit.value = iSize.toString();
    size_set(iSize);
    document.forms[0].zoomit.value="0";
    nav_set(0);
    formSubmit(false);
  }
}

/* ------------------------------------------------------------------ */

function size_set(iSize)
{
  document.forms[0].size_1.src = "./images/t08.png";
  document.forms[0].size_2.src = "./images/t12.png";
  document.forms[0].size_3.src = "./images/t16.png";
  document.forms[0].size_4.src = "./images/t20.png";
  document.forms[0].size_5.src = "./images/t24.png";

  switch (iSize)
  {
    case 1:
      document.forms[0].size_1.src = "./images/s08.png";
      document.forms[0].map_width.value = "390";
      document.forms[0].map_height.value = "390";
      break;
    case 2:
      document.forms[0].size_2.src = "./images/s12.png";
      document.forms[0].map_width.value = "600";
      document.forms[0].map_height.value = "450";
      break;
    case 3:
      document.forms[0].size_3.src = "./images/s16.png";
      document.forms[0].map_width.value = "800";
      document.forms[0].map_height.value = "600";
      break;
    case 4:
      document.forms[0].size_4.src = "./images/s20.png";
      document.forms[0].map_width.value = "1000";
      document.forms[0].map_height.value = "750";
      break;
    case 5:
      document.forms[0].size_5.src = "./images/s24.png";
      document.forms[0].map_width.value = "1200";
      document.forms[0].map_height.value = "900";
      break;
    default:
      document.forms[0].size_1.src = "./images/s08.png";
      document.forms[0].map_width.value = "400";
      document.forms[0].map_height.value = "400";
  }
  document.forms[0].mapa.width =
              parseInt(document.forms[0].map_width.value);
  document.forms[0].mapa.height =
              parseInt(document.forms[0].map_height.value);
  return;
}

/* ------------------------------------------------------------------ */

/*  nonSpatialSearch()
    Executed when the user clicks the 'Submit Search' button          */

/* ------------------------------------------------------------------ */

function nonSpatialSearch()
{
    if ( !validate(document.forms[0].lon.value,
                   document.forms[0].lat.value,
                   document.forms[0].nts.value) ) return false;

    // check the Title string for invalid characters
    szCheck = checkString( document.forms[0].txtTitleShow.value );
    if ( szCheck != '' )
    {
        alert( 'Title: ' + szCheck );
        return false;
    }

    // check the abstract string for invalid characters
    szCheck = checkString( document.forms[0].txtAbstractShow.value );
    if ( szCheck != '' )
    {
        alert( 'Abstract: ' + szCheck );
        return false;
    }

    // set flag
    document.forms[0].search_database.value = 1;

    // submit form
    formSubmit(false);
    return true;
}

/* ------------------------------------------------------------------ */

function checkString( szString )
{
    // check for '
    if ( szString.indexOf("'") != -1 )
    {
        return ( "Invalid character found.  " +
                 "The character ' is not allowed in a filter." );
    }

    // add more cases as required
    // ....

    // return
    return '';
}

/* ------------------------------------------------------------------ */

function boxOnDrawEnd(oRect)
{
  document.forms[0].mapa_x.value = oRect.left;      // west
  document.forms[0].mapa_x1.value = oRect.right;    // east
  document.forms[0].mapa_y.value = oRect.bottom;    // south
  document.forms[0].mapa_y1.value = oRect.top;      // north

  formSubmit(false);

  return true;
}

/* ------------------------------------------------------------------ */

function boxOnPointEnd(pt)
{
  document.forms[0].mapa_x.value = pt.x;            // longitude
  document.forms[0].mapa_y.value = pt.y;            // latitude

  formSubmit(false);

  return true;
}

/* ------------------------------------------------------------------ */

function setNTSDisplay()
{
  i250K = parseInt(document.forms[0].map_base_250K.value);
  i50K = parseInt(document.forms[0].map_base_50K.value);
  iScale = parseInt(document.forms[0].map_scale.value);
  i50K_MaxScale = parseInt(document.forms[0].map_50K_maxscale.value);
  i250K_MaxScale = parseInt(document.forms[0].map_250K_maxscale.value);

  if (i250K == -1 )
  {
    if ( iScale > i50K_MaxScale && iScale <= i250K_MaxScale )
      document.forms[0].chk250.checked = true;
    else
      document.forms[0].chk250.checked = null;
  }
  else if ( i250K == 1 )
    document.forms[0].chk250.checked = true;
  else
    document.forms[0].chk250.checked = null;

  if (i50K == -1 )
  {
    if ( iScale > i50K_MaxScale )
      document.forms[0].chk50.checked = null;
    else
      document.forms[0].chk50.checked = true;
  }
  else if ( i50K == 1 )
    document.forms[0].chk50.checked = true;
  else
    document.forms[0].chk50.checked = null;

}

/* ------------------------------------------------------------------ */

function selectScale()
{
  var iMin250 = parseInt(document.forms[0].map_250K_minscale.value);
  var iMax250 = parseInt(document.forms[0].map_250K_maxscale.value);
  var iMin50 = parseInt(document.forms[0].map_50K_minscale.value);
  var iMax50 = parseInt(document.forms[0].map_50K_maxscale.value);

  var oldScale = parseInt(document.forms[0].map_scale.value);
  var minScale = parseInt(document.forms[0].map_minscale.value);
  var maxScale = parseInt(document.forms[0].map_maxscale.value);

  if ( oldScale < minScale  || oldScale > maxScale )
  {
    alert( "critical error!\n\n" +
           "map scale: " + oldScale + "\n" +
           "outside allowable range: " + minScale + " - " + maxScale);
  }

  var newScale = document.forms[0].txtScale.value;

  newScale = newScale.trim();

  if ( isInteger(newScale) )
  {
    document.forms[0].map_scale.value = newScale;
    if ( newScale < minScale  || newScale > maxScale )
    {
      alert( " Input: " + newScale + "\n" +
           "is outside allowable range: " + minScale + " - " +
            maxScale + "\n\n  Reverting to old scale");
      document.forms[0].txtScale.value = oldScale;
    }
  }
  else
  {
    alert( "Error!\n\n" +
           "Input: '" + newScale + "' is not a valid integer" +
           "\n\n  Reverting to old scale");
    document.forms[0].txtScale.value = oldScale;
  }

  if ( newScale > iMax250 )
  {
    document.forms[0].chk250.checked = false;
    document.forms[0].map_base_250K.value = -1;
  }
  else if ( newScale >= iMin250 )
  {
    document.forms[0].chk250.checked = true;
    document.forms[0].map_base_250K.value = 1;
  }

  if ( newScale > iMax50 )
  {
    document.forms[0].chk50.checked = false;
    document.forms[0].map_base_50K.value = -1;
  }
  else
  {
    document.forms[0].chk50.checked = true;
    document.forms[0].map_base_50K.value = 1;
  }

  document.forms[0].map_userdef_scale.value = 1;

}

/* ------------------------------------------------------------------ */

function select250K()
{
  var iMin = parseInt(document.forms[0].map_250K_minscale.value);
  var iMax = parseInt(document.forms[0].map_250K_maxscale.value);

  var newScale = parseInt(document.forms[0].txtScale.value);

  if (document.forms[0].chk250.checked)
  {
    if ( newScale > iMax )
    {
      alert ("Current scale: " + newScale + "\n\n" +
             "NTS 1:250K base is always disabled at scales above " +
              iMax );
      document.forms[0].map_base_250K.value = -1;
      document.forms[0].chk250.checked = null;
    }
    else
    {
      document.forms[0].map_base_250K.value = 1;
    }
  }
  else
  {
    if ( newScale > iMax )
    {
      document.forms[0].map_base_250K.value = -1;
    }
    else if ( newScale > iMin )
    {
      alert ("Current scale: " + newScale + "\n\n" +
             "NTS 1:250K base is always enabled at scales between " +
              iMin + " and " + iMax );
      document.forms[0].map_base_250K.value = 1;
      document.forms[0].chk250.checked = true;
    }
    else
    {
      document.forms[0].map_base_250K.value = 0;
    }
  }

}

/* ------------------------------------------------------------------ */

function select50K()
{
  var iMin = parseInt(document.forms[0].map_50K_minscale.value);
  var iMax = parseInt(document.forms[0].map_50K_maxscale.value);

  var newScale = parseInt(document.forms[0].txtScale.value);

  if (document.forms[0].chk50.checked)
  {
    if ( newScale > iMax )
    {
      alert ("Current scale: " + newScale + "\n\n" +
             "NTS 1:50K base is always disabled at scales above " +
              iMax );
      document.forms[0].map_base_50K.value = -1;
      document.forms[0].chk50.checked = null;
    }
    else
    {
      document.forms[0].map_base_50K.value = 1;
    }
  }
  else
  {
    if ( newScale > iMax )
    {
      document.forms[0].map_base_50K.value = -1;
    }
    else
    {
      document.forms[0].map_base_50K.value = 0;
    }
  }
}

/* ------------------------------------------------------------------ */

/* mapRedraw
   use the specified scale to zoom in or out, on the centre of the map
                                                                      */

/* ------------------------------------------------------------------ */

function mapRedraw()
{
  document.forms[0].map_scale.value = document.forms[0].txtScale.value;
  document.forms[0].map_user_redraw.value = 1;
  var newScale = document.forms[0].map_scale.value;

  /* alert ("map scale will be set to: " + newScale + "\n" +
         "1:250K status: " + document.forms[0].map_base_250K.value
          + "\n" +
         "1:50K status: " + document.forms[0].map_base_50K.value );   */
  map_zoomscale();
}

/* ------------------------------------------------------------------ */

/* formSubmit
                                                                      */
/* ------------------------------------------------------------------ */

function formSubmit(verify)
{
  var answer = true;

  if (verify)
    answer = confirm("Do you really want to submit the form?");

  if (answer)
  {
    document.body.style.cursor="wait";  // not working ?
    showDiv(LOADING);

    // encode the title and abstract textboxes
    document.forms[0].txtTitle.value =
               escape( document.forms[0].txtTitleShow.value );

    document.forms[0].txtAbstract.value =
               escape( document.forms[0].txtAbstractShow.value );

    document.forms[0].submit();
    if (verify) alert("Form has been submitted!");
    return true;
  }
  else
  {
    alert("Submit has been cancelled!");
    return false;
  }
}

/* ------------------------------------------------------------------ */

/* formReset
     Replaces the default handler for the form reset event
     Confirm that the user wants to reset the form.  If yes, then
     reset all of the fields
                                                                      */
/* ------------------------------------------------------------------ */

function formReset()
{
  var question = "Do you really want to reset the form?";

  if (location.pathname.indexOf('_f') != -1 )
    question =  "Voulez-vous vraiment réinitialiser la forme?";

  var answer = confirm(question);

  if (answer)
  {
    document.forms[0].reset();
    document.forms[0].selOrg.selectedIndex = -1;
    document.forms[0].selYear.selectedIndex = -1;
    document.forms[0].selYearOp.selectedIndex = -1;
    document.forms[0].selProvince.selectedIndex = -1;
    document.forms[0].selSurveyType.selectedIndex = -1;

    document.forms[0].txtTitleShow.value = '';
    document.forms[0].txtAbstractShow.value = '';

    document.forms[0].lon.value = '';
    document.forms[0].lat.value = '';
    document.forms[0].nts.value = '';

    // reset previous query list
    document.forms[0].txtPrevHighlightedIDs.value = '';

    // return to full extent
    document.forms[0].zoomit.value="-2";
    nav_set(-2);

    /* nonSpatialSearch with all input fields reset will restore the
       map to its initial state (all surveys displayed, none
       highlighted)                                                   */
    nonSpatialSearch();

    // alert("Form has been reset!");

    /* return false stops the default handler from executing - only
       works in Firefox, not IE7.  Therefore make the input
       type="button", not type="reset"                                */
    return false;
  }
  else
  {
    // alert("Reset has been cancelled!");
    return false;
  }
}

/* ------------------------------------------------------------------ */

function isInteger(iTest)
{
  var i;
  var c;
  var sSet = "0123456789";

  for ( var i = 0; i < iTest.length; i++)
  {
    c = iTest.charAt(i);
    if (sSet.indexOf (c, 0) == -1 ) return false;
  }
  return true;
}

/* ------------------------------------------------------------------ */

/* changeText
     Replaces a text string in a web page element.  Currently, it is
     designed to work for a simple structure:
     <div id="myID"><p>text to change</p></div>
                                                                      */
/* ------------------------------------------------------------------ */

function changeText(id, txtChange_en, txtChange_fr)
{
  var fieldNameElement = document.getElementById(id);

  /*  alert("Text to change:" + "\n" +
       fieldNameElement.firstChild.firstChild.nodeValue);             */

  if(fieldNameElement.firstChild.firstChild)
  {
    if (english)
    {
      fieldNameElement.firstChild.firstChild.nodeValue = txtChange_en; 
    }
    else
    {
      fieldNameElement.firstChild.firstChild.nodeValue = txtChange_fr;
    }
  }

  /*  alert("New text:" + "\n" +
       fieldNameElement.firstChild.firstChild.nodeValue);             */
}

/* ------------------------------------------------------------------ */

  function getLanguage()
  {
    var s1 = window.location.href;

    var s2 = s1.substr(s1.length-12, 6);

    if ((s2.substr(s2.length-1)) == "f")
    {
       english = false; 
    } 
    return s2;
  }

/* ------------------------------------------------------------------ */

String.prototype.trim=function(){
    return this.replace(/^\s*|\s*$/g,'');
}

String.prototype.ltrim=function(){
    return this.replace(/^\s*/g,'');
}

String.prototype.rtrim=function(){
    return this.replace(/\s*$/g,'');
}

/* ------------------------------------------------------------------ */

