//if(!window.onload)
//  window.onload = init;
window.onresize = adjustWindowSize;
var _Umap;
var UpositionType;
var _Utabpane;
var Utarget;
var UexValues = ['範例：台北縣板橋市文化路一段266號', '範例：仁愛路二段', '範例：忠孝東路 基隆路', '範例：總統府'];
var Ustart;
var Uend;
var UroutingDisabled;
var UbusStationIcon;
var UbusSolutionNum;
var UbusStations = new Array();
var UroutePath;
var UcontextMenuLatLng;

function init() {
  // initialize map //
  _Umap = new UMap(U.gi('mapDiv'));
  _Umap.addControl(U_TYPE_CONTROL);
  _Umap.addControl(U_FULLZOOM_CONTROL);
  //_Umap.centerAndZoom(new ULatLng(25.035405, 121.530255), 9);
  _Umap.addListener('click', mapMarkerClick);
  _Umap.gotoCookieLocation();
  // initialize basic tab //
  //_Utabpane = new TabPane(U.gi('tabDiv'), '#88f', null, 'url(/img/toolbar_bg.jpg)');
  _Utabpane = new TabPane(U.gi('tabDiv'), '#88f', '#D6F0FB', 'url(./imgs/up_toolbar.gif)');
  _Utabpane.addTab('list', '查詢結果', 'listDiv_All');
  _Utabpane.addTab('routing', '交通導航', 'routingDiv');
  _Utabpane.selectTab('list');
  // initialize special marker //
  var icon = new UIcon();
  icon.image = '/img/redpoint.gif';
  icon.iconWidth = 16;
  icon.iconHeight = 16;
  icon.iconAnchor = new UPoint(8, 8);
  icon.infoWindowAnchor = new UPoint(8, 0);
  Utarget = new UMarker(new ULatLng(0, 0), icon, null, null, 99);
  _Umap.addOverlay(Utarget);
  var icon = new UIcon();
  icon.image = '/img/s.gif';
  icon.iconWidth = 26;
  icon.iconHeight = 30;
  icon.iconAnchor = new UPoint(13, 30);
  icon.infoWindowAnchor = new UPoint(13, 0);
  Ustart = new UMarker(new ULatLng(0, 0), icon, null, null, 100);
  _Umap.addOverlay(Ustart);
  icon = new UIcon(icon);
  icon.image = '/img/e.gif';
  Uend = new UMarker(new ULatLng(0, 0), icon, null, null, 100);
  _Umap.addOverlay(Uend);
  UbusStationIcon = new UIcon();
  UbusStationIcon.image = '/img/busStation.gif';
  UbusStationIcon.iconWidth = 16;
  UbusStationIcon.iconHeight = 30;
  UbusStationIcon.iconAnchor = new UPoint(8, 30);
  UbusStationIcon.infoWindowAnchor = new UPoint(8, 0);
  // custom initialize process //
  if(customInit)
    customInit();
  // others //
  resetExample();
  adjustWindowSize();
  // initialize event //
  U.gi('queryText').onfocus = queryTextFocused;
  U.gi('queryText').onblur = resetExample;
  for(var i=0; i<U.gn('queryType').length; i++)
    U.gn('queryType')[i].onclick = resetExample;
  U.gi('queryBtn').onclick = smartQuery;
  U.gi('queryForm').onsubmit = smartQuery;
  //U.gi('printMapLink').style.display = 'none';
  //U.gi('returnToSaveLink').style.display = 'none';
  if(U.gi('printMapLink'))
    U.gi('printMapLink').onclick = printMap;
  if(U.gi('linkMapLink'))
    U.gi('linkMapLink').onclick = linkMap;
  if(U.gi('emailMapLink'))
    U.gi('emailMapLink').onclick = emailMap;
  if(U.gi('returnToSaveLink'))
  	U.gi('returnToSaveLink').onclick = returnToSave;
  if(U.gi('viewStartLink'))
  	U.gi('viewStartLink').onclick = viewStart;
  if(U.gi('viewEndLink'))
  	U.gi('viewEndLink').onclick = viewEnd;
  if(U.gi('startRoutingLink'))
  	U.gi('startRoutingLink').onclick = startRouting;
  if(U.gi('switchSELink'))
  	U.gi('switchSELink').onclick = switchStartEnd;
  if(U.gi('resetRoutingLink'))
  	U.gi('resetRoutingLink').onclick = resetRoutingSetting;
  U.addEvent(U.gi('mapDiv'), 'contextmenu', showContextMenu);
  U.gi('setStartMenuItem').onclick = function(ev) {
    U.cancelDefault(ev);
    _setRoutingStartLocation(UcontextMenuLatLng, '圖面自訂點');
  };
  U.gi('setEndMenuItem').onclick = function(ev) {
    U.cancelDefault(ev);
    _setRoutingEndLocation(UcontextMenuLatLng, '圖面自訂點');
  };
  if(U.gi('closeMenuItem'))
  	U.gi('closeMenuItem').onclick = hideContextMenu;
  if(U.gi('measureLink'))
    U.gi('measureLink').onclick = function() {_Umap.setMapAction(U_MEASURE_ACTION);UCounter.addCount('花旗銀行_function_測量距離');};
  DWRUtil.useLoadingMessage();
}
function resetExample() {
  var text = U.gi('queryText').value;
  var setEx = text==''?true:false;
  for(var i=0; i<UexValues.length; i++)
    if(text==UexValues[i])
      setEx = true;
  if(setEx) {
    U.gi('queryText').className = 'gray';
    for(i=0; i<U.gn('queryType').length; i++)
      if(U.gn('queryType')[i].checked)
        U.gi('queryText').value = UexValues[i];
  }
}
function queryTextFocused() {
  var text = U.gi('queryText').value;
  var isEx = false;
  for(var i=0; i<UexValues.length; i++)
    if(text==UexValues[i])
      isEx = true;
  if(isEx) {
    U.gi('queryText').value='';
    U.gi('queryText').className='black';
  }
}
function adjustWindowSize() {
  var dim = U.getWindowSize();
  var h = (dim[1]-U.gi('headerDiv').offsetHeight-U.gi('toolbarDiv').offsetHeight-U.gi('footerDiv').offsetHeight-4); /* 要扣掉 body 的 margin 2*2 */
  U.gi('centerDiv').style.height = h+'px';
  U.gi('mapDiv').style.height = h+'px';
  U.gi('infoDiv').style.height = h+'px';
  var adDivHeight = U.gi('adDiv')?U.gi('adDiv').offsetHeight:0;
  U.gi('tabDiv').style.height = (h-4-adDivHeight)+'px'; /* 要扣掉 infoDiv 的 padding 2*2 */
  U.gi('mapDiv').style.marginRight = U.gi('infoDiv').offsetWidth+'px';
  _Utabpane.fitContainerSize();
  _Umap.checkResize();
}

/* this is a seperate line =================================================================== */
function smartQuery() {
  var queryString = document.getElementById('queryText').value.replace(/^[\s]+/g,'').replace(/[\s]+$/g,'');
  for(var i=0; i<UexValues.length; i++)
    if(queryString==UexValues[i])
      return false;
  if(queryString.length==0)
    return false;
  var coords = queryString.split(',');
  if(coords.length==2 && !isNaN(coords[0]) && !isNaN(coords[1])) {
    setMapTarget(new ULatLng(parseFloat(coords[1]), parseFloat(coords[0])), '目標點', '經度:'+coords[0]+'<br>緯度:'+coords[1], 0);
    return false;
  }
  var qtype;
  for(var i=0; i<U.gn('queryType').length; i++) {
    if(U.gn('queryType')[i].checked) {
      qtype = U.gn('queryType')[i].value
      break;
    }
  }
  SearchBean.search(queryString, qtype, smartQueryCallback);
  return false;
}

function smartQueryCallback(result) {
  //清除 使用者查詢條件
  clearAllAdss();
  if(result.length==0) {
    alert('很抱歉我們查不到您所輸入的地點');
    return;
  }
  var locations = result.split(';');
  if(locations.length==1) {
    var data = locations[0].split(',');
    var positionType = (data[3]!='1' || data[7]=='準確' || data[7]=='模糊')?1:2;
    setMapTarget(new ULatLng(parseFloat(data[5]), parseFloat(data[4]), U_TM2_COORDSYS), data[1], data[2], positionType);
  } else {
    var dataTypes = ['', '地址', '道路', '交叉路口', '縣市', '鄉鎮市區', '村里', '基礎地標','','','TaipeiWalker','網路消費協會認證業者','地標'];
    var resultList = new Object();
    for(var i=0; i<dataTypes.length; i++) {
      resultList[dataTypes[i]] = new Object();
      resultList[dataTypes[i]].count = 0;
    }
    for(var i=0; i<locations.length; i++) {
      var data = locations[i].split(',');
      if(data.length!=8)
        continue;
      if(!resultList[dataTypes[parseInt(data[3])]][data[0]])
        resultList[dataTypes[parseInt(data[3])]][data[0]] = new Array();
      resultList[dataTypes[parseInt(data[3])]][data[0]].push(data[1]+';'+data[5]+';'+data[4]);
      resultList[dataTypes[parseInt(data[3])]].count++;
    }
    U.gi('listDiv').innerHTML = '';
    var resultTree = new treelist(U.gi('listDiv'), searchResultClick, false);
    var pickOne = false;
    for(var i=0; i<dataTypes.length; i++) {
      if(resultList[dataTypes[i]].count==0)
        continue;
      var typeNode = new treenode(dataTypes[i]+'('+resultList[dataTypes[i]].count+')', resultTree, false);
      for(city in resultList[dataTypes[i]]) {
        if(city=='count')
          continue;
        var results = resultList[dataTypes[i]][city];
        var cityNode = new treenode(city+'('+results.length+')', typeNode, false);
        for(var j=0; j<results.length; j++) {
          new treenode(results[j].split(';')[0], cityNode, false, results[j]);
          if(!pickOne) {
            var data = results[j].split(';');
            setMapTarget(new ULatLng(parseFloat(data[1]), parseFloat(data[2]), U_TM2_COORDSYS), data[0], null, 3);
            pickOne = true;
          }
        }
      }
    }
    _Utabpane.selectTab('list');
    U.blinkElement(U.gi('listDiv'), '#fbb');
  }
}

function setMapTarget(latlng, label, desc, positionType) {
  UpositionType = positionType;
  switch(positionType) {
    case 1:
      Utarget.setMouseonInfo(label);
      break;
    case 2:
      Utarget.setMouseonInfo(desc);
      break;
    default:
      Utarget.setMouseonInfo(label, desc);
  }
  Utarget.setPoint(latlng);
  _Umap.centerMap(latlng);
  Utarget.label = label;
  Utarget.desc = desc;
  mapMarkerClick(Utarget);
}

function mapMarkerClick(overlay, latlng, isRightBtn) {
  UadSearchByAddr = false;
  if(overlay==Utarget) {
    var html;
    switch(UpositionType) {
      case 0:
        html = '我所在的位置是：<br>經度 '+Utarget.getPoint().lng()+'<br>緯度 '+Utarget.getPoint().lat();
        break;
      case 1:
        html = '我所在的位置是：<br><b>'+Utarget.label+'</b>';
        break;
      case 2:
        html = '很抱歉，本系統無此地址資料：<br>'+Utarget.label+'<br><br>目前所在位置是：<br><b style="color:blue;">'+Utarget.desc+'</b>';
        break;
      case 3:
        html = '我所在的位置是：<br><b style="color:blue;">'+Utarget.label+'</b><p>如果這不是你要找的地點，其他的相關地點都列在右邊的搜尋結果中</p>';
        break;
    }
    if(!UroutingDisabled)
      html += '<p><a href="javascript:void(0);" id="setStartLink">設為起點</a> | <a href="javascript:void(0);" id="setEndLink">設為終點</a>';
	//加上 查詢附近店家 的查詢功能
	html += " | <a href='javascript:void(0);' onclick='javascript:{adSearchInAddr(null,null);};'>附近店家</a></p>";
	
    Utarget.openInfoWindow(html);
    if(!UroutingDisabled) {
      U.gi('setStartLink').onclick = function() {_setRoutingStartLocation(overlay.getPoint(), overlay.label);};
      U.gi('setEndLink').onclick = function() {_setRoutingEndLocation(overlay.getPoint(), overlay.label);};
    }
  } else if(overlay==Ustart || overlay==Uend) {
    var desc = overlay==Ustart?'導航起點':'導航終點';
    overlay.openInfoWindow(desc+'<br><b style="color:blue;">'+overlay.label+'</b><p><a href="javascript:void(0);" id="removeRoutingNodeLink">移除這個點</a> | <a href="javascript:void(0);" id="switchStartEndLink">起終點對調</a></p>');
    U.gi('removeRoutingNodeLink').onclick = function() {removeRoutingNode(overlay);};
    U.gi('switchStartEndLink').onclick = switchStartEnd;
  }
}

function searchResultClick(node) {
  var data = node.data.split(';');
  setMapTarget(new ULatLng(parseFloat(data[1]), parseFloat(data[2]), U_TM2_COORDSYS), data[0], null, 3);
  node.select(true);
}

function returnToSave() {
  if(Utarget.getPoint().lat()!=0) {
    _Umap.centerMap(Utarget.getPoint());
    mapMarkerClick(Utarget);
  }
}

/* additional map function */
function printMap() {
  U.gi('infoDiv').style.display = 'none';
  adjustWindowSize();
  window.print();
  U.gi('infoDiv').style.display = 'block';
  adjustWindowSize();
  _Umap.refreshMap();
}

function generateMapLinkString() {
  var mode = _Umap.getCurrentMapType()==U_MAP_TYPE?0:(_Umap.getCurrentMapType()==U_SATELLITE_TYPE?1:2);
  var str = _Umap.getCenter().lng()+';'+_Umap.getCenter().lat()+';'+_Umap.getZoomLevel()+';'+mode+';twd97'+'@';
  if(Utarget.getPoint().lat()!=0)
    str += Utarget.label+';'+Utarget.desc+';'+Utarget.getPoint().lng()+';'+Utarget.getPoint().lat()+';twd97';
  str += '@';
  if(Uads.length > 0) {
	  //Key Value
	  str += U.gi('KeyWord').value;
	  //SelectedNode
	  if(SelectedNode)
		str += ';'+UadCategory;
	  else 
		str += ';null';
	  //UadSearchByAddr = true ==>按下周遭店家時
	  str += ';'+UadSearchByAddr+';twd97';
  }
  str += '@';
  return str;
}

function linkMap(ev) {
  var str = generateMapLinkString();
  DWREngine.setAsync(false);
  SearchBean.encode(str, linkMapCallback);
  DWREngine.setAsync(true);
}

function emailMap(ev) {
  var str = generateMapLinkString();
  DWREngine.setAsync(false);
  SearchBean.encode(str, emailMapCallback);
  DWREngine.setAsync(true);
}

function linkMapCallback(enc) {
  DWREngine.setAsync(true);
  enc = encodeURI(enc);	//再encode一次，避免轉串來的碼被瀏覽器編過，造成錯誤
  //alert(enc);
  //var url = 'http://www.urmap.com/?link='+enc;
  var url = citiBankUrlLink + 'index.jsp?link='+enc;
  //var html = '連結網址：<input type="button" value="全選" style="font-size:12px;" onclick="document.getElementById(\'urlTA\').select();"><br><textarea id="urlTA" rows="5" cols="33" style="font-size:13px;">'+url+'</textarea><br><br>HTML連結語法：<input type="button" value="全選" style="font-size:12px;" onclick="document.getElementById(\'htmlTA\').select();"><br><textarea id="htmlTA" rows="7" cols="33" style="font-size:13px;"><a target="_blank" href="'+url+'">地圖連結</a></textarea><br><br>我要試試看：<a target="_blank" href="'+url+'">地圖連結</a><p style="color:red;">PS.導航結果目前暫時無法提供網頁連結</p>';
  var config = 'height=400,width=350,scrollbars=yes,resizable=yes';
  var win_open = 'LinkMap.jsp?url='+url;//+'&html='+html;
  window.open(win_open, 'win_open', config);
  //U.gi('detailDiv').innerHTML = html;
  //_Utabpane.selectTab('detail');
  //U.blinkElement(U.gi('detailDiv'), '#fbb');
}

function emailMapCallback(enc) {
  DWREngine.setAsync(true);
  var url = 'http://localhost/?link='+enc;
  location.href = 'mailto:?subject=UrMap&body='+escape(url);
}

function _decodeMap(enc) {
  SearchBean.decode(enc, decodeMapCallback);
}

function decodeMapCallback(result) {
  //alert(result);
  if(result) {
	  var data = result.split('@');
	  var latlng;
	  if(data[1].length>0) {
		var targetdata = data[1].split(';');
		if(targetdata.length==4) /* old 67 link */
		  latlng = new ULatLng(parseFloat(targetdata[3])-200, parseFloat(targetdata[2])+826, U_TM2_COORDSYS);
		else {
		  latlng = new ULatLng(parseFloat(targetdata[3]), parseFloat(targetdata[2]));
		}
		setMapTarget(latlng, targetdata[0], targetdata[1], 1);
	  }
	  var xyz = data[0].split(';');
	  if(xyz.length==4)
		latlng = new ULatLng(parseFloat(xyz[1])-200, parseFloat(xyz[0])+826, U_TM2_COORDSYS);
	  else
		latlng = new ULatLng(parseFloat(xyz[1]), parseFloat(xyz[0]));
	  _Umap.centerAndZoom(latlng, parseInt(xyz[2]));
	  var mode = xyz[3]=='0'?U_MAP_TYPE:(xyz[3]=='1'?U_SATELLITE_TYPE:U_HYBRID_TYPE);
	  _Umap.setMapType(mode);
	  
	  //先定位，在Search
	  if(data[2].length>0) {
		var _searMsg = data[2];
		var data2 = _searMsg.split(';');
		var _key = data2[0];
		var _selectedNodeValue = data2[1];
		var _searchByAll = data2[2];
		if('true'==_searchByAll) {	//周邊店家
			adSearchInAddr();
		}
		else {
			U.gi('KeyWord').value = _key;
			var nodeValue = ('null'==_selectedNodeValue)?null:_selectedNodeValue;
			adSearch('citi',nodeValue);
		}
	  }
  } else {
  	_Umap.centerAndZoom(new ULatLng(25.04, 121.55), 9);
  }
}

function showContextMenu(ev) {
  if(UroutingDisabled)
    return;
  U.cancelDefault(ev);
  var menu = U.gi('contextMenu');
  menu.style.display = 'block';
  menu.style.left = (ev.clientX+2)+'px';;
  menu.style.top = ev.clientY+'px';
  UcontextMenuLatLng = _Umap.transformContainerCoordinatesToLatLng(new UPoint(ev.clientX-U.findPosX(U.gi('mapDiv')), ev.clientY-U.findPosY(U.gi('mapDiv'))));
}

function hideContextMenu(ev) {
  U.cancelDefault(ev);
  U.gi('contextMenu').style.display = 'none';
}

/* routing related function */
function removeRoutingNode(node) {
  setRoutingNode(new ULatLng(0, 0), '', node);
  _Umap.closeInfoWindow();
}

function setRoutingNode(latlng, label, node) {
  var desc = node==Ustart?'導航起點':'導航終點';
  node.setPoint(latlng);
  node.setMouseonInfo(label, desc);
  node.label = label;
  if(node==Ustart) {
    U.gi('viewStartLink').innerHTML = label;
    U.blinkElement(U.gi('viewStartLink').parentNode, '#fbb');
  } else {
    U.gi('viewEndLink').innerHTML = label;
    U.blinkElement(U.gi('viewEndLink').parentNode, '#fbb');
  }
  _Utabpane.selectTab('routing');
}

function viewStart() {
  if(Ustart.getPoint().lat()!=0)
    _Umap.centerAndZoom(Ustart.getPoint(), 9);
}

function viewEnd() {
  if(Uend.getPoint().lat()!=0)
    _Umap.centerAndZoom(Uend.getPoint(), 9);
}

function switchStartEnd() {
  var point = new ULatLng(Ustart.getPoint().lat(), Ustart.getPoint().lng());
  var label = Ustart.label;
  setRoutingNode(Uend.getPoint(), Uend.label, Ustart);
  setRoutingNode(point, label, Uend);
  _Umap.closeInfoWindow();
}

function resetRoutingSetting() {
  removeRoutingNode(Ustart);
  removeRoutingNode(Uend);
  while(UbusStations.length>0)
    _Umap.removeOverlay(UbusStations.pop());
  UbusSolutionNum = null;
  U.gi('routingResultDiv').style.display = 'none';
  if(UroutePath)
    _Umap.removeOverlay(UroutePath);
}

function startRouting() {
  if(Ustart.getPoint().lat()==0 || Uend.getPoint().lat()==0) {
    alert('請先設定好起終點!');
    return;
  }
  //導航功能的使用率
  UCounter.addCount('ASP花旗特約店_function_導航');
  UviewAd = true;
  if(U.gi('carRouting').checked==true)
    SearchBean.getRoute(Math.round(Ustart.getPoint().x()), Math.round(Ustart.getPoint().y()), Math.round(Uend.getPoint().x()), Math.round(Uend.getPoint().y()), startCarRoutingCallback);
  else if(U.gi('busRouting').checked==true)
    SearchBean.getPTRouting(Math.round(Ustart.getPoint().x()), Math.round(Ustart.getPoint().y()), Math.round(Uend.getPoint().x()), Math.round(Uend.getPoint().y()),  startBusRoutingCallback);
}

function startCarRoutingCallback(result) {
  if(result=='' || result.split(':').length!=4) {
    alert('很抱歉，你輸入的起迄點資料無法規劃出適當路徑，請變更起迄點位置以後再試一次。');
    return;
  }
  UviewAd = true;	//避免  mapChange 造成查詢效果
  var distance = parseFloat(result.split(':')[1]);
  var pts = result.split(':')[2].split(';');
  var pathXY = result.split(':')[3].split(',');
  var html = '<table cellspacing="0"><tr><td class="num">全長</td><td class="value">'+distance+' 公尺</td></tr>';
  var box = new UBounds();
  for(var i=0; i<pts.length; i++) {
    var nxy = pts[i].split(',');
    html+='<tr><td class="num">'+(i+1)+'</td><td class="value"><a href="javascript:void(0);" xcoor="'+nxy[1]+'" ycoor="'+nxy[2]+'">&nbsp;'+nxy[0]+'</a></td></tr>';
    box.extend(new ULatLng(parseFloat(nxy[2]), parseFloat(nxy[1]), U_TM2_COORDSYS));
  }
  html+='</table>';
  box.extend(Ustart.getPoint());
  box.extend(Uend.getPoint());
  U.gi('routingResultDiv').innerHTML = html;
  U.gi('routingResultDiv').style.display = 'block';
  var links = U.gt(U.gi('routingResultDiv'), 'a');
  for(var i=0; i<links.length; i++)
    links[i].onclick = routingVertexLinkClick;
  var viewFullRouteLink = document.createElement('a');
  viewFullRouteLink.href = 'javascript:void(0);';
  viewFullRouteLink.innerHTML = '觀看全程路線地圖';
  viewFullRouteLink.onclick = function() {
    _Umap.centerAndZoom(box.getCenter(), _Umap.getBoundsZoomLevel(box));
  };
  U.gi('routingResultDiv').insertBefore(viewFullRouteLink, U.gi('routingResultDiv').firstChild);
  _Umap.centerAndZoom(box.getCenter(), _Umap.getBoundsZoomLevel(box));
  if(UroutePath)
    _Umap.removeOverlay(UroutePath);
  var path = new Array();
  for(var i=0; i<pathXY.length/2; i++)
    path.push(new ULatLng(parseFloat(pathXY[2*i+1]), parseFloat(pathXY[2*i]), U_TM2_COORDSYS));
  UroutePath = new UPolyline(path);
  _Umap.addOverlay(UroutePath);
}

function routingVertexLinkClick(ev) {
  UviewAd = true;	//避免  mapChange 造成查詢效果
  var vertex = U.findTarget(ev, 'a');
  if(vertex.getAttribute('xcoor'))
    _Umap.centerAndZoom(new ULatLng(parseFloat(vertex.getAttribute('ycoor')), parseFloat(vertex.getAttribute('xcoor')), U_TM2_COORDSYS), 9);
}

function startBusRoutingCallback(result) {
  U.gi('routingResultDiv').innerHTML = result;
  U.gi('routingResultDiv').style.display = 'block';
  
  //U.gi('routingResultDiv').style.height = getRoutingDivSize() + 'px';	//長
  U.gi('routingResultDiv').style.width = (U.gi('routingResultDiv').offsetWidth-15) + 'px';	//寬
  
  var links = U.gt(U.gi('routingResultDiv'), 'a');
  for(var i=0; i<links.length; i++)
    links[i].onclick = busStationLinkClick;
  var solutions = U.gt(U.gi('routingResultDiv'), 'td');
  for(var i=0; i<solutions.length; i++) {
    solutions[i].solutionNum = i;
    var viewSolutionLink = document.createElement('a');
    viewSolutionLink.href = 'javascript:void(0);';
    viewSolutionLink.style.paddingLeft = '10px';
    viewSolutionLink.innerHTML = '觀看此方案所有站牌位置';
    viewSolutionLink.onclick = busSolutionLinkClick;
    solutions[i].appendChild(viewSolutionLink);
  }
  UbusSolutionNum = null;
  UviewAd = true;	//避免  mapChange 造成查詢效果
}

function getRoutingDivSize() {
  //var dim = U.getWindowSize();
  //var h = (dim[1]-U.gi('headerDiv').offsetHeight-U.gi('toolbarDiv').offsetHeight-U.gi('footerDiv').offsetHeight-4); /* 要扣掉 body 的 margin 2*2 */
  //alert('h:' + h);
  var routingResult_H;
  //alert('centerDiv==>' + U.gi('centerDiv').offsetWidth + 'px');
  //alert('mapDiv==>' + U.gi('mapDiv').offsetWidth + 'px');
  /*alert('tabDiv==>' + U.gi('tabDiv').offsetWidth + 'px');
  alert('tabDiv==>' + U.gi('tabDiv').offsetHeight + 'px');
  alert('routingDiv==>' + U.gi('routingDiv').offsetHeight + 'px');
  alert('routingDiv_All2==>' + U.gi('routingDiv_All2').offsetHeight + 'px');
  alert('routingResultDiv==>' + U.gi('routingResultDiv').offsetHeight + 'px');
  */
  routingResult_H = U.gi('routingDiv').offsetHeight - U.gi('routingDiv_All2').offsetHeight - 100;
  //if()
  	
  //alert(routingResult_H);
  return routingResult_H;
}

function setBusStations(solutionNum) {
  if(UbusSolutionNum==solutionNum)
    return;
  UbusSolutionNum = solutionNum;
  while(UbusStations.length>0)
    _Umap.removeOverlay(UbusStations.pop());
  var stLinks = U.gt(U.gt(U.gi('routingResultDiv'), 'td')[solutionNum], 'a');
  for(var i=0; i<stLinks.length; i++) {
    if(stLinks[i].getAttribute('xcoor')) {
      var station = new UMarker(new ULatLng(parseFloat(stLinks[i].getAttribute('ycoor')), parseFloat(stLinks[i].getAttribute('xcoor')), U_TM2_COORDSYS), UbusStationIcon, stLinks[i].innerHTML, null, 98);
      UbusStations.push(station);
      _Umap.addOverlay(station);
    }
  }
}

function busStationLinkClick(ev) {
  UviewAd = true;
  var station = U.findTarget(ev, 'a');
  if(station.getAttribute('xcoor')) {
    setBusStations(station.parentNode.solutionNum);
    _Umap.centerAndZoom(new ULatLng(parseFloat(station.getAttribute('ycoor')), parseFloat(station.getAttribute('xcoor')), U_TM2_COORDSYS), 9);
  }
}

function busSolutionLinkClick(ev) {
  UviewAd = true;
  var solution = U.findTarget(ev, 'td');
  setBusStations(solution.solutionNum);
  var box = new UBounds();
  for(var i=0; i<UbusStations.length; i++)
    box.extend(UbusStations[i].getPoint());
  box.extend(Ustart.getPoint());
  box.extend(Uend.getPoint());
  _Umap.centerAndZoom(box.getCenter(), _Umap.getBoundsZoomLevel(box));
}

function _setRoutingStartLocation(latlng, label) {
  UviewAd = true;
  setRoutingNode(latlng, label, Ustart);
  _Umap.closeInfoWindow();
  hideContextMenu();
}

function _setRoutingEndLocation(latlng, label) {
  UviewAd = true;
  setRoutingNode(latlng, label, Uend);
  _Umap.closeInfoWindow();
  hideContextMenu();
}

function _disableRoutingFunction() {
  _Utabpane.hideTab('routing');
  UroutingDisabled = true;
}
