/*---------------------------------------------------------------------------*/
/* LINK VARIABLES */

var lotusNotesDatabase = "/internet/otd/publishing.nsf/";
var locatorPage        = lotusNotesDatabase + "Content/locator";

var busySymbol         = lotusNotesDatabase + "AttachmentsByTitle/busy.gif/$FILE/busy.gif"; 
var targetSymbol       = "http://www.doctorconnect.gov.au/internet/otd/publishing.nsf/AttachmentsByTitle/target.gif/$FILE/target.gif"
var corporateLogo      = lotusNotesDatabase + "AttachmentsByTitle/locatorPrintCrest.gif/$FILE/locatorPrintCrest.gif";
var siteLogo           = lotusNotesDatabase + "AttachmentsByTitle/locatorDCPrintLogo.gif/$FILE/locatorDCPrintLogo.gif";

var dwsFactSheet       = lotusNotesDatabase + "Content/dwsFactsheet";
var medicareForms      = "http://www.medicareaustralia.gov.au/provider/pubs/medicare-forms/provider-number.jsp";
var outerMetropolitan  = "http://www.health.gov.au/outermetro"; 

/*---------------------------------------------------------------------------*/
/* GLOBAL VARIABLES */

var map = null;
var geocoder = null;
var placemarkObject = null;
var infoArgs = null;
var infoPoint = null;
var infoLayer = null;
var infoHTML = null;
var infoForm = null;

/*---------------------------------------------------------------------------*/
/* CURRENT DATE */

function getCurrentDate() {
	var months=new Array(13);
	months[1]="January";
	months[2]="February";
	months[3]="March";
	months[4]="April";
	months[5]="May";
	months[6]="June";
	months[7]="July";
	months[8]="August";
	months[9]="September";
	months[10]="October";
	months[11]="November";
	months[12]="December";
	
	var weekday=new Array(7);
	weekday[0]="Sunday";
	weekday[1]="Monday";
	weekday[2]="Tuesday";
	weekday[3]="Wednesday";
	weekday[4]="Thursday";
	weekday[5]="Friday";
	weekday[6]="Saturday";
	
	var time=new Date();
	var lmonth=months[time.getMonth() + 1];
	var date=time.getDate();
	var year=time.getYear();
	if (year < 2000) {
	  year = year + 1900;
	}
	
	return weekday[time.getDay()] + ", " + lmonth + " " + date + ", " + year;
}

/*---------------------------------------------------------------------------*/
/* INFORMATION WINDOWS */

/* Remoteness Area Information Window */
function getInfoRA(args, print) {

  infoArgs    = args;
  infoLayer   = PolyTile.activeLayer;
  infoPoint   = args[0];
  var method  = args[1];
  var search  = args[2];
  var result  = args[3];
  var address = args[4];
  var region  = args[5];
  var rrma    = args[6];

  var classification = [];
  classification[0] = "Major Cities";
  classification[1] = "Inner Regional";
  classification[2] = "Outer Regional";
  classification[3] = "Remote";
  classification[4] = "Very Remote";

  return '<table border="0" cellspacing="0" cellpadding="2">'
  +  '<tr>'
  +    '<td class="iwb">Geographic Information</td><td>&nbsp;</td>'
  +  '</tr>'
  +  '<tr>'
  +    '<td class="iw">Address:</td><td class="iw">' + result + '</td>'
  +  '</tr>'
  +  '<tr>'
  +    '<td class="iw">Longitude,Latitude:</td><td class="iw">' + infoPoint.x.toFixed(6) + ',' + infoPoint.y.toFixed(6) + '</td>'
  +  '</tr>'  
  +  '<tr>'
  +    '<td class="iw">Classification:</td>'
  +    (region.classification == 0 ? 
       '<td class="iw">Offshore</td>' : 
       '<td class="iw">RA' + region.classification + ' - ' + classification[region.classification-1] + '</td>')
  +  '</tr>'
  +  '<tr>'
  +    '<td class="iw">Previous Classification:</td>'
  +    (rrma.classification == 0 ?
       '<td class="iw">Offshore</td>' :
       '<td class="iw">RRMA ' + rrma.classification + '</td>')
  +  '</tr>'
  + ( print ? '' :
     '<tr>'
  +    '<td class="iw">Program Eligibility:</td>'
  +    (region.classification < 2 ?
       '<td class="iw">No incentives available</td>' :
       '<td class="iw"><a target="_blank" href="' + locatorPage + '/$FILE/RA' + region.classification + '.pdf">Incentive Fact Sheet</a></td>')
  +  '</tr>')
  +'</table>';
}

/*---------------------------------------------------------------------------*/
/* District of Workforce Shortage Information Window */

function getInfoDWS(args, print) {
	
  infoArgs    = args;
  infoLayer   = PolyTile.activeLayer;
  infoPoint   = args[0];
  var method  = args[1];
  var search  = args[2];
  var result  = args[3];
  var address = args[4];
  var region  = args[5];
  
  var classification = [];
  classification[0] = "No";
  classification[1] = "No";
  classification[2] = "Yes";
  
  var metro = (region.key + " ").substring(5,6);
      
  infoHTML = '<table border="0" cellspacing="0" cellpadding="2">'
  +  '<tr>'
  +    '<td colspan="2" class="iwb">Districts of Workforce Shortage for General Practice</td>'
  +  '</tr>'
  +  '<tr>'
  +    '<td class="iw">Address:</td><td class="iw">' + result + '</td>'
  +  '</tr>'    
  +  '<tr>'
  +    '<td class="iw">Longitude,Latitude:</td><td class="iw">' + infoPoint.x.toFixed(6) + ',' + infoPoint.y.toFixed(6) + '</td>'
  +  '</tr>'  
  +  '<tr>'
  +    '<td class="iw">SLA Number:</td>'
  +    (region.classification == 0 ?
       '<td class="iw">&nbsp;</td>' :
       '<td class="iw">' + (region.key + " ").substring(0,5) + '</td>')
  +  '</tr>'
  +  '<tr>'
  +    '<td class="iw">SLA Name:</td>'
  +    (region.classification == 0 ?
       '<td class="iw">&nbsp;</td>' :
       '<td class="iw">' + region.name + '</td>')
  +  '</tr>'
  +  (metro == "0" ? 
		  '' :
		  '<tr>'
  +         '<td class="iw">Urban Classification:</td>'
  +         '<td class="iw">' + (metro == "1" ? "Inner Metropolitan" : "Outer Metropolitan") + '</td>'
  +       '</tr>')
  +  '<tr>'
  +    '<td class="iw">District of Workforce Shortage: </td>'
  +    '<td class="iw">' + classification[region.classification] + ', as at ' + getCurrentDate() + '</td>'
  +  '</tr>'
  +  '<tr>'
  +    '<td colspan="2" class="iwb"><br>Information for Overseas Trained Doctors</td>'
  +  '</tr>'
  +  (region.classification == 2 ?
     '<tr><td class="iw" colspan="2">'
   +     'This location is considered to be within a District of Workforce Shortage (DWS).<br><br>'
   +     'Therefore, it is likely that an application for an exemption under section 19AB of<br>'
   +     'the <i>Health Insurance Act 1973</i> for an overseas trained doctor to access the<br>'
   +     'Medicare Benefits Scheme (MBS) at this location would be favorably considered.<br><br>'
   +     "This advice is valid for a period of three months from today's date.<br><br>"
      + ( print ? '' :
         '<b>Step 1:</b> Please click the print button in the "Search the Map" window on the right<br> '
   +	 'hand side of the page. Your preliminary assessment documentation will<br>'
   +     'appear on screen, ready for you to print.<br><br>'
   +	 '<b>Step 2:</b> Print the preliminary assessment documentation.<br><br>'
   +     '<b>Step 3:</b> Click on the link <a target="_blank" href="' + medicareForms + '">Apply for a Medicare Provider Number form</a> and attach<br>'
   +      'your preliminary assessment documentation to this form.<br><br>')
   +     '</td>'
  +  '</tr>' :
          '<tr>'
  +         '<td class="iw" colspan="2">This location is not considered to be within a District of Workforce Shortage (DWS).<br><br>'
   +         'For further information, consult the ' + (print ? '' : '<a target="_blank" href="' + dwsFactSheet + '">') + 'DWS Fact Sheet' + (print ? '' : '</a>') + '.</td>'
  +       '</tr>')
  +'</table>'; 
  
  return infoHTML;
}

/*---------------------------------------------------------------------------*/
/* Metropolitan Information Window */

function getInfoMetro(args, print) {
	  infoArgs    = args;	
	  infoLayer   = PolyTile.activeLayer;
	  infoPoint   = args[0];	
	  var method  = args[1];
	  var search  = args[2];
	  var result  = args[3];
	  var address = args[4];
	  var region  = args[5];
	  
	  var metro = (region.key + " ").substring(5,6);
	    
	  return '<table border="0" cellspacing="0" cellpadding="2">'
	  +  '<tr>'
	  +    '<td class="iwb">Geographic Information</td><td>&nbsp;</td>'
	  +  '</tr>'
	  +  '<tr>'
	  +    '<td class="iw">Address:</td><td class="iw">' + result + '</td>'
	  +  '</tr>'  
	  +  '<tr>'
	  +    '<td class="iw">Longitude,Latitude:</td><td class="iw">' + infoPoint.x.toFixed(6) + ',' + infoPoint.y.toFixed(6) + '</td>'
	  +  '</tr>'  
	  +  '<tr>'
	  +    '<td class="iw">Urban Classification:</td>'
	  +    '<td class="iw">' + (metro == "1" ? "Inner Metropolitan" : metro == "2" ? "Outer Metropolitan" : "Non-Metropolitan") + '</td>'
	  +  '</tr>'
	  +  (metro == "0" || print ?
			  '' :
	          '<tr>'
	  +         '<td class="iw">Further Information:</td>'
      +         '<td class="iw"><a target="_blank" href="' + outerMetropolitan + '">More Doctors For Outer Metropolitan Areas</a></td>'
      +       '</tr>')
 
	  
	  +  '<tr>'
	  +   	'<td class="iwb"><br/>Telehealth eligibility classification</td><td>&nbsp;</td>'
	  +   '</tr>'
	  +	   '<tr>'
	  +       '<td class="iw">Telehealth Classification:</td>'
      +       '<td class="iw">' + (metro == "1" ? "Not MBS Telehealth Eligible" : metro == "2" ? "MBS Telehealth Eligible" : "MBS Telehealth Eligible") + '</td>'
      +    '</tr>'
	  +	   '<tr>'
	  +        '<td class="iw">Further Information:</td>'
      +        '<td class="iw"><a target="_blank" href="http://www.mbsonline.gov.au/telehealth">www.mbsonline.gov.au</a></td>'
      +    '</tr>'
	  +'</table>';
	}
/*---------------------------------------------------------------------------*/
/* MAP LAYERS */

/* ASGC Remoteness Area Layer */

var raLayer = PolyTile.createLayer("RA", "ASGC Remoteness Areas", "1eu76g80939nqz3", "sla_ra_06", 0.5, 1, getInfoRA);
    PolyTile.moveLayerToTop(raLayer);
/*---------------------------------------------------------------------------*/
/* District of Workforce Shortage Layer: defined in separate javascript file */
    
    DWSLayer.setInfoWindowHTML(getInfoDWS);
    
/*---------------------------------------------------------------------------*/
/* RRMA Layer */
var rrmaLayer = new PolyTileLayer("RRMA", "RRMA", "azlbojgl2kwn38", "sla_rrma_06", 0.5, 1, getInfoRA);
    raLayer.setNextLayer(rrmaLayer);

/*---------------------------------------------------------------------------*/
/* Metropolitan Layer*/
    
var metroLayer = PolyTile.createLayer("Metro", "Eligible Metropolitan Areas", "1ld27lpws5x76v4", "sla04", 0.5, 1, getInfoMetro);

/*---------------------------------------------------------------------------*/
/* Reverse Geocode to find out an Address from (Latitude,Longitude) */

function reverseGeocode(overlay, point) {
	
  if (point != null && PolyTile.activeLayer != null) {
    if (map.getZoom() > 16) {
    	map.openInfoWindowHtml(point, "<p class='iw' style='text-align:center'>We are sorry, but we don't have<br>" +  PolyTile.activeLayer.name + " information<br>at this zoom level for this region.<br><br>Please zoom out for a broader look.</p>");
    } else {
	    geocoder.getLocations(point, function(placemark) {
          placemarkObject = placemark;
        
          var addressSummary = new AddressSummary(placemark);

          if (addressSummary.address != null) {
            PolyTile.identifyRegion([point, "CLICK", "", addressSummary.result, addressSummary.address]);
          }
	   });
    }
  }
}
  
/*---------------------------------------------------------------------------*/
/* Geocode an address to find (Latitude,Longitude) */
    
function geocode() {

   var query = document.getElementById("textInput");
   if (geocoder && query.value != null && query.value.length > 0) {

    var address = query.value;
    var originalAddress = address;

    if (address.match(/( |,)(Au|Aus|Australia)$/i)) {
    } else {
      address += " Australia";
    }
    
    geocoder.getLocations(
      address,
      function(placemark) {
    	placemarkObject = placemark;
    	
    	var addressSummary = new AddressSummary(placemark);
    	
    	if (addressSummary.address != null) {
			
			
          // -------- 22/11/2010 INNISFAIL PROBLEM ---------
          //
          // Innisfail geocode result: 146.032329,-17.524681

          if (Math.abs(addressSummary.address.point.x - 146.032329) < 0.000001 && 
              Math.abs(addressSummary.address.point.y - -17.524681) < 0.000001) {

            // move from river to street

            addressSummary.address.point = new GLatLng(-17.524565, 146.032012);
          }

          // ----------------------------------------------
		  
		    var zoom = addressSummary.address.bounds != null ? 
		    		map.getBoundsZoomLevel(addressSummary.address.bounds) : 13;
			if (zoom > 16) {
				zoom = 16;
			}
		    map.setCenter(addressSummary.address.point, zoom);
		    PolyTile.identifyRegion([addressSummary.address.point, "SEARCH", originalAddress, addressSummary.result, addressSummary.address]);		      
    	} else {
        	alert(originalAddress + " not found.");
    	}
    	
    	if (placemarkObject.Placemark) {
          for (var i=0; i<placemarkObject.Placemark.length; i++) {
	        if (placemarkObject.Placemark[i].address.length > 0) {        	   
		      var address = new Address(placemarkObject.Placemark[i]);

		      return;
		    }
          }
    	}

      }
    );
  }
}

/*---------------------------------------------------------------------------*/
/* Automatically submit form when enter is pressed */

function submit_form(e) {
  var enterPressed = false;
  if(e) { // Firefox
    enterPressed = e.keyCode && e.keyCode==13;
  } else if (event) {  // IE
//    enterPressed = event.keyCode && event.keyCode==13;
// IE will submit form automatically
  }

  if (enterPressed) {
    geocode();
  }
}

/*---------------------------------------------------------------------------*/
/* Collate Information for the Print Window */

function openPrintWindow() {
	
	var overlays = null;
	if (PolyTile.activeLayer != null) {
		overlays = [["http://www.doctorconnect.gov.au/internet/otd/publishing.nsf/AttachmentsByTitle/" + PolyTile.activeLayer.id + "-Legend.gif/$FILE/" + PolyTile.activeLayer.id + "-Legend.gif",0,0,100]];
	}
	
	if (infoLayer == PolyTile.activeLayer && infoPoint != null) {
		 map.closeInfoWindow();
		 map.setCenter(new GLatLng(infoPoint.y, infoPoint.x), map.getZoom());
	}
	
	PolyTile.openPrintWindow(
			[640,500],
			overlays,
			infoLayer == PolyTile.activeLayer ? infoPoint : null, 
			PolyTile.activeLayer != null && infoArgs != null && infoLayer == PolyTile.activeLayer ? 
					PolyTile.activeLayer.infoWindowHTML(infoArgs, true) : null);
}

/*---------------------------------------------------------------------------*/
/* CREATE GOOGLE MAP */
if (GBrowserIsCompatible()) {

  var container = document.getElementById("map");
  map = new GMap2(container);
  PolyTile.setContext(map, lotusNotesDatabase, busySymbol, targetSymbol, corporateLogo, siteLogo, outerMetropolitan, "opacity", "au");

  map.addControl(new SearchControl());

  var button = document.getElementById("searchButton");
  var input = document.getElementById("textInput");
  input.onkeydown = submit_form;
  button.onclick = geocode;
  
  geocoder = new GClientGeocoder();
  geocoder.setBaseCountryCode("au");

  map.addControl(new GLargeMapControl());
  var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(75,7));
  map.addControl(new GMapTypeControl(), topLeft);
  map.addControl(new GScaleControl());
  map.enableContinuousZoom();
  map.enableScrollWheelZoom();
  
  var layerId = null;
  var x = null;
  var y = null;
  var z = null;
  
  var i = location.href.indexOf("#");
  if (i > 0) {
	  var s = location.href.substring(i+1);
	  var args = s.split("&");
	  layerId = args[0];
	  if (args.length > 1) {

		  for (var j=1; j<args.length; j++) {
			  if (args[j].indexOf("x=")==0) {
				  x = args[j].substring(2);
			  } else if (args[j].indexOf("y=")==0) {
				  y = args[j].substring(2);
			  }  else if (args[j].indexOf("z=")==0) {
				  z = args[j].substring(2);
			  } 
		  }
	  }
  }
  
  var selectedLayer = null;  
  if (layerId == null) {
	  selectedLayer = raLayer;
  } else if (layerId.toLowerCase() == "metro") {
	  selectedLayer = metroLayer;
  } else if (layerId.toLowerCase() == "dws") {
	  selectedLayer = DWSLayer;
  } else {
	  selectedLayer = raLayer;
  }
  
  var mapCentre = null;
  if (x != null && y != null && z != null) {
	  mapCentre = new GLatLng(parseFloat(y), parseFloat(x));
	  map.setCenter(mapCentre, parseInt(z));
  } else {
	  map.setCenter(new GLatLng(-27.5,134), 4);
  }
  var ov = new GOverviewMapControl();
  map.addControl(ov);
    
  map.addOverlay(selectedLayer.overlay);
  PolyTile.activeLayer = selectedLayer;
  PolyTile.selectOpacity(selectedLayer.opacity);
  
  GEvent.addListener(map, "click", reverseGeocode);
  
  for (var i=0; i<PolyTile.getNumberOfLayers(); i++) {
	 var layer = PolyTile.getLayer(i);
     layer.linkCheckBox(layer.id == 'DWS' ? 'dwsClickWrap' : null);
  }
  
  selectedLayer.enableClickWrap();
  
  map.addControl(new LegendControl());
}
/*---------------------------------------------------------------------------*/

 
