
//check the validation of input data
function getTai(){

var inputRe = /[A-HJ-Z]\d{4}[A-H][A-E]\d{2,4}/;
var taiSource = document.getElementById('xySource').value;
taiSource = taiSource.toUpperCase();
var digiChk = taiSource.length;
var formatChk = taiSource.search(inputRe);
if ((digiChk != 9 && digiChk != 11) || formatChk ==- 1){
  alert ("座標格式錯誤，請重新檢查後再輸入一次!　");
  return;
}

var Chr0 = getFirstChr();

if ( Chr0 == "Z" || Chr0 =="S"){
  alert ("很抱歉，本轉換式目前不適用於金門及馬祖地區!　");
  return;
}

return taiSource;

}

//Taipower coordinates system convert
function convertTai(){

var taiGrid = getTai();
//set the xy original coordinates by divisions
var divStr = "A B C D E F G H J K L M N O P Q R T U V W X Y Z";
divStr = divStr.replace(/ /g,"");

var idxOne = divStr.indexOf(taiGrid.charAt(0));
var idx3x = divStr.indexOf(taiGrid.charAt(5));
var idx3y = divStr.indexOf(taiGrid.charAt(6));

var xArray = "170000 250000 330000 170000 250000 330000 170000 250000 90000 170000 250000 90000 170000 250000 90000 170000 250000 170000 250000 170000 250000 275000 275000 552700";
var yArray = "2750000 2750000 2750000 2700000 2700000 2700000 2650000 2650000 2600000 2600000 2600000 2550000 2550000 2550000 2500000 2500000 2500000 2450000 2450000 2400000 2400000 2614000 2564000 2675800";
var zArray = "0 1 2 3 4 5 6 7";

xArray = xArray.split(" ");
yArray = yArray.split(" ");
zArray = zArray.split(" ");

//convert the Taipower grid to t6767/tm2
var n1x = eval(xArray[idxOne]);
var n1y = eval(yArray[idxOne]);

var n2x = eval(taiGrid.substr(1,2))*800;
var n2y = eval(taiGrid.substr(3,2))*500;

var n3x = eval(zArray[idx3x])*100;
var n3y = eval(zArray[idx3y])*100;

var chr9 = taiGrid.charAt(9);
chr9 = chr9.replace("","0");
var chr10 = taiGrid.charAt(10);
chr10 = chr10.replace("","0");

var n5x = eval(taiGrid.charAt(7))*10 + eval(chr9);
var n5y = eval(taiGrid.charAt(8))*10 + eval(chr10);

var xT67TM2 = n1x + n2x + n3x + n5x;
var yT67TM2 = n1y + n2y + n3y + n5y;

var xyT67TM2 = xT67TM2 + ", " + yT67TM2;

return xyT67TM2;

}

//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"; //TWD97/WGS84 DMS

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

Proj4js.defs["EPSG:3826"] = "+title=EPSG:3826 +proj=tmerc  +lat_0=0 +lon_0=121 +k=0.9999 +x_0=250000 +y_0=0 +ellps=GRS80 +units=公尺 +no_defs"; // TWD97 TM2 Taiwan

Proj4js.defs["EPSG:3825"] = "+title=EPSG:3825 +proj=tmerc  +lat_0=0 +lon_0=119 +k=0.9999 +x_0=250000 +y_0=0 +ellps=GRS80 +units=公尺 +no_defs"; // TWD97 TM2 Penghu

Proj4js.defs["EPSG:3828"] = "+title=EPSG:3828 +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=公尺";// TWD67 TM2 Taiwan

Proj4js.defs["EPSG:3827"] = "+title=EPSG:3827 +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=公尺"; // TWD67 TM2 Penghu

//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=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"; //Google Mercator

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);   
   
	//revise the label contents
    //var label = (projHash[def].title ? projHash[def].title : '');
	
	//var opt = new Option(label, def);
    //crsSource.options[optIndex]= opt;	
	//var opt = new Option(label, def);
    //crsDest.options[optIndex]= opt;
	
    ++optIndex;
	
  }  // for
  //updateCrs('Source');
  updateCrs('Dest');
}

function updateCrs(id) {
  
  zoneChk();

  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 projChk = crs.value;
	
	if ( projChk == 'TM97TM2' || projChk == 'TM67TM2' ) {
      
	  //check the projection div btw Taiwan/Penghu
      if ( getFirstChr() == 'X' || getFirstChr() == 'Y' ) {
		//decide the Penghu datum 
		if ( projChk == 'TM97TM2') {
          var proj = projHash['EPSG:3825']; //T97TM2,Penghu
		  } else {
          var proj = projHash['EPSG:3827']; //T67TM2,Penghu
		  }
		} else {
		//decide the Taiwan datum 
		if ( projChk == 'TM97TM2') {
          var proj = projHash['EPSG:3826']; //T97TM2,Taiwan
		  } else {
          var proj = projHash['EPSG:3828']; //T67TM2,Taiwan
		  }
		}

	  } else {
		// Not 2-degrees projection
        var proj = projHash[crs.value];
	  }

    var units = document.getElementById('units'+id);
    //units.innerHTML = proj.units;
	//include the css style to hack ie6, ie7
    units.innerHTML = "<div style='width:60'>"+proj.units+"</div>";

	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';	  
	   }
	}
	//Title has revised and equal to EPSG SN
	var projTitle = proj.title;
	projTitle = projTitle.replace(/ /g,"");	
	return projTitle;
  }
}

function transform() {
  
  zoneChk();
  
  //clear the xyDest value when transform porceed
  document.getElementById('xyDest').value = '';	  
  document.getElementById('xyDest2').value = '';	  
  
  //decide the crsSource
  //var crsSource = document.getElementById('crsSource');
  var sourceEPSG = null;
  if ( getFirstChr() == 'X' || getFirstChr() == 'Y' ) {
	sourceEPSG = 'EPSG:3827'; // T67 TM2 Penghu
  } else {
	sourceEPSG = 'EPSG:3828'; // T67 TM2 Taiwan
  }
  var projSource = null;
  if (sourceEPSG) {
    projSource = projHash[sourceEPSG];
  } else {
    alert("請選擇欲轉換之座標參考系統!　");
    return;
  }
  
  //decide the crsDest
  //var crsDest = document.getElementById('crsDest');
  var destEPSG = updateCrs('Dest');  
  var projDest = null;
  
  if (destEPSG) {
    projDest = projHash[destEPSG];
  } else {
    alert("請選擇轉換後之座標參考系統!　");
    return;
  }

  //var pointInput = document.getElementById('xySource');
  var pointInput = convertTai();
    
  if (pointInput) {
    var pointSource = new Proj4js.Point(pointInput);
    var pointDest = Proj4js.transform(projSource, projDest, pointSource);
	
	//check the Dest coordinates
	if ( isNaN(pointDest.x) || isNaN(pointDest.y)) {
      alert("請檢查並重新輸入電力座標!　");
	  return;
	}
	
    if( updateCrs('Dest') == 'WGS84' || updateCrs('Dest') == 'EPSG:3821' ) { 
	  // convert destPoint to 6-digi/longlat or 0-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(0);
	  pointDest.y = (pointDest.y).toFixed(0);
    }

  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 first character of Input
function getFirstChr() {
  var taiGrid = document.getElementById('xySource').value;
  taiGrid = taiGrid.toUpperCase();
  return taiGrid.charAt(0);
}

//zone check by input
function zoneChk() {
  var zone = document.getElementById('zoneSource');
  zone.innerHTML = '';
  if ( getFirstChr() == 'X' || getFirstChr() == 'Y' ) {
      zone.innerHTML = '澎湖區';
	} else {
      zone.innerHTML = '台灣區';
	}
}

//get the output by TWD97(WGS84) to feed google maps API
function googleLoc() {

  //get the input from taipower grid convert
  var pointInputLoc = convertTai();
  //decice the projSource by first input character
  var sourceEPSGloc = null;
  if ( getFirstChr() == 'X' || getFirstChr() == 'Y' ) {
	sourceEPSGloc = 'EPSG:3827'; // T67 TM2 Penghu
  } else {
	sourceEPSGloc = 'EPSG:3828'; // T67 TM2 Taiwan
  } 
  //force the input/output datum to TWD67/TWD97(WGS84)
  var projSourceLoc = projHash[sourceEPSGloc];
  var projDestLoc = projHash['WGS84'];
  if (pointInputLoc) {
    var pointSourceLoc = new Proj4js.Point(pointInputLoc);
    var pointDestLoc = Proj4js.transform(projSourceLoc, projDestLoc, pointSourceLoc);
  }
  
  pointDestLoc.x = (pointDestLoc.x).toFixed(6);
  pointDestLoc.y = (pointDestLoc.y).toFixed(6);
  
  return ( pointDestLoc.x + ',' + pointDestLoc.y );
}

//Google Maps API

var myMap = null;
var myMarker = null;
	
function initialize() {	
  if (GBrowserIsCompatible()) {		
    myMap = new GMap2(document.getElementById("googleMaps"));
	var myLatLng = new GLatLng(25.063810, 121.653744); //上河門市
	//document.getElementById('inLatLng').value = myLatLng.toString();
    myMap.setCenter(myLatLng, 15);
    myMap.setUIToDefault();
	
	myMarker = new GMarker(myLatLng);
	myMap.addOverlay(myMarker);
	
	var sunRiver = "<b>" + "上河文化門市" + "</b>"  + "<br>" + "電話: (02)2647-3053, (02)2647-3143" + "<br>" + "地址：汐止市大同路二段184巷7號1樓"+ "<br>" +"座標：25.063810, 121.653744";
	var sunHtml = "<span style = padding-bottom:8;padding-right:8;line-height:1.5;>" + sunRiver + "</span>";
    myMarker.openInfoWindowHtml(sunHtml);
	
  }
}

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 taiDest = "電力座標：" + "<b>" + getTai() + "</b>" +"<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;>" + taiDest + location + result2 + "</span>";
	  myMarker.openInfoWindowHtml(html);
	  //document.getElementById('address').value = result.address;
	}
  });
}
