var mapDataSource = "elocation_mercator" ;
var poiDataSource = "gcus" ;
var baseMapName = mapDataSource+".world_map" ; 
var baseURL  = "http://"+document.location.host+"/mapviewer";

var mapview;
var basemap0 = new MVMapTileLayer(baseMapName);
basemap0.setVisible(true);
var searchFrame ;
var resultNode ;
var leftPanel;
var poiTheme = null ;
var copyRight = null ;
var redline = null ;
var mouseRightClickLoc = null ;
var distSearchTheme =null ;
var radiusFOI = null ;
var clearResultNode = null ;
var lastMouseLoc = null ;
var enterAction = null ;
var enterActionParam = null ;
var distAreaBar = null ;
var isIE = navigator.userAgent.indexOf("MSIE")>=0 ;
var isIE7 = navigator.userAgent.indexOf("MSIE 7")>=0 ;
var CITY_LEVEL=11 ;
var STREET_LEVEL=14 ;

function init()
{
  resultNode = document.getElementById("result_panel") ;
  clearResultNode = document.getElementById("clear_result") ;
  showMap() ;
}
function rightClick()
{
  document.getElementById("marqueezoom").checked=false ;
  mapview.stopMarqueeZoom() ;
  mouseRightClickLoc = mapview.getMouseLocation();
  showRightClickMenu(mouseRightClickLoc);
}
function showMap()
{
  mapview = new MVMapView(document.getElementById("map"), baseURL);
  mapview.addMapTileLayer(basemap0);
  var mapCenterLon = -96;
  var mapCenterLat =  45;
  var mapZoom      =  3;  
  var mpoint = MVSdoGeometry.createPoint(mapCenterLon,mapCenterLat,8307);
  mapview.setCenter(mpoint);   
  mapview.setZoomLevel(mapZoom);
  mapview.addNavigationPanel("EAST");
  addSearchIcons() ;  
  addMapControls() ;
  addCopyRightNote() ;
  addOverViewMap() ;
  mapview.addEventListener("mouse_right_click", rightClick);
  mapview.display();  			
  mapview.addScaleBar();
  mapview.addEventListener("mouse_click", removeMenu);
  var iframe = document.getElementById("search_frame") ;
  leftPanel = document.getElementById("left_panel") ;
  resultNode.style.height=(leftPanel.offsetHeight-resultNode.offsetTop-50)+"px" ;
  if(document.getElementById("marqueezoom"))
    document.getElementById("marqueezoom").checked=false ;
}

function addMapControls()
{
  var mapTypeControl = 
    "<div id='type_map' class=ElocButtonSelected style='left:0.5em;width:4em' onclick='selectMapType(this)'>Map</div>"+
    "<div id='type_satellite' class=ElocButton style='left:5em;width:4em' onclick='selectMapType(this)'>Satellite</div>"+
    "<div id='type_hybrid' class=ElocButton style='left:9.5em;width:4em' onclick='selectMapType(this)'>Hybrid</div>" ;
    
  /*var md=new MVMapDecoration(mapTypeControl, 0.5, 0,200,20);
  md.setOffset(0, 5);
  mapview.addMapDecoration(md);*/
  
  var toolBar =
    "<div>"+
    "<table cellpadding=1 cellspacing=0>"+
    "<tr><td style='border-width:1px;border-style:solid;border-color:black;background-color:white'>"+
    "<table cellpadding=0 cellspacing=0>"+
    "<tr VALIGN=middle>"+
    "<td align=right>"+
    (isIE&&!isIE7?
      "<div style=\"width:24px;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/zoombox.png\', sizingMethod=\'scale\')\" title='Marquee Zoom' onclick='enableMarqueeZoom(false)'></div>" :  
      "<img style='width:24px;cursor:pointer' src='images/zoombox.png' title='Marquee Zoom' onclick='enableMarqueeZoom(false)'>")+
    "</td>"+
    "<td align=left>"+
    "<INPUT style='' id='marqueezoom' title='Marquee Zoom' TYPE='checkbox' value='marqueezoom' onclick='enableMarqueeZoom(true)' unchecked/>"+
    "</td>"+
    "<td width='0.5em'>&nbsp;&nbsp;"+
    "</td>"+
    "<td>"+
    (isIE&&!isIE7?
      "<div style=\"width:16px;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/ruler.png\', sizingMethod=\'scale\')\" title='Measure distance' onclick='measureDistanceArea(false)'></div>" :  
      "<img style='width:16px;cursor:pointer' src='images/ruler.png' title='Measure distance' onclick='measureDistanceArea(false)'>")+
    "</td>"+
    "<td align=left>"+
    "<INPUT id='distarea' title='Measure distance/area' TYPE='checkbox' value='distarea' onclick='measureDistanceArea(true)' unchecked/>"+
    "</td>"+
    "</tr>"+
    "</table>"+
    "</td></tr></table>"+
    "</div>" ;
  md = new MVMapDecoration(toolBar, 0, 0) ;
  md.setOffset(5, 2) ;
  mapview.addMapDecoration(md);
}

function addCopyRightNote()
{
  copyRight=new MVMapDecoration( "&#169;2009 Oracle Corp. &#169;2009 NAVTEQ&#8482;",1, 1,400,20);
  copyRight.setOffset(-600, -20);
  mapview.addMapDecoration(copyRight);
}

function addOverViewMap()
{
  ovcontainer = new MVMapDecoration(null,null,null,200,150) ;
  ovcontainer.setCollapsible(true, true);
  ovcontainer.setTitleBar("Overview Map", "images/overviewicon.gif", "Overview map");
  mapview.addMapDecoration(ovcontainer);
  var over=new MVOverviewMap(ovcontainer.getContainerDiv(),4);
  mapview.addOverviewMap(over) ;
}

function escapeSingleQuote(instr)
{
  if(instr)
    return instr.replace("'", "\\'") ;
  else
    return instr ;
}

function showPOIInfo(name, street, lastLine, x, y, edgeId, side, percent, country)
{
  var infoStr = "<font class=OraPromptText>" ;
  infoStr += (street&&street.length>0)?(street+"<BR>"+lastLine):lastLine;
  infoStr += "<BR><BR>Get directions:" ;
  var address = escapeSingleQuote(((street&&street.length>0)?(street+","+lastLine):lastLine))+","+country ;
  infoStr += "<a href='javascript:void(0)' onclick='showDirectionsPan(\"from\", true,\""+address+"\")'>From here</a>&nbsp;&nbsp;" ;
  infoStr += "<a href='javascript:void(0)' onclick='showDirectionsPan(\"to\", true,\""+address+"\")'>To here</a>" ;
  infoStr += "</font>" ;
  infoStr += "<input id='hidden_address' type='hidden' value='"+address+"'>" ;
  infoStr += "<input id='street' type='hidden' value='"+escapeSingleQuote(street)+"'>" ;
  infoStr += "<input id='lastline' type='hidden' value='"+escapeSingleQuote(lastLine)+"'>" ;
  infoStr += "<input id='lon' type='hidden' value='"+x+"'>" ;
  infoStr += "<input id='lat' type='hidden' value='"+y+"'>" ;
  infoStr += "<input id='edgeid' type='hidden' value='"+edgeId+"'>" ;
  infoStr += "<input id='side' type='hidden' value='"+side+"'>" ;
  infoStr += "<input id='percent' type='hidden' value='"+percent+"'>" ;
  var winHeight = (street&&street.length>0)?110+20:120 ;
  var loc = MVSdoGeometry.createPoint(x,y);
  var winWidth = 250 ;
  if(name.length*10>250)
    winWidth = name.length*10 ;
  mapview.displayInfoWindow(loc, infoStr, winWidth, winHeight, null, name) ;
}

function clearResults()
{
  clearSearchResult() ;
  mapview.removeFOI("start");
  mapview.removeFOI("end");
  mapview.removeFOI("route");
  if(poiTheme)
    poiTheme.setVisible(false);
  if(distSearchTheme)
    distSearchTheme.setVisible(false);
  if(radiusFOI)
  {
    mapview.removeFOI(radiusFOI);
    radiusFOI = null ;
  }
  clearResultNode.innerHTML = "" ;
}

function showDistPOIs()
{
  var fois = distSearchTheme.getFOIData() ;
  showPOIs(fois) ;
}

function showNamePOIs()
{
  if(distSearchTheme)
    distSearchTheme.setVisible(false);
  if(radiusFOI)
  {
    mapview.removeFOI(radiusFOI);
    radiusFOI = null ;
  }
  var fois = poiTheme.getFOIData() ;
  showPOIs(fois) ;
}

function showPOIs(fois)
{
  clearSearchResult() ;
  resultNode.style.height=(leftPanel.offsetHeight-resultNode.offsetTop-50)+"px" ;
  if(fois)
  {
    clearResultNode.innerHTML = "<font class=OraFieldLink><a href='javascript:clearResults()'>Clear results</a></font>" ;

    var resultNodeHTML = "<div style='overflow:auto;clip:auto;height:"+window.parent.resultNode.style.height+"'>" ;
    resultNodeHTML += "<font class=OraFieldText>Search results:"+fois.length+"</font> " ;
    resultNodeHTML += "<table width='100%' bgcolor='#cccc99'>" ;
    resultNodeHTML += "<tbody>" ;

    for(i=0; i<fois.length; i++)
    {
      resultNodeHTML += "<tr class=OraSmallTableCellText>" ;
      resultNodeHTML += "<td>" ;
      resultNodeHTML += "<a href=\"javascript:void(0)\" onclick=\"showPOIInfo('"+
                        escapeSingleQuote(fois[i].name)+"','"+escapeSingleQuote(fois[i].attrs[3])+"','"+
                        escapeSingleQuote(fois[i].attrs[4])+"',"+fois[i].x+","+fois[i].y+","+
                        fois[i].attrs[0]+",'"+fois[i].attrs[1]+"',"+
                        fois[i].attrs[2]+",'"+fois[i].attrs[6]+"')\">"+fois[i].name+"</a><BR>" ;
      if(fois[i].attrs[3])
        resultNodeHTML += fois[i].attrs[3]+"<br>" ;
      resultNodeHTML += fois[i].attrs[4]+"<br>"+fois[i].attrs[5] ;
      resultNodeHTML += "</td></tr>" ;
    }
    setResultNodeContent(resultNodeHTML+"</tobdy></table></div>") ;
  }
}

function displayPOIInfoWindow(loc, foi)
{
  foi.name = trim(foi.name) ;
  showPOIInfo(foi.name, foi.attrs[3], foi.attrs[4], foi.x, foi.y, 
              foi.attrs[0], foi.attrs[1], foi.attrs[2], foi.attrs[6]) ;    
}

function getSearchKeywords(id)
{
  var searchParam = getNodeValue(id) ;
  var keywords = searchParam.split(' ') ;
  searchParam = "" ;
  var first = true ;
  for(i=0; i<keywords.length; i++)
  {
    if(keywords[i] && keywords[i]!=' ')
    {
      if(!first)
        searchParam += ' AND ' ;
      else
        first = false ;
      searchParam += keywords[i] ;
    }
  }
  return searchParam ;
}

function setQueryParameters()
{
  var searchParam = getSearchKeywords('poiname') ;
  if(!searchParam || searchParam=='')
    return ;
  var bbox = poiTheme.getLayerMBR() ;
  poiTheme.setQueryParameters(searchParam, bbox) ;
}

function searchPOI()
{
  clearResults() ;
  var searchParam = getSearchKeywords('poiname') ;
  if(!searchParam || searchParam=='')
    return ;
  if(!poiTheme)
  {
    poiTheme = new MVThemeBasedFOI('poisearch', poiDataSource +'.poi_search_100') ;
    var bbox = mapview.getMapWindowBBox() ;
    poiTheme.setQueryParameters(searchParam, bbox) ;
    poiTheme.addEventListener('before_refresh', setQueryParameters) ;
    poiTheme.addEventListener('after_refresh', showNamePOIs) ;
    poiTheme.addEventListener('mouse_click', displayPOIInfoWindow) ;
    poiTheme.setQueryWindowMultiplier(1) ;
    mapview.addThemeBasedFOI(poiTheme) ;
  }
  else
  {
    poiTheme.setQueryParameters(searchParam) ;
    if(poiTheme.isVisible())
      poiTheme.refresh() ;
    else
    {
      poiTheme.setVisible(true) ;
      poiTheme.refresh() ;
      showNamePOIs() ;
    }
  }
}

function getMap(id)
{
  var address1Node = document.getElementById("address"+id) ;
  if(!address1Node.value && address1Node.value.length==0)
    return ;
  if(!searchFrame)
    searchFrame = document.getElementById("search_frame") ;
    
  searchFrame.src = "search.jsp?address"+id+"="+encodeURI(address1Node.value) ;
}

function clearNode(node)
{
  if(node && node.childNodes)
  {
    while(node.childNodes.length>0)
    {
      node.removeChild(node.childNodes[0]) ;
    }
  }
}

function clearSearchResult()
{
  resultNode = document.getElementById("result_panel") ;
  clearNode(resultNode) ;
}

function setAddress(id, street, lastLine, country, x, y, edgeId, side, percent)
{
  if(street!=null && street.length>0)
  {
    setInputValue("address"+id, street+","+lastLine+","+country) ;
    setInputValue("hidden_address"+id, street+","+lastLine+","+country) ;
  }
  else
  {
    setInputValue("address"+id, lastLine+","+country) ;
    setInputValue("hidden_address"+id, lastLine+","+country) ;
  }
  setInputValue("street"+id, street) ;
  setInputValue("lastline"+id, lastLine) ;
  setInputValue("lon"+id, x) ;
  setInputValue("lat"+id, y) ;
  setInputValue("edgeid"+id, edgeId) ;
  setInputValue("side"+id, side) ;
  setInputValue("percent"+id, percent) ;
  setInputValue("country"+id, country) ;
}

function createAddressMarker(markerId, street, lastLine, country, x, y, 
                             edgeId, side, percent, displayInfoWindow)
{
  mapview.removeFOI(markerId);
  var loc = MVSdoGeometry.createPoint(x, y, 8307) ;
  var callBack = function(newLoc)
  {
    var imgStr = isIE&&!isIE7 ?
                   "<div style=\"position:absolute;width:16px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'images/flag.png\', sizingMethod=\'scale\')\"></div>" : 
                   "<img src='images/flag.png'>" ;
    var marker = MVFOI.createHTMLFOI(markerId, newLoc, imgStr, 1, -10) ;
    var infoStr = "<font class=OraHeaderSubSub>" ;
    infoStr += (street&&street.length>0)?(street+"<BR>"+lastLine):lastLine ;
    var address = escapeSingleQuote(((street&&street.length>0)?(street+","+lastLine):lastLine)+","+country) ;
    infoStr += "</font>";
    infoStr += "<font class=OraPromptText>" ;
    infoStr += "<BR><BR>Get directions:" ;
    infoStr += "<a href='javascript:void(0)' onclick=\"showDirectionsPan('from', true,'"+address+"')\">From here</a>&nbsp;&nbsp;" ;
    infoStr += "<a href='javascript:void(0)' onclick=\"showDirectionsPan('to', true,'"+address+"')\">To here</a>" ;
    infoStr += "</font>" ;
    infoStr += "<input id='hidden_address' type='hidden' value='"+address+"'>" ;
    infoStr += "<input id='street' type='hidden' value='"+street+"'>" ;
    infoStr += "<input id='lastline' type='hidden' value='"+lastLine+"'>" ;
    infoStr += "<input id='lon' type='hidden' value='"+x+"'>" ;
    infoStr += "<input id='lat' type='hidden' value='"+y+"'>" ;
    infoStr += "<input id='edgeid' type='hidden' value='"+edgeId+"'>" ;
    infoStr += "<input id='side' type='hidden' value='"+side+"'>" ;
    infoStr += "<input id='percent' type='hidden' value='"+percent+"'>" ;
    var winHeight = (street&&street.length>0)?100+20:100
    var winWidth = 250 ;
    marker.setInfoWindow(infoStr, winWidth, winHeight);
    mapview.addFOI(marker) ;
    if(displayInfoWindow)
      mapview.displayInfoWindow(newLoc, infoStr, winWidth, winHeight) ;
  }
  if(mapview.getSrid()!=8307) 
  {
    mapview.transformGeom(loc, mapview.getSrid(), null, callBack) ;
  }
  else
    callBack(loc) ;
}

function setGCResult(id, street, lastLine, country, x, y, edgeId, side, percent, level)
{
  clearResults() ;    
  setAddress(id, street, lastLine, country, x, y, edgeId, side, percent) ;
  var loc = MVSdoGeometry.createPoint(x, y, 8307) ;
  mapview.setCenterAndZoomLevel(loc, level) ;
  createAddressMarker('address', street, lastLine, country, x, y, edgeId, side, percent, true) ;
}

function setInputValue(id, value)
{
  document.getElementById(id).value = value ;
}

function setResultNodeContent(result)
{
  resultNode.innerHTML = result ;
}

function getHiddenAddress(id)
{
  return document.getElementById('hidden_address'+id).value ;
}

function getNodeValue(id)
{
  var node = document.getElementById(id) ;
  if(!node || !node.value || node.value=='')
    return '' ;
  else
    return node.value;
}

function getAddress(id)
{
  return document.getElementById('address'+id).value ;
}

function getDirections()
{
  clearResults();
  var address1 = getNodeValue("address1") ;
  if(address1!=getNodeValue("hidden_address1"))
    resetHiddenAddress(1) ;
  var address2 = getNodeValue("address2") ;
  if(address2!=getNodeValue("hidden_address2"))
    resetHiddenAddress(2) ;
  if(address1=='' || address2=='')
    return ;
  if(!searchFrame)
    searchFrame = document.getElementById("search_frame") ;
    
  searchFrame.src = "direction.jsp?address1="+encodeURI(address1) +
                    "&street1="+getNodeValue('street1')+"&lastline1="+getNodeValue('lastline1')+
                    "&city1="+getNodeValue("city1")+"&region1="+getNodeValue("region1")+
                    "&postalCode1="+getNodeValue("postalCode1")+"&country1="+getNodeValue("country1")+
                    "&lon1="+getNodeValue('lon1')+"&lat1="+getNodeValue('lat1')+
                    "&edgeid1="+getNodeValue('edgeid1')+"&side1="+getNodeValue('side1')+
                    "&percent1="+getNodeValue('percent1')+
                    "&country1="+getNodeValue('country1')+
                    "&address2="+encodeURI(address2) +
                    "&street2="+getNodeValue('street2')+"&lastline2="+getNodeValue('lastline2')+
                    "&city2="+getNodeValue("city2")+"&region2="+getNodeValue("region2")+
                    "&postalCode2="+getNodeValue("postalCode2")+"&country2="+getNodeValue("country2")+
                    "&lon2="+getNodeValue('lon2')+"&lat2="+getNodeValue('lat2')+
                    "&edgeid2="+getNodeValue('edgeid2')+"&side2="+getNodeValue('side2')+
                    "&percent2="+getNodeValue('percent2')+
                    "&country2="+getNodeValue('country2');
}

function setHiddenInputs(id) 
{
  setInputValue("hidden_address"+id, getNodeValue("hidden_address")) ;
  setInputValue("street"+id, getNodeValue("street")) ;
  setInputValue("lastline"+id, getNodeValue("lastline")) ;
  setInputValue("lon"+id, getNodeValue("lon")) ;
  setInputValue("lat"+id, getNodeValue("lat")) ;
  setInputValue("edgeid"+id, getNodeValue("edgeid")) ;
  setInputValue("side"+id, getNodeValue("side")) ;
  setInputValue("percent"+id, getNodeValue("percent")) ;
}

function clearHiddenInputs(id)
{
  setInputValue("hidden_address"+id, "") ;
  setInputValue("street"+id, "") ;
  setInputValue("lastline"+id, "") ;
  setInputValue("lon"+id, "") ;
  setInputValue("lat"+id, "") ;
  setInputValue("edgeid"+id, "-1") ;
  setInputValue("side"+id, "") ;
  setInputValue("percent"+id, "") ;
}

var searchImgStr = isIE&&!isIE7 ?
               "<div style=\"position:absolute;border:0;width:16px;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/search.png', sizingMethod='image')\"></div>" : 
               "<img src='images/search.png' style='cursor:pointer;border:0'>" ;

function showDirectionsPan(fromOrTo, closeInfoWindow, address)
{
  clearResults() ;
  resultNode.style.height="0px" ;
  var titleBar = document.getElementById('getmapdirection_title') ;
  clearNode(titleBar) ;
  titleBar.innerHTML = "<font class=OraDataLink><A href='javascript:showMapPan(1)'>Get Map</A>&nbsp;&nbsp;</font><FONT class=OraDataText>Get Directions</FONT>" ;
  var inputPanel = document.getElementById('address_input') ;
  clearNode(inputPanel) ;
  var addressLine = null ;
  if(closeInfoWindow)
  {
    if(address)
      addressLine = address ;
    else
      addressLine = getNodeValue("hidden_address") ;
  }
  else
    addressLine = getNodeValue("hidden_address1") ;


  if(fromOrTo=='from')
  {
    inputPanel.innerHTML = '<font class=OraPromptText>From:</font><br>'+
                           '<INPUT id="address1" tabIndex=3 maxLength=60 size=40 value="'+addressLine+'" name=address1" onkeypress="checkEnter(event, getDirections)">'+
                           '<A href="javascript:getMap(1);">'+
                           searchImgStr + '</A><BR>' +
                           '<font class=OraPromptText>To:</font><br>'+
                           '<INPUT id="address2" tabIndex=3 maxLength=60 size=40 value="" name=address2 onkeypress="checkEnter(event, getDirections)">'+
                           '<A href="javascript:getMap(2);">'+
                           searchImgStr + '</A><br>' +
                           '<FONT face="Arial, Helvetica, sans-serif" size=1>Street Address, City, State or Postal Code</FONT><BR>'+
                           '<center><input type=button class=OraButtonText onclick="getDirections()" value="Get Directions"></center>' ;
    if(getNodeValue("lon")!='')
    {
      setHiddenInputs(1) ;
      clearHiddenInputs(2);
    }
  }
  else 
  {
    inputPanel.innerHTML = '<font class=OraPromptText>From:</font><br>'+
                           '<INPUT id="address1" tabIndex=3 maxLength=60 size=40 value="" name=address1>'+
                           '<A href="javascript:getMap(1);">'+
                           searchImgStr + '</A><BR>' +
                           '<font class=OraPromptText>To:</font><br>'+
                           '<INPUT id="address2" tabIndex=3 maxLength=60 size=40 value="'+addressLine+'" name=address2>'+
                           '<A href="javascript:getMap(2);">' +
                           searchImgStr + '</A>' +
                           '<FONT face="Arial, Helvetica, sans-serif" size=1>Street Address, City, State or Postal Code</FONT><BR>'+
                           '<center><input type=button class=OraButtonText onclick="getDirections()" value="Get Directions"></center>' ;
    if(getNodeValue("lon")!='')
    {
      setHiddenInputs(2) ;
      clearHiddenInputs(1);
    }
  }
  resultNode.style.height=(leftPanel.offsetHeight-resultNode.offsetTop-50)+"px" ;
  if(closeInfoWindow)
    mapview.removeInfoWindow() ;
}

function showMapPan(id)
{
  clearResults();
  var titleBar = document.getElementById('getmapdirection_title') ;
  clearNode(titleBar) ;
  titleBar.innerHTML = "<FONT class=OraDataText>Get Map&nbsp;&nbsp;</FONT><font class=OraDataLink><A href=\"javascript:showDirectionsPan('from')\">Get Directions</A></font>" ;
  var inputPanel = document.getElementById('address_input') ;
  var address = getAddress(id) ;
  clearNode(inputPanel) ;
  inputPanel.innerHTML = '<INPUT id="address1" tabIndex=3 maxLength=60 size=40 value="'+address+'" name=address1 onkeypress="checkEnter(event, getMap, 1)">'+
                         '<A href="javascript:getMap(1);">'+
                         searchImgStr+'</A><BR>' +
                         '<FONT face="Arial, Helvetica, sans-serif" size=1>Street Address, City, State or Postal Code</FONT>';
  resultNode.style.height=(leftPanel.offsetHeight-resultNode.offsetTop-50)+"px" ;
}
function resetHiddenAddress(id)
{
  setInputValue("hidden_address"+id, "") ;
  setInputValue("street"+id, "") ;
  setInputValue("lastline"+id, "") ;
  setInputValue("lon"+id, "") ;
  setInputValue("lat"+id, "") ;
  setInputValue("edgeid"+id, "-1") ;
  setInputValue("side"+id, "") ;
  setInputValue("percent"+id, "") ;
}
var oracleOffices = null ;

function openOfficeURL(url)
{
  newwindow=window.open(url, 'mywindow');
  if (window.focus) 
    newwindow.focus() ;
}

function trim(str)
{
   str = str.replace(/^\s*|\s*$/g,"");
   str = str.replace(/&nbsp;/g, " ") ;
   return str ;
}  

function clickOffice(loc, foi)
{
  var infoStr = "<img src='images/oraclelogo.gif'><br>" ;
  infoStr += "<font class=OraHeaderSubSub>" ;
  foi.name = trim(foi.name);
  infoStr += foi.name +"</font><br>" ;
  infoStr += "<font class=OraPromptText>"+ foi.attrs[0] ;
  infoStr += "<BR>URL: <a href=\"javascript:void(0)\" onclick=\"openOfficeURL('"+foi.attrs[1]+"')\">Click here</a>" ;
  infoStr += "</font>" ;
  infoStr += "<BR>Get directions: " ;
  infoStr += "<a href='javascript:void(0)' onclick='showDirectionsPan(\"from\", true)'>From here</a>&nbsp;&nbsp;" ;
  infoStr += "<a href='javascript:void(0)' onclick='showDirectionsPan(\"to\", true)'>To here</a>" ;
  infoStr += "</font>" ;
  infoStr += "<input id='hidden_address' type='hidden' value='"+foi.attrs[0]+"'>" ;
  infoStr += "<input id='street' type='hidden' value=''>" ;
  infoStr += "<input id='lastline' type='hidden' value=''>" ;
  infoStr += "<input id='lon' type='hidden' value=''>" ;
  infoStr += "<input id='lat' type='hidden' value=''>" ;
  infoStr += "<input id='edgeid' type='hidden' value=''>" ;
  infoStr += "<input id='side' type='hidden' value=''>" ;
  infoStr += "<input id='percent' type='hidden' value=''>" ;
  hiddenAddress = foi.addrs[0] ;
  var winWidth = 250 ;
  if(foi.name.length*9>winWidth)
    winWidth = foi.name.length*9 ;
  if(foi.attrs[0].length*7.2>winWidth)
    winWidth = foi.attrs[0].length*7.2 ;
  mapview.displayInfoWindow(loc, infoStr, winWidth, 140) ;
}

function showOracleOffices(checkBoxClicked)
{
  var checkBox = document.getElementById("showoffices") ;
  if(!checkBoxClicked)
    checkBox.checked = !checkBox.checked ;
  if(checkBox.checked)
  {
    if(!oracleOffices)
    {
      oracleOffices = new MVThemeBasedFOI("oracle_offices", poiDataSource+".oracle_offices") ;
      oracleOffices.setBoundingTheme(true) ;
      oracleOffices.addEventListener('mouse_click', clickOffice) ;
      mapview.addThemeBasedFOI(oracleOffices) ;
    }
    else
      oracleOffices.setVisible(true) ;
  }
  else
  {
    if(oracleOffices)
      oracleOffices.setVisible(false) ;
  }
}

function enableMarqueeZoom(checkBoxClicked)
{
  var checkBox = document.getElementById("marqueezoom") ;
  if(!checkBoxClicked)
    checkBox.checked = !checkBox.checked ;
  if(checkBox.checked)
    mapview.startMarqueeZoom("prompt"); 
  else
    mapview.stopMarqueeZoom() ;
}
function setCopyRight(text)
{
  copyRight.getContainerDiv().innerHTML = text ;
}
function selectMapType(item)
{
  document.getElementById('type_map').style.backgroundColor='#ffffff';
  document.getElementById('type_map').style.color='#000000';
  document.getElementById('type_satellite').style.backgroundColor='#ffffff';
  document.getElementById('type_satellite').style.color='#000000';
  document.getElementById('type_hybrid').style.backgroundColor='#ffffff';
  document.getElementById('type_hybrid').style.color='#000000';
  item.style.backgroundColor = '#336699' ;
  item.style.color = '#ffffff' ;
  var type = item.innerHTML;
  if(type=='Map')
  {
    copyRight.getContainerDiv().style.color="#000000";
    setCopyRight("&#169;2007 Oracle Corp. &#169;2007 NAVTEQ&#8482;") ; 
    basemap1.setVisible(false);
    basemap2.setVisible(false);
    if(!basemap0.isVisible())
      basemap0.setVisible(true);
  }
  else if(type=='Hybrid')
  {
    copyRight.getContainerDiv().style.color="#ffffff";
    setCopyRight("&#169;2007 Oracle Corp. &#169;2007 Digital Globe. &#169;2007 NAVTEQ&#8482;") ; 
    basemap0.setVisible(false);
    if(!basemap1.isVisible())
      basemap1.setVisible(true);
    if(!basemap2.isVisible())
      basemap2.setVisible(true);
  }
  else
  {
    // satellite
    copyRight.getContainerDiv().style.color="#ffffff";
    setCopyRight("&#169;2007 Oracle Corp. &#169;2007 Digital Globe.") ; 
    basemap0.setVisible(false);
    if(!basemap1.isVisible())
      basemap1.setVisible(true);
    basemap2.setVisible(false);
  }
}

function removeMenu()
{
  mapview.removeFOI("right_click_menu") ;
}

function showRightClickMenu(loc)
{
  mapview.removeFOI("right_click_menu");
  var html = "<table cellpadding=1 cellspacing=0 style='width:8em'><tr>"+
             "<td style='border-width:1px;border-style:solid;border-color:black;background-color:white'>"+
             "<table><tbody id='menu_table'></tbody></table>"+
             "</td>"+
             "</tr></table>"
  var menu = MVFOI.createHTMLFOI("right_click_menu", loc, html, -2, -2) ;
  menu.setInfoTip(null);
  menu.setInfoWindow(null, 0, 0);
  mapview.addFOI(menu);
  menu = document.getElementById('menu_table') ;
  menu.appendChild(createMenuItem(menu, 'To city level', zoomToCity)) ;
  menu.appendChild(createMenuItem(menu, 'To street level', zoomToStreet)) ;
  menu.appendChild(createMenuItem(menu, 'Nearby businesses', showSearchWindow)) ;
}

function zoomToCity()
{
  removeMenu();
  mapview.setCenterAndZoomLevel(mouseRightClickLoc, CITY_LEVEL);
}

function zoomToStreet()
{
  removeMenu();
  mapview.setCenterAndZoomLevel(mouseRightClickLoc, STREET_LEVEL);
}

function showSearchWindow()
{
  removeMenu();
  var searchImgStr = isIE&&!isIE7 ?
                 "<div style=\"position:absolute;border:0;width:16px;cursor:pointer;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/search.png', sizingMethod='image')\"" : 
                 "<img src='images/search.png' style='cursor:pointer;border:0'" ;
  var infoStr = "<font class=OraHeaderSubSub>Find nearby businesses</font><br>" ;
  infoStr += "<font size=-1><br></font>" ;
  infoStr += "<table class=OraPromptText>" ;
  infoStr += "<tr><td align=right>Radius:</td><td align=left><input id='radius_input' size=2 value=1> miles</td><tr>" ;
  infoStr += "<tr><td align=right>Keywords:</td><td align=left><input id='dist_keywords' size=15 onkeypress='checkEnter(event, searchNearbyBusinesses)'/>"+searchImgStr + " style='cursor:pointer' onclick='searchNearbyBusinesses()'"+
  (isIE&&!isIE7?"></div>":">")+"</td></tr>" ;
  infoStr += "</table>" ;
  mapview.displayInfoWindow(mouseRightClickLoc, infoStr, 300, 150);
}

function searchNearbyBusinesses()
{
  clearResults() ;
  dist = document.getElementById('radius_input').value ;
  searchParam = getSearchKeywords('dist_keywords');
  mapview.transformGeom(mouseRightClickLoc, 8307, null, showRadiusAndSearchResult) ;
}

function showRadiusAndSearchResult(center)
{
  if(radiusFOI)
    mapview.removeFOI(radiusFOI) ;
  var radiusGeom = MVSdoGeometry.createGeodeticCirclePolygon(center.getPointX(), center.getPointY(), dist*1609, 8307) ;
  radiusFOI = new MVFOI("radiusFOI", radiusGeom, poiDataSource + ".C.TRANSPARENT_RED") ;
  mapview.addFOI(radiusFOI) ;
  var mbr = radiusGeom.getMBR() ;
  var rect = MVSdoGeometry.createRectangle(mbr[0], mbr[1], mbr[2], mbr[3], 8307) ;
  mapview.zoomToRectangle(rect) ;
  
  if(distSearchTheme)
  {
    distSearchTheme.setVisible(true);
    distSearchTheme.setQueryParameters(searchParam, mouseRightClickLoc, dist) ;
    distSearchTheme.refresh() ;
  }
  else
  {
    distSearchTheme = new MVThemeBasedFOI('distsearch', poiDataSource + '.poi_search_dist') ;
    distSearchTheme.setQueryParameters(searchParam, mouseRightClickLoc, dist) ;
    distSearchTheme.addEventListener('after_refresh', showDistPOIs) ;
    distSearchTheme.addEventListener('mouse_click', displayPOIInfoWindow) ;
    mapview.addThemeBasedFOI(distSearchTheme) ;
  }
}

function createMenuItem(menu, label, listener)
{
  /*var item = document.createElement('div') ;
  item.style.fontFamily = "Arial, Helvetica, Geneva, sans-serif" ;
  item.style.fontSize = "13px" ;
  item.style.position = "absolute" ;
  var w = menu.style.width;
  if(w.indexOf("em")>0)
  {
    var width = w.substring(0, w.indexOf("em")) ;
    w = width*0.98+"em" ;
  }
  else if(w.indexOf("px")>0)
  {
    var width = w.substring(0, w.indexOf("px")) ;
    w = width*0.98+"px" ;
  }
  else
    w = x*0.98 ;
  item.style.width = w ;
  item.style.left = '2px' ;
  item.style.top = (menu.childNodes.length-1)*1.3 + 'em' ;
  item.style.textAlign = 'left' ;
  item.innerHTML = label ;
  item.onmouseover = function()
  {
    this.style.backgroundColor = "#336699" ;
    this.style.color = "#ffffff" ;
  }
  item.onmouseout = function()
  {
    this.style.backgroundColor = "transparent" ;
    this.style.color = "#000000" ;
  }
  if(listener)
  {
    item.onmousedown = function(event)
    {
      stopEvent(event) ;
      listener() ;
    }
  }*/
  var item = document.createElement('tr') ;
  item.style.fontFamily = "Arial, Helvetica, Geneva, sans-serif" ;
  item.style.fontSize = "13px" ;
  item.align = 'left' ;
  var td = document.createElement("td") ;
  td.innerHTML = label ;
  item.appendChild(td);
  item.onmouseover = function()
  {
    this.style.backgroundColor = "#336699" ;
    this.style.color = "#ffffff" ;
  }
  item.onmouseout = function()
  {
    this.style.backgroundColor = "transparent" ;
    this.style.color = "#000000" ;
  }
  if(listener)
  {
    item.onmousedown = function(event)
    {
      stopEvent(event) ;
      listener() ;
    }
  }
  return item ;
}

var distance = true ;

function measureDistanceArea(checkBoxClicked)
{
  var checkBox = document.getElementById("distarea") ;
  if(!checkBoxClicked)
    checkBox.checked = !checkBox.checked ;
  if(checkBox.checked)
  {
    if(!distAreaBar)
      createDistanceAreaBar() ;
    distAreaBar.setVisible(true);
    document.getElementById("distarea_bar").innerHTML = 0 ;
    
    distance = true ;
    document.getElementById("marqueezoom").checked=false ;
    mapview.stopMarqueeZoom() ;
    if(!redline)
    {
      redline = new MVRedlineTool(mapDataSource+".L.EUPH", mapDataSource+".C.ROSY BROWN STROKE");
      mapview.addRedLineTool(redline);
    }
    //stopMeasuringDistance() ;
    redline.init() ;
    redline.addEventListener("mouse_click", showDistanceArea);
  }
  else
  {
    stopMeasuringDistance();
    distAreaBar.setVisible(false);
  }
}

function createDistanceAreaBar()
{
  var distAreaBarStr =
    "<div>"+
    "<table cellpadding=1 cellspacing=0 ><tr>"+
    "<td style='border-width:1px;border-style:solid;border-color:black;background-color:white' id='distarea_bar'>"+
    "</td></tr></table>"+
    "</div>" ;
  distAreaBar = new MVMapDecoration(distAreaBarStr, 0, 0) ;
  distAreaBar.setOffset(110, 2) ;
  mapview.addMapDecoration(distAreaBar);
}

function showDistanceArea()
{
  var distArea = null ;
  if(distance)
    getDistance() ;
  else
    getArea() ;
}

function showArea(event)
{
  stopEvent(event) ;
  var button = document.getElementById('dist_area_button');
  button.innerHTML = "Distance" ;
  button.onmousedown = showDistance ;
  areaAction = function(area)
  {
    document.getElementById("dist_area").innerHTML = area ;
  }
  getArea() ;
  distance = false ;
}

function showDistance(event)
{
  stopEvent(event) ;
  var button = document.getElementById('dist_area_button');
  button.innerHTML = "Area" ;
  button.onmousedown = showArea ;
  distAction = function(length)
  {
    document.getElementById("dist_area").innerHTML = length ;
  }
  getDistance() ;
  distance = true ;
}

function getArea(line)
{
  var coords = redline.getOrdinates() ;
  coords = coords.slice() ;
  coords.push(coords[0]) ;
  coords.push(coords[1]) ;
  var line = MVSdoGeometry.createPolygon(coords, mapview.getSrid()) ;
  var area = line.getArea("ACRE", true, null, areaCallBack);
}

function areaCallBack(area)
{
  if(area>640)
    area = Math.round(area/64)/10+" sq miles" ;
  else if(area>=0.1)
    area = Math.round(area*10)/10 + " acres";
  else 
  {
    area *= 43560 ;
    area = Math.round(area) + " sq feet";
  }
  areaAction(area) ;
}

function getDistance(line)
{
  var line = MVSdoGeometry.createLineString(redline.getOrdinates(), mapview.getSrid()) ;
  line.getLength("MILE", true, null, distCallBack);
}

function distCallBack(length)
{
  if(length>100)
    length = Math.round(length)+" miles" ;
  else if(length>=0.1)
    length = Math.round(length*100)/100 + " miles";
  else 
  {
    length *= 5280 ;
    length = Math.round(length) + " feet";
  }
  document.getElementById("distarea_bar").innerHTML = length ;
}

function stopMeasuringDistance()
{
  lastMouseLoc = null ;
  redline.clear() ;
  mapview.removeFOI("distance_window");
  document.getElementById("distarea").checked = false ;
  return false ;
}

function stopEvent(evt)
{
  if(!evt)
    evt = window.event ;
   if(evt)
  {
    if(evt.stopPropagation) 
      evt.stopPropagation();
    else
      evt.cancelBubble = true;
  
    //prevent event default
    if (evt.preventDefault)
      evt.preventDefault();
    else
      evt.returnValue = false;     
  }
}

function checkEnter(e, func, param)
{
  var numCharCode;
  if (!e) var e = window.event;
  if (e.keyCode) numCharCode = e.keyCode;
  else if (e.which) numCharCode = e.which;
  if ( numCharCode == 13)
  {
    func(param) ;
    return false ;
  }
  return true ;  
}

function addSearchIcons()
{
  var node1 = null ;
  var node2 = null ;  
  if(isIE && !isIE7)
  {
    node1 = document.createElement("div") ;
    node1.style.position="absolute";
    node1.style.width="16px" ;
    node1.style.border="0";
    node1.style.cursor="pointer" ;
    node1.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/search.png', sizingMethod='scale')" ;
    node2 = document.createElement("div") ;
    node2.style.position="absolute";
    node2.style.width="16px" ;
    node2.style.border="0";
    node2.style.cursor="pointer" ;
    node2.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/search.png', sizingMethod='scale')" ;
  }
  else
  {
    node1 = document.createElement("img") ;
    node1.style.width="16px" ;
    node1.style.border=0;
    node1.src = "images/search.png" ;
    node2 = document.createElement("img") ;
    node2.style.width="16px" ;
    node2.style.border=0;
    node2.src = "images/search.png" ;
  }
  document.getElementById("search_icon1").appendChild(node1) ;
  document.getElementById("search_icon2").appendChild(node2) ;
}

function openwindowlink(fileName, title){
  newwin = window.open(fileName, title," height=700,width=600,scrollbars,resizable") ;
}
