function pmsInit() {
  var hotUpdater = alm.getPanel('hotDiv').getUpdateManager();
  //hotUpdater.update({url:'/pms/home.jsp',nocache:true,scripts:true});
  hotUpdater.loadScripts = true;
  alm.getPanel('hotDiv').setUrl('/pms/home.jsp', null, false);
  
}

function showListTab(url) {
  alm.getPanel('listDiv').getUpdateManager().update({url:url, nocache:true});
  alm.getLayout('mainLayout').showPanel('listDiv');
}

var tabCount = 0;
// tabID: ContentPanel的id
// title: ContentPanel的title
// url: 連結的網址, 可以帶參數
function addNewTab(tabID, tabText, url) {
  // 依據tabID決定動作
  var reg = alm.getLayout('mainLayout').getRegion('east');
  var panel = reg.getPanel('detailDiv');
  var detailUpdater = panel.getUpdateManager();
  detailUpdater.loadScripts = true;
  detailUpdater.disableCaching =true;
  detailUpdater.update(url);
  //alm.getPanel('detailDiv').setUrl(url);
  //detailUpdater.update({url:url,nocache: true,scripts: true,text: 'Loading...'});
  reg.showPanel('detailDiv');
  return false;
}

// tabID(optional): ContentPanel的id, 沒有id的話會refresh目前正打開的tab
function refreshTab(tabID) {
  var layout = alm.getLayout('mainLayout');
  var region = layout.getRegion('center');
  var panel;
  if (tabID == null) {
    panel = region.getPanel(tabID);
  }
  else {
    panel = region.getTabs().getActiveTab();
  }
  panel.refresh();
}

/*function refreshHeader() {
  var layout = alm.getLayout('mainLayout');
  var region = layout.getRegion('north');
  var updater = region.getActivePanel().getUpdateManager();
  updater.loadScripts = true;
  updater.update();
}*/

// tabID: ContentPanel的id
function removeTab(tabID) {
  // deprecated
}

function setTabContent(tabID, url, loadScript) {
  var layout = alm.getLayout('mainLayout');
  var callback = {
    success: function(o) {
      //alert(o.responseText);
      var region = layout.getRegion('center');
      var panel = region.getTabs().getTab(tabID);
      panel.setContent(o.responseText, loadScript);
    },
    failure: function(o) {
      //alert('fail...');
    }
  };
  var cObj = YAHOO.util.Connect.asyncRequest('GET', '/pms/test/getPageContent.jsp?url='+encodeURIComponent(url), callback);
}

// title: ContentPanel的title
// url: 連結的網址, 可以帶參數
function openRightBox(title, url) {
  var listUpdater = alm.getPanel('listDiv').getUpdateManager();
  listUpdater.loadScripts = true;
  listUpdater.disableCaching = true;
  listUpdater.update(url);
  alm.getLayout('mainLayout').showPanel('listDiv');
}

function sendForm(formId, target, isNew, title) {
  var formObject = document.getElementById(formId);
  YAHOO.util.Connect.setForm(formObject);
  //alert("target :" + target);
  //alert("formId :" + formId);
  var callback = {
    success: function(o) {
      if (formId == 'loginForm' || formId == 'loginForm2') UCounter.addCount('UrMap首頁_function_會員登入');
      if (formId == 'registerFormId') UCounter.addCount('UrMap首頁_function_加入會員');
      if (target == 'dialog') {
        dialog.getLayout().findPanel('dlg-center').setContent(o.responseText, true);
		//alert(o.responseText);
      }else if(target== 'userDiv'){
	//alert("o.responseText :" + o.responseText);
      	  if(o.responseText.indexOf('錯誤') > 0){
      	  	  alert('輸入資料錯誤，請重新輸入');
      	  }else
      	  	  window.location.reload();
      }else {
        alm.getPanel(target).setContent(o.responseText, true);
        alm.getLayout('mainLayout').getRegion('east').showPanel(target);
      }
    },
    failure: function(o) {
      alert('伺服器錯誤，請稍後再試！');
    }};
    //alert("action : " + formObject.getAttribute('action'));
  var cObj = YAHOO.util.Connect.asyncRequest('POST', formObject.getAttribute('action'), callback);
}

// formId: form的id
// newPageURL: 要導向的頁面(可以傳參數)
// newTitle: 新tab的title
function sendFormAndSwitch(formId, newPageURL, newTitle) {
  var layout = alm.getLayout('mainLayout');
  var formObject = document.getElementById(formId);
  var region = layout.getRegion('center');
  var activateItem = region.getTabs().getActiveTab();
  var updater = activateItem.getUpdateManager();
  updater.loadScripts = true;
  updater.formUpdate(formObject);
  // 完成後導到新頁面, not work yet
  activateItem.setText(newTitle);
  activateItem.setUrl(newPageURL);
  activateItem.refresh();
}

// formId: form的id
// url: 連結的網頁(可以帶參數)
// callbackFn(optional): callback function(至少要帶一個參數o.responseText)
// failMessage(optional): 錯誤訊息
function sendFormAsync(formId, url, callbackFn, failMessage) {
  var formObject = document.getElementById(formId);
  YAHOO.util.Connect.setForm(formObject);
  var returnText;
  var callback = {
    success: function(o) {
      //alert(o.responseText)
      //alert(callback);
      if (typeof(callbackFn) == 'function') {
        callbackFn(o.responseText);
      }
    },
    failure: function(o) {
      if (failMessage==null) alert('伺服器錯誤，請稍後再試！');
      else alert(failMessage);
    }
  };
  var cObj = YAHOO.util.Connect.asyncRequest('POST', url, callback);
}

var dialog;
// title: 對話視窗的標題
// url: 連結的網頁(可以帶參數)
// formId(optional): 要傳送的表單id(未完成)
function showDialog(title, url, config, formId) {
  if (title == '') title='對話視窗';
  var defaultConfig = {modal:false,
                       width:600,
                       height:400,
                       shadow:true,
                       minWidth:300,
                       minHeight:300,
                       center: {
                         autoScroll:true,
                         scripts:true
                       }};
  for (var argName in config) {
    defaultConfig[argName] = config[argName];
  }
  if(!dialog){ // lazy initialize the dialog and only create it once
    dialog = new YAHOO.ext.LayoutDialog("op-dlg", defaultConfig);
  }
  else {
    // resize dialog
    var width = 600, height = 400;
    if (config) {
      if (config['width']) {width = config['width'];}
      if (config['height']) {height = config['height'];}
    }
    dialog.resizeTo(width, height);
  }
  dialog.setTitle(title);
  dialog.addKeyListener(27, dialog.hide, dialog);
  var layout = dialog.getLayout();
  dialog.beginUpdate();
  var cp = new YAHOO.ext.ContentPanel('dlg-center',{fitToFrame:true,scripts:true});
  if (formId == null) {
    if (url != '' && url != null) {
      cp.setUrl(url, null, false);
    }
  }
  else {
    // not implement yet....
    var form = document.getElementById(formId);
    if (form!=null) {
      var updater = cp.getUpdateManager();
    }
  }
  layout.add('center', cp);
  dialog.endUpdate();
  //dialog.center();
  dialog.show();
}

// 關閉對話視窗
function closeDialog() {
  dialog.hide();
}

<!-- 按紐效果的javascript -->
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//顯示ToolTip
//var staticTip = new TipObj('staticTip');
var staticTip;
var tp1 = '<table cellpadding="0" cellspacing="0" width="%2%" border="0">' +
          '<tr><td><table cellpadding="3" cellspacing="1" width="100%" border="0">' +
          '<tr><td bgcolor="#336666" align="center" height="18">%3%</td></tr>' +
          '<tr><td align="center" height="*">%4%</td></tr>' +
		  '<tr><td height="3">  </td></tr>' +
          '</table></td></tr></table>';
var tp2 = '<table cellpadding="0" cellspacing="0" width="%2%" border="0">' +
          '<tr><td><table cellpadding="3" cellspacing="1" width="100%" border="0">' +
		  '<tr><td height="3">  </td></tr>' +
          '<tr><td align="center" height="*">%4%</td></tr>' +
		  '<tr><td height="3">  </td></tr>' +
          '</table></td></tr></table>';
function showTT(config) {
  staticTip = new TipObj('staticTip');
  var width = 200;
  var caption = '';
  if (config['width']) width = config['width'];
  if (config['title']) caption = config['title'];
  if (config['url']) {
    var callback = {
      success: function(o) {
        with (staticTip)
        {
          var text = o.responseText;
          // I'm using tables here for legacy NS4 support, but feel free to use styled DIVs.
          if (caption == '') template = tp2;
          else template = tp1;
          // HIERARCHIAL TIPS: To call one tip object from within another tip object, make sure you
          // pass the a reference to the current object as the second parameter to the show() function.
          tips.links = new Array(1, 1, width, caption, text);
          hideDelay = 10;
          tipStick = 0;
        }
        staticTip.show('links');
      },
      failure: function(o) {
      }
    };
    var cObj = YAHOO.util.Connect.asyncRequest('GET', config['url'] , callback);
  }
  else {
    with (staticTip) {
      // I'm using tables here for legacy NS4 support, but feel free to use styled DIVs.
          if (caption == '') template = tp2;
          else template = tp1;
      // HIERARCHIAL TIPS: To call one tip object from within another tip object, make sure you
      // pass the a reference to the current object as the second parameter to the show() function.
      tips.links = new Array(1, 1, width, caption, config['content']);
          hideDelay = 10;
      tipStick = 0;
    }
    staticTip.show('links');
  }
  return false;
}

function hideTT() {
  if (staticTip) {
    staticTip.hide();
  }
}

var retryCount = 0;
function openUserTab(username) {
	//console.log(arguments.callee.caller);
	//console.log(this);
	//console.log(arguments.callee);
  var title = '';
  var url = '';
  if (username!=null) {
    if (!alm) {
      if (retryCount>10) return false;
      else {
        setTimeout("openUserTab('"+ username +"')",1000);
        retryCount++;
        return false;
      }
    }
	title = username;
	url = '/pms/user/index.jsp';
  } else {
	title = 'Urmap會員';
	url = '/pms/loginBefore.jsp';
  }
  alm.getPanel('userDiv').getUpdateManager().update({url:url, nocache:true,scripts:true, callback:function(){
  	/*if(username)
  	document.getElementById('motorRoutingImg').onclick = function() {
				alm.getLayout('mainLayout').showPanel('routingDiv');
				setEvent();
			}*/
  }});
  if(username){
  	alm.getPanel('userDiv').setTitle(username);
	alm.getLayout('mainLayout').showPanel('userDiv');
  }
}

function closeUserTab() {
  if (alm.getPanel('userDiv')!=null)
    alm.getPanel('userDiv').closeClick();
}
function getCenterToTextBox(){
	var qsTextBox = $('queryString');
	var center = map.getCenter();
	setTextDefult(qsTextBox);
	qsTextBox.value = center.lat()+','+center.lng();
	U.blinkElement($('queryString'), '#FCB052');
}
function chTp(el){
	var chkBox = document.getElementById('chkSearchNowViewed');
	var qsTextBox = $('queryString');
	//alert(chkBox.checked);
	if(!chkBox.checked){
		
		el.style.color = '#000';
		el.style.fontWeight = '500';
		chkBox.value = qsTextBox.value;
		setTextDefult(qsTextBox);
		//qsTextBox.value = center.lat()+','+center.lng();
		getCenterToTextBox();
		map.addListener('moveend', getCenterToTextBox);
	}
	else{
		el.style.color = '#404040';
		el.style.fontWeight = '300';
		qsTextBox.disabled = '';
		//setTextDefult(qsTextBox);
		qsTextBox.value = chkBox.value;
		map.removeListener('moveend', getCenterToTextBox);
	}
	
	//void(0);
}
// param格式為{param1:'123', param2:'456'} or param1=123&param2=456
// 第二種必須做encoding
function refreshHeader(param) {
  if (param) {
    //alm.getPanel('headerDiv').getUpdateManager().update({ url:'/pms/include/mapHeader.jsp', params:param, scripts:false});
    eval(param);//sType=1,2,3
    var searchTarget;
    var tabClassName = '';
    mouseoverTab(sType);
    switch(sType){
    	case(2):
    		$('div_text_input').className = 'tab2_text_input';
			searchTarget = "poi";
    		break;
    	case(3):
    		$('div_text_input').className = 'tab3_text_input';
			searchTarget = "player";
    		break;
    	default:
    		$('div_text_input').className = 'tab1_text_input';
			searchTarget = "";
    		break;
    }
    $('mapHeader.sType').value = sType;
    $('searchTarget').value = searchTarget;
    //setQueryTextBox(sType);
  }
  //else {
    //alm.getPanel('headerDiv').setUrl('/pms/include/mapHeader.jsp', null, false);
  //}
  return false;
}
function mouseoverTab(sType){
	switch(sType){
    	case(2):
    		$('tab1').className = 'tab1';
    		$('tab2').className = 'tab2_active';
    		$('tab3').className = 'tab3';
    		break;
    	case(3):
    		$('tab1').className = 'tab1';
    		$('tab2').className = 'tab2';
    		$('tab3').className = 'tab3_active';
    		break;
    	default:
    		$('tab1').className = 'tab1_active';
    		$('tab2').className = 'tab2';
    		$('tab3').className = 'tab3';
    		break;
    }
}
function setDefaultTextonText(el, text){
	if(typeof(el) == 'string') el = document.getElementById(el);
	el.value = text;
	el.style.color = '#CCCCCC';
	el.onfocus = function(){if(this.value && this.value==text) setTextDefult(el);};
	el.onblur = function(){if(!this.value) {this.value=text;this.style.color = '#CCCCCC';}};
	//el.focus();
}
function setTextDefult(el){
	el.value='';el.style.color = '';
}
/*function setQueryTextBox(sType){
	var qry_div = document.getElementById('qry_div');
	var qryTextBox = document.getElementById('queryString');
	var qryKwTextBox;
	if(sType == 1){
		if(qry_div.getElementsByTagName('input').length < 2){
			qryKwTextBox = document.createElement('input');
			qryKwTextBox.id = 'queryStringKW';
			qryKwTextBox.value = 'test';
			qryKwTextBox.style.cssText = 'display:inline;width:31%;margin-right:3px;height:18px;font-size:13px;padding-top:2px;';
			qryKwTextBox.onkeypress = function(event){return entsub(event);};
			
			qryTextBox.style.cssText = 'display:inline;width:65%;height:18px;font-size:13px;padding-top:2px;';
			qry_div.insertBefore(qryKwTextBox, qryTextBox);
			//alert(qry_div.childNodes.length);
			setDefaultTextonText(qryKwTextBox, '請輸入關鍵字');
			setDefaultTextonText(qryTextBox, '請輸入地點');
		}
	}
	else {
		if(qryKwTextBox) {
			delete qryKwTextBox;
		}	
		qry_div.innerHTML = '<input type="text" id="queryString" onkeypress="return entsub(event);" value="" style="width:310px;height:18px;font-size:13px;padding-top:1px;" name="queryString"/>';
		
		qryTextBox = document.getElementById('queryString');
		if(sType == 2)	setDefaultTextonText(qryTextBox, '請輸入欲查詢的分享地標');
		else if(sType ==3)	setDefaultTextonText(qryTextBox, '請輸入欲查詢的玩家帳號');
	}
}*/
function drawUserMap(uid) {
  var center = map.getCenter();
  var bounds = map.getBounds();
  // 計算坐標範圍
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  var minLat = sw.lat();
  var minLon = sw.lng();
  var maxLat = ne.lat();
  var maxLon = ne.lng();
  var sUrl;
  if (uid) sUrl = '/pms/getUserPoiByBounds?uid='+uid+'&minlat='+minLat+'&minlng='+minLon+'&maxlat='+maxLat+'&maxlng='+maxLon;
  else sUrl = '/pms/getUserPoiByBounds?minlat='+minLat+'&minlng='+minLon+'&maxlat='+maxLat+'&maxlng='+maxLon;
  //document.write(sUrl);
  var callback = {
    success: function(o) {
      var poiText = o.responseText;
      //alert(poiText);
      markPmsPoi(poiText);
    },
    failure: function(o) {
      alert('伺服器錯誤，請稍後再試！');
    }
  };
  var cObj = YAHOO.util.Connect.asyncRequest('GET', sUrl , callback);
}
function latlngFormatCheck(qs){
	var latlng = qs.indexOf(',')!=-1?qs.split(','):null;
  	var chkLatlng = true;
  	if(latlng)	{
  		//alert('there is a ,');
	  	for(var ii in latlng){
	  		if(typeof parseFloat(latlng[ii]) != 'number'){
	  			chkLatlng = false;
	  			break;
	  		}
	  	}  	
  	}//else 	
  	//	chkLatlng = false;
  	return (latlng);
}
function doSearch() {
  var form = document.getElementById('searchForm');
  var sType = document.getElementById('mapHeader.sType').getAttribute('value');
  var qs = document.getElementById('queryString').value.trim();
  if (sType=='1') {
    smartQuery(qs);
  }else if (sType=='2' || sType=='3') {
    if (qs!=''){
      sendForm('searchForm', 'listDiv', true, '');
			UCounter.addCount('UrMap首頁_function_PMS搜尋');
		}
  }
  return false;
}

function switchMapIcon(obj) {
  var objId = obj.id;
  var cName = '';
  if(objId=='poiType1'){
  	cName = 'showPublicPoi';
  }
  else if(objId=='poiType2'){
  	cName = 'showPrivatePoi';
  }
  else if(objId=='poiType3'){
  	cName = 'showCollectedPoi';
  }
  
  if (obj.checked) {
  	remarkPOIType(obj.value);
  }
  else {
  	removePOIType(obj.value);
  }
  SetCookie(cName, obj.checked?'true':'false');
  
  return false;
}

// -- Start of Edward add

function drawAllUserMap(){
	var zoom = map.getZoomLevel();
	if(zoom <7){
		return;
	}
	var center = map.getCenter();
  var bounds = map.getBounds();
  // 計算坐標範圍
  var sw = bounds.getSouthWest();
  var ne = bounds.getNorthEast();
  var minLat = sw.lat();
  var minLon = sw.lng();
  var maxLat = ne.lat();
  var maxLon = ne.lng();
  var sUrl = '/pms/getUserPoiByBounds?&minlat='+minLat+'&minlng='+minLon+'&maxlat='+maxLat+'&maxlng='+maxLon+'&openAllUserPmsPoi='+openAllUserPmsPoi;
  //alert('sUrl='+sUrl);
  var callback = {
    success: function(o) {
      var poiText = o.responseText;
      //alert(poiText);
      getAllUserPmsPoi(poiText);
    },
    failure: function(o) {
      alert('伺服器錯誤，請稍後再試！');
    }
  };
  var cObj = YAHOO.util.Connect.asyncRequest('GET', sUrl , callback); 
}

var openAllUserPmsPoi = 'false';
var hasInitOpenAllUserPmsPoi = 'false';
function switchAllUserPmsPoi(obj) {
  if (obj.checked) {
  	openAllUserPmsPoi = 'true';
  	if(hasInitOpenAllUserPmsPoi == 'false'){
  		drawAllUserMap();
  		map.addListener('moveend', function(){drawAllUserMap();});
  		map.addListener('zoom', function(oldZoomLevel, newZoomLevel) {drawAllUserMap();});
  		hasInitOpenAllUserPmsPoi = 'true';
  	}
  	drawAllUserMap();
  	//remarkAllUserPmsPOI();
  }
  else {
  	openAllUserPmsPoi = 'false';
  	removeAllUserPmsPOI();
  }
  return false;
}

function getCookieVal (offset) 
{
 var endstr = document.cookie.indexOf (";", offset);
 if (endstr == -1)
    endstr = document.cookie.length;
 return unescape(document.cookie.substring(offset, endstr));
}

function GetCookie (name) 
{
	 var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;
   while (i < clen) 
   {
     var j = i + alen;
     if (document.cookie.substring(i, j) == arg)
        return getCookieVal (j);
     i = document.cookie.indexOf(" ", i) + 1;
     if (i == 0) break; 
   }
   return null;
}

function SetCookie (name, value) 
{
   var argv = SetCookie.arguments;
   var argc = SetCookie.arguments.length;
   var expires = (argc > 2) ? argv[2] : null;
   var path = (argc > 3) ? argv[3] : null;
   var domain = (argc > 4) ? argv[4] : null;
   var secure = (argc > 5) ? argv[5] : false;
   document.cookie = name + "=" + escape (value) +
        ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
        ((path == null) ? "" : ("; path=" + path)) +
        ((domain == null) ? "" : ("; domain=" + domain)) +
        ((secure == true) ? "; secure" : "");
}



// -- End of Edward add