// external.js

/*********************************************************
 * Globals                                               *
 * map     : GMap2 object - id of document map <div>     *
 * center  : GLatLng object - Lat and Long of centre     *
 *********************************************************/
var map, center;

/*********************************************************
 * Other globals set in each calling HTML module         *
 *********************************************************/
// Map name and first label line
var mapname;
// Map location and zoom
var lat, lng, zoom ;
// Rectangle parameters
var width, height, rotate;
// Other label lines
var title2;
// Streetview parameters
var yaw, pitch, svzoom, svlat, svlng;
/** END Globals **/

function handleNoFlash(errorCode) {
/*********************************************************
 * errorCode : Error code found                          * 
 *********************************************************/
  if (errorCode == FLASH_UNAVAILABLE)
    alert("Error: Flash doesn't appear to be supported by your browser")
  else if (errorCode == NO_NEARBY_PANO)
     alert("Error: No nearby panorama data was found.")
  else alert("Error: Error Code = " + errorCode);
}
/** END handleNoFlash() **/

function mapLoad() {
/*********************************************************/
  if (GBrowserIsCompatible()) {
    // Set globals
    map = new GMap2(document.getElementById("map_canvas"));
    center = new GLatLng(lat,lng);		// map Center
    document.getElementById("mapname").innerHTML=mapname;    
    // Call other functions
    setMap();
    addRectangle(width, height, {rRotate: rotate});
    setMarker(center, {rTitle1: mapname, rTitle2: title2});    
    streetview(yaw, pitch, svzoom);
  } // END if
  else
    alert ('Browser is not compatible with Google Maps');
}
/** END mapLoad() **/

function setMap() {
/*********************************************************
 * Set default map details                               *
 * =======================                               *
 * NOTE : map.getCenter() returns map centre             *
 *        in format of GLatLng                           *
 *********************************************************/
  map.setCenter(center, zoom)			// Centre and zoom level
  map.setMapType(G_HYBRID_MAP)			// Map type - Hybrid
  map.addControl(new GMapTypeControl()) 	// Map|Satellite|Hybrid control buttons
  map.addControl(new GLargeMapControl())	// Large pan/zoom control
  map.addControl(new GOverviewMapControl())	// Collapsible overview map
  map.addControl(new GScaleControl())		// Map scale
/*
  map.addOverlay(new GStreetviewOverlay())	// Street View overlay
*/
  GEvent.addListener(map, "error", handleNoFlash)
}
/** END setMap **/

function addRectangle(rWidth, rHeight, opts) {
/*********************************************************
 * Add rectangle to map                                  *
 * ====================					 *
 * rWidth  : width of rectangle in degrees of longitude  *
 * rHeight : height of rectangle in degrees of latitude  *
 * opts    : { rRotate: val, other1: val, ..etc.. }      *
 *   rRotate : angle of rotation of rectangle in degrees *
 *	           (clockwise)                               *
 *                                                       *
 * NOTE    : x(width) = longitude; y(height) = latitude  *
 *********************************************************/
  if (opts && typeof(opts) != 'object') {
    alert ("Parameter 'opts' should be an array of options")
    return
  }

  // If rRotate passed, convert to degrees. Else set to zero
  var rRotate = (opts) ? opts.rRotate * Math.PI/180 : 0

  // Get Latitude and Logitude of center (degrees)
  var cLat = center.lat()
  var cLng = center.lng()

  // Calculate metres per Lat and Long
  var mPerLat = center.distanceFrom(new GLatLng(cLat+1, cLng))
  var mPerLng = center.distanceFrom(new GLatLng(cLat, cLng+1))

  // Convert rHeight and rWidth to metres
  rHeight *= mPerLat
  rWidth  *= mPerLng

  var rAngle = Math.atan(rHeight/rWidth)	// Diagonal angle from horiz.(radians)
  var rDiag  = 0.5*rHeight/Math.sin(rAngle)	// Distance vertex to centre (metres)

  // Calculate Top Left and Bottom Right offset from center (degrees lng and lat)
  var offsetx1 = rDiag*Math.cos(rAngle+rRotate)/mPerLng
  var offsety1 = rDiag*Math.sin(rAngle+rRotate)/mPerLat

  // Calculate Bottom Left and Top Right offset from center (degrees lng and lat)
  var offsetx2 = rDiag*Math.cos(rAngle-rRotate)/mPerLng
  var offsety2 = rDiag*Math.sin(rAngle-rRotate)/mPerLat

  // Define and add polygon
  map.addOverlay(new GPolygon(
        [  new GLatLng(cLat + offsety1, cLng - offsetx1) // topleft
         , new GLatLng(cLat + offsety2, cLng + offsetx2) // topright
         , new GLatLng(cLat - offsety1, cLng + offsetx1) // botright
         , new GLatLng(cLat - offsety2, cLng - offsetx2) // botleft
         , new GLatLng(cLat + offsety1, cLng - offsetx1) // topleft
        ], "#f00", 1, 0.5, "#ffc", 0.5	// stroke color, weight, opacity; fill color, opacity
  	 )
  )
}
/** END addRectangle **/

function setMarker(center, opts) {
/*********************************************************
 * Set marker                                            *
 * ==========                                            *
 * center  : GLatLng object - Lat and Long of marker     *
 * opts    : {  rIcon :  rIcon                           *
 *            , rTitle1: rTitle1                         *
 *            , rTitle2: rTitle2 }                       *
 *   rIcon   : icon image to be displayed                *
 *   rTitle1 : First line of title                       *
 *   rTitle2 : Other lines of title                      *
 * NOTE    : x(width) = longitude; y(height) = latitude  *
 *********************************************************/
  // Extract local variables
  var rIcon = G_DEFAULT_ICON , rTitle1=' ', rTitle2=' ';

  if (opts) {
    if (typeof(opts) != 'object') {
      alert ("Parameter 'opts' should be an array of options");
      return;
    }
    else {
      rIcon   = opts.rIcon || rIcon ;
      rTitle1 = opts.rTitle1 || rTitle1;
      rTitle2 = opts.rTitle2 || rTitle2;
    }
  }
  /***
  else {
    var rIcon = new GIcon();
        rIcon.image = "images/red.gif";
        rIcon.iconAnchor = new GPoint(10, 34);
  }
  ***/

  // Define and position marker

  var marker = new LabeledMarker(center,
  {  "icon": rIcon
   , "clickable": true
   , "title": "Click to view information"
   , "labelText": "<div title='Click marker to view information'"
                 + "align='left'><===" + rTitle1 + "</div>"
   /* , "labelOffset": new GSize(40, 0) */ } )
  map.addOverlay(marker)

  // Add balloon text at center
  rTitle1 = "<div title='Click X to close this box'>"
          + rTitle1 + '<br/>' + rTitle2  + "</div>"
  // Open immediately
  // map.openInfoWindow(center, rTitle1)

  GEvent.addListener(marker, "click",
  	   function(){ map.openInfoWindow(center, rTitle1) } )
}
/** END setMarker **/

function streetview(yaw, pitch, svzoom) {
/*********************************************************
 * yaw      : Deviation of streetview from N (90 = East) *
 * pitch    : Angle from vertical                        *
 *            (0=horizontal, 90= vertically down)        *
 * svzoom   : Zoom level of streetview (0 = none)        *
 *********************************************************/
  var myPano = new GStreetviewPanorama(document.getElementById('pano'));
  var svcenter = new GLatLng(svlat, svlng);	// streetview center

  yaw    = yaw || 0 ;
  pitch  = pitch || 0 ;
  svzoom = svzoom || 0 ;

  myPano.setLocationAndPOV(svcenter, {yaw: yaw, pitch: pitch, zoom: svzoom});
  GEvent.addListener(myPano, "error", handleNoFlash);
}
/** END streetview() **/

function openmap(url){
/*********************************************************
 * url     : URL of page holding map                     *
 *********************************************************/
spawnJimcoPopup(url, ''
	,  'toolbar=no,location=no,directories=no,status=no,menubar=no'
         + ',scrollbars=yes,resizable=yes'
	, 600, 600, 'center', '0', 'pixel')
}
/** END openmap() **/

function hidesv(panoId){
/*********************************************************
 * panoId  : ID of div holding streetview                *
 *********************************************************/
  var d = document.getElementById(panoId);
  var dd = d.style.display;
  dd = d.style.display = ((!dd) || (dd == 'none')) ? 'block'
                       : (dd != 'none') ? 'none'
                       :  dd ;
  window.resizeBy(0, (dd != 'none') ? 300 : -300)

  /** Alternative
  var dc = d.currentStyle || getComputedStyle(d,null);
  var sd = d.style.display = (dc.display == 'none') ? '' : 'none';
  window.resizeBy(0, (sd != 'none') ? 200 : -200)
  **/
}
/** END hidesv() **/

function qsobj(parm) {
/*********************************************************
 * Retrieves value of variables passed with url          *
 *********************************************************/	
  var qpairs=[], qvbl=[];  
  
  // get url string after '?' and split by "&"
  qpairs = location.search.substring(1).split("&");
  
  // if it exists, split qpairs[parm] by "=" into an array  
  if (qpairs[parm])
    qvbl = qpairs[parm].split("=");
  
  // return string after '=' if it exists, else null
  return qvbl[1] ? unescape(qvbl[1].replace(/%20|\ +/g," ")) : null;
} // ---- end qsobj() ------------

function spawnJimcoPopup(url, name, options, h, w, x, y, scaleType) {
/*********************************************************
 * NOTE: name = '' or null === name = '_blank'           *
 *       options = '' or null sets all options = yes     *
 *       options = 'no' sets all options = no            *
 *       h, w = height and width                         *
 *       x, y = a number or 'center'                     *
 *       scaleType = 'percent' or 'pixel'                *
 * FOR FULL SCREEN, call as                              *
 *       spawnJimcoPopup(url, name, options)             *
 *    OR spawnJimcoPopup(url, name)                      *
 *    OR spawnJimcoPopup(url)                            *
 *    OR call window.open(...) with same parameters      *
 *********************************************************/
  var new_Window;

  if (!options)
    { options = ''; }
  else if (options=='no') {
    options = 'toolbar=no,location=no,directories=no,status=no'
            + ',menubar=no,scrollbars=no,resizable=no';
  }

  if (scaleType == 'percent')
   { h = (h * screen.availHeight) / 100;
     w = (w * screen.availWidth)  / 100; }

  if (x == 'center')
    { x = (screen.availWidth  - w) / 2; }
  if (y == 'center')
    { y = (screen.availHeight - h) / 2; }

  options += (w) ? ',width='  + w: '';
  options += (h) ? ',height=' + h: '';
  options += (x) ? ',left='   + x: '';
  options += (y) ? ',top='    + y: '';

  new_Window = window.open(url, name, options);
  new_Window.focus();
} // ---- end spawnJimcoPopup() --

function writeem(ename){
/*********************************************************
 * ename  : Destination email addresse (tcl/ratec)       *
 *********************************************************/
  var title = 'Click&nbsp;Here&nbsp;to&nbsp;Email&nbsp;Me';
  var subject = 'Response from RATEC site';
  var body = 'Please enter your message here';
  var eaddr = (ename=='tcl') ? 'tandcl' + '@' + 'homemail' + '.com.au'
            : (ename=='ratec') ? 'webmaster' + '@' + 'ratec' + '.actbus' + '.net'
            : ' ';
  var text = title;     
  document.write('<a onmouseover="window.status=\' \';return true;"'
               + 'title=' + title 
               + ' href="mailto:' + eaddr
               + '?subject=' + subject
               + '&body=' + body + '">'
               + '<br><span style="color:black; background:#f5f5dc">' + text + '</span></a>');
}
/** END writeem **/

function generatenew(fDays) {
/*********************************************************
 * fDays  : Day of file update                           *
 *********************************************************/
    now = new Date();
    nDays = now.getTime() / 86400000;
    if((nDays - fDays) <= 30)
      document.write('<span class="newlabel">NEW<\/span>');
}
/** END generatenew **/

function writeiFrame(url){	
/*********************************************************
 * url  : URL to losd into iFrame                        *
 *********************************************************/
  var h = screen.availHeight - 175;
  var w = Math.min(screen.availWidth-4,1024);
  var x = document.getElementById("fid");
  x.width = w;
  x.height = h;
  x.src = url;
}
/** END writeiFrame **/  
  
/*********************************************************
// Polylines
  var polyline = new GPolyline([topleft,topright],"#ff0000", 10);
  map.addOverlay(polyline);
  var polyline = new GPolyline([topright,botright],"#ff0000", 10);
  map.addOverlay(polyline);
  var polyline = new GPolyline([botright,botleft],"#ff0000", 10);
  map.addOverlay(polyline);
  var polyline = new GPolyline([botleft,topleft],"#ff0000", 10);
  map.addOverlay(polyline);

// Polygon on Click
  var map = new GMap2(document.getElementById("map_canvas"));
  map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  map.addControl(new GSmallMapControl());

  GEvent.addListener(map, 'click',
        function(overlay, latlng)
  	{  var lat = latlng.lat();
  	   var lon = latlng.lng();
  	   var latOffset = 0.01;
  	   var lonOffset = 0.01;
  	   var polygon = new GPolygon(
  	        [new GLatLng(lat, lon - lonOffset),
  	   	 new GLatLng(lat + latOffset, lon),
  	   	 new GLatLng(lat, lon + lonOffset),
  	   	 new GLatLng(lat - latOffset, lon),
  	   	 new GLatLng(lat, lon - lonOffset)]
  	   	 , "#f33f00", 5, 1, "#ff0000", 0.2);
  	   map.addOverlay(polygon); }  );

// control position of MapType
  var mapTypeControl = new GMapTypeControl();
  var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
  var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
  map.addControl(mapTypeControl, topRight);

  GEvent.addListener(map, "dblclick",
                     function(){map.removeControl(mapTypeControl); map.addControl(new GMapTypeControl(), bottomRight);} );
  map.addControl(new GSmallMapControl());
*********************************************************/