
//Visit PROJ.4/Proj4js at http://www.proj4js.org/ for source code

//Proj4js.defs["EPSG:3822"] = "+title=經緯度：TWD97/WGS84 +proj=longlat +ellps=GRS80 +units=度 +no_defs";

Proj4js.defs["EPSG:3821"] = "+title=經緯度：TWD67 +proj=longlat  +towgs84=-752,-358,-179,-.0000011698,.0000018398,.0000009822,.00002329 +ellps=aust_SA +units=度 +no_defs";

Proj4js.defs["EPSG:3826"] = "+title=二度分帶：TWD97 TM2 台灣 +proj=tmerc  +lat_0=0 +lon_0=121 +k=0.9999 +x_0=250000 +y_0=0 +ellps=GRS80 +units=公尺 +no_defs"; 

Proj4js.defs["EPSG:3825"] = "+title=二度分帶：TWD97 TM2 澎湖 +proj=tmerc  +lat_0=0 +lon_0=119 +k=0.9999 +x_0=250000 +y_0=0 +ellps=GRS80 +units=公尺 +no_defs"; 

Proj4js.defs["EPSG:3828"] = "+title=二度分帶：TWD67 TM2 台灣 +proj=tmerc  +towgs84=-752,-358,-179,-.0000011698,.0000018398,.0000009822,.00002329 +lat_0=0 +lon_0=121 +x_0=250000 +y_0=0 +k=0.9999 +ellps=aust_SA  +units=公尺";

Proj4js.defs["EPSG:3827"] = "+title=二度分帶：TWD67 TM2 澎湖 +proj=tmerc  +towgs84=-752,-358,-179,-.0000011698,.0000018398,.0000009822,.00002329 +lat_0=0 +lon_0=119 +x_0=250000 +y_0=0 +k=0.9999 +ellps=aust_SA  +units=公尺";

//Proj4js.defs["EPSG:4326"] = "+title=經緯度：WGS84 long/lat +proj=longlat +ellps=WGS84 +datum=WGS84 +units=度 +no_defs ";

//Google Mercator projection
//Proj4js.defs["EPSG:900913"]= "+title=Google Mercator EPSG:900913 +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=公尺 +nadgrids=@null +no_defs";


var projHash = {};
function initProj4js() {
  var crsSource = document.getElementById('crsSource');
  var crsDest = document.getElementById('crsDest');
  var optIndex = 0;
  for (var def in Proj4js.defs) {
    //create a Proj for each definition
    projHash[def] = new Proj4js.Proj(def);   
    //var label = def+" - "+ (projHash[def].title ? projHash[def].title : '');
	//revise the label contents
    var label = (projHash[def].title ? projHash[def].title : '');
	
	//force to revise the title of def:WGS84
	if (def == 'WGS84') {
	  label = (projHash[def].title ? "經緯度：TWD97/WGS84" : '');
	  //alert (label);
	  }
	
    var opt = new Option(label, def);
    crsSource.options[optIndex]= opt;
    var opt = new Option(label, def);
    crsDest.options[optIndex]= opt;
	//alert (label);
    ++optIndex;
		
  }  // for
  updateCrs('Source');
  updateCrs('Dest');
}
  
function updateCrs(id) {
  var crs = document.getElementById('crs'+id);
		
  if (crs.value) {

	//clear the xyDest value when crs changed
    document.getElementById('xyDest').value = '';	  
    document.getElementById('xyDest2').value = '';	  
  
    var proj = projHash[crs.value];
    //var str = 'projection: ' + proj.projName + ' - datum: ' + proj.datumName;
    //var desc = document.getElementById('desc'+id);
    //desc.innerHTML = str;
    var units = document.getElementById('units'+id);
    units.innerHTML = proj.units;

	//get the dest projName
	if ('crs'+id == 'crsDest') {
	  if (proj.projName == 'longlat') {
      //display the xyDMS
      document.getElementById('xyDMS').style.display = displayOn();	  
	  } else {
      //hidden the xyDMS
      document.getElementById('xyDMS').style.display = 'none';	  
	  }
	  return proj.projName;
	}    
  }
}

function transform() {

  //clear the xyDest value when transform porceed
  document.getElementById('xyDest').value = '';	  
  document.getElementById('xyDest2').value = '';	  
  
  var crsSource = document.getElementById('crsSource');
  var projSource = null;
  if (crsSource.value) {
    projSource = projHash[crsSource.value];
  } else {
    alert("請選擇欲轉換之座標參考系統!　");
    return;
  }
  var crsDest = document.getElementById('crsDest');
  var projDest = null;
  if (crsDest.value) {
    projDest = projHash[crsDest.value];
  } else {
    alert("請選擇轉換後之座標參考系統!　");
    return;
  }
    
  var pointInput = document.getElementById('xySource');
  if (pointInput.value) {
    var pointSource = new Proj4js.Point(pointInput.value);
    var pointDest = Proj4js.transform(projSource, projDest, pointSource);

	//check the Input(not Source) coordinates
	var xyInput = pointInput.value;
    //clear the space, comma & decimal letter
    xyInput = xyInput.replace(" ",'');
	xyInput = xyInput.replace(",",'');
	xyInput = xyInput.replace(".",'');
	xyInput = xyInput.replace(".",'');
	//xyInput = xyInput.replace(/\./gi,'');
	//alert (xyInput);
    
	var inputRe = /^[0-9]+$/;
    if ( xyInput.search(inputRe) == -1) {
      alert("請檢查並重新輸入待轉換座標!　");
	  return;
	}
	//check the Dest coordinates
	if ( isNaN(pointDest.x) || isNaN(pointDest.y)) {
      alert("請檢查並重新輸入待轉換座標!　");
	  return;
	}
	
    if( updateCrs('Dest') == "longlat" ) { 
	  // convert destPoint to 6-digi/longlat or 3-digi/tm2 decimal
	  pointDest.x = (pointDest.x).toFixed(6);
	  pointDest.y = (pointDest.y).toFixed(6);
   
      // convert numeric degrees to deg/min/sec
      var xDMS = convertToDMS(pointDest.x);
      var yDMS = convertToDMS(pointDest.y);	 	 
	  var pointDest2 = xDMS + ", " + yDMS;
      } else  {     // else project
	  pointDest.x = (pointDest.x).toFixed(3);
	  pointDest.y = (pointDest.y).toFixed(3);
    }
  
  document.getElementById('xyDest').value = pointDest.toShortString();
  document.getElementById('xyDest2').value = pointDest2;
  
  } else {
    alert("請輸入欲轉換之原始座標!　");
    return;
  }
}

//style display for firefox & ie
function displayOn() {   
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
    return "table-row";
  } else if (window.ActiveXObject) { // ie
    return "block";
  }
} 

// convert numeric degrees to deg/min/sec
function convertToDMS(d) {  
  var deg = Math.floor(d);
  var minu = Math.floor((d-deg)*60);
  var sec = ((d-deg-minu/60)*3600).toFixed(2);
  // add leading zeros if required
  //if (deg<100) deg = '0' + deg; if (deg<10) deg = '0' + deg;
  if (minu<10) minu = '0' + minu;
  if (sec<10) sec = '0' + sec;
  return deg + 'd' + minu + "'" + sec + '"';
} 

//get the output by TWD97(WGS84) to feed google maps API
function googleLoc() {
  //get the crsSource & pointSource for google
  var crsSourceGoogle = document.getElementById('crsSource');
  var projSourceGoogle = projHash[crsSourceGoogle.value];
  
  var pointInputGoogle = document.getElementById('xySource');
  var pointSourceGoogle = new Proj4js.Point(pointInputGoogle.value);

  //creat a new projection for google geocoding
  var projGoogle = projHash['WGS84'];
  var googleDest = Proj4js.transform(projSourceGoogle, projGoogle, pointSourceGoogle);

  googleDest.x = (googleDest.x).toFixed(6);
  googleDest.y = (googleDest.y).toFixed(6);
	    
  return ( googleDest.x + ',' + googleDest.y );
}

//get the source datum & point to display
function getShow() {
  var crsSourceShow = document.getElementById('crsSource');
  var projSourceShow = projHash[crsSourceShow.value];
  var pointInputShow = document.getElementById('xySource');
  
  var inputCoord = pointInputShow.value;
  //switch x,y (lnglat) to y,x (latlng)
  inputCoord = inputCoord.replace(" ",'');
  var comma = inputCoord.indexOf(',')
  var xShow = inputCoord.substring(0, comma);
  var yShow = inputCoord.substring(comma+1, googleLoc().length+1);
  inputCoord = yShow +', '+ xShow;
  
  var inputDatum = projSourceShow.title;  
  if ( inputDatum == 'WGS84 ') { //注意空白
	inputDatum = '經緯度：TWD97/WGS84';
  } 
  
  return ( '輸入：' + '<b>' + inputCoord + '</b>' + '<br>' + '基準：' + inputDatum );
}

//Google Maps API

var myMap = null;
var myMarker = null;
	
function initialize() {	
  if (GBrowserIsCompatible()) {		
    myMap = new GMap2(document.getElementById("googleMaps"));
	var myLatLng = new GLatLng(23.973875, 120.982025); //虎子山原點
	//document.getElementById('inLatLng').value = myLatLng.toString();
    myMap.setCenter(myLatLng, 15);
    myMap.setUIToDefault();
	
	myMarker = new GMarker(myLatLng);
	myMap.addOverlay(myMarker);
	
	var HuTzuShan = "<b>" + "虎子山 台灣地理中心" + "</b>"  + "<br>" + "位置：台灣南投縣埔里鎮大湳里"+ "<br>" + "高程：578.955公尺，一等三角點" + "<br>" + "座標：23.973875, 120.982025";
	var huHtml = "<span style = padding-bottom:8;padding-right:8;line-height:1.5;>" + HuTzuShan + "</span>";
    myMarker.openInfoWindowHtml(huHtml);
  }
}

function showLocation() {
  window.location.href = '#a03';
  //switch x,y (lnglat) to y,x (latlng)
  var comma = googleLoc().indexOf(',')
  var xLoc = googleLoc().substring(0, comma);
  var yLoc = googleLoc().substring(comma+1, googleLoc().length+1);
    
  var myLatLng = new GLatLng(yLoc, xLoc);
  
  //move & mark the center of myMap
  myMap.panTo(myLatLng);
  myMarker.setLatLng(myLatLng);
    
  //geocoding service by input coordinates
  myGeocoder = new GClientGeocoder();
  myGeocoder.getLocations(myLatLng, function(addresses) {
    if(addresses.Status.code != 200) {
      alert("金拍謝~ 此座標沒有找到對應的地址!　" + myLatLng.toUrlValue());
	} else { 
      var sourceShow = getShow() + "<br>";
      var location = "輸出：" + myLatLng.lat() + ", " +  myLatLng.lng() + "<br>";
	  var result = addresses.Placemark[0];
	  var result2 = "地址：" + result.address + "<br>";
	  var html = "<span style = padding-bottom:8;padding-right:8;line-height:1.5;>" + sourceShow + location + result2 + "</span>";
	  myMarker.openInfoWindowHtml(html);
	  //document.getElementById('address').value = result.address;
	}
  });
}
