var currentPanoFile="";
var currentRefAngle=0;
var currentPan=0;
var currentTilt=0;
var currentFoV=80;
var housenumberlistboxtxt;

var isMinNS4 = (navigator.appName.indexOf("Netscape") >= 0 &&
                parseFloat(navigator.appVersion) >= 4) ? true : false;
var isMinNS6 = (navigator.appName.indexOf("Netscape") >= 0 &&
                parseFloat(navigator.appVersion) >= 5) ? true : false;
var isMinIE4 = (document.all) ? true : false;
var isMinIE5 = (isMinIE4 && (navigator.appVersion.indexOf("5.") >= 0)) ? true : false;

var hastry=isMinIE5 && (!isMinNS4);

function panoViewerBodyOnLoad()
{
  var pano=getVar("pano");
  var pantxt=getVar("pan");
  var tilttxt=getVar("tilt");
  var fovtxt=getVar("fov");
  if(pantxt != "")
  {
    currentPan=pantxt-0;
  }
  if(tilttxt!= "")
  {
    currentTilt=tilttxt-0;
  }
  if(fovtxt!= "")
  {
    currentFoV=fovtxt-0;
  }
  loadPanoFromFile(pano);
  if(pano == "")
  {
//    if(nopanoshotspot >= 0) 
//    {
//      alert("document.ptviewer.DrawSHSImage("+nopanoshotspot+")");
//      document.ptviewer.DrawSHSImage(nopanoshotspot);
//    }
  }
}

function pollView()
{
  getview(document.ptviewer.pan(),document.ptviewer.tilt(),document.ptviewer.fov());
}

function loadPanoFromList(i)
{
  var newfile;
  var newrefangle=0;
  if(i < numpanos)
  {
    newfile=panolist[i].toLowerCase();
    newrefangle=anglelist[i];
  }
  else
  {
    newfile="";
  }
  if(newfile != currentPanoFile)
  {
    if(currentPanoFile != "")
    {
      pollView();
    }
    document.ptviewer.newPanoFromList(i);
    currentPanoFile=newfile;
    currentRefAngle=newrefangle;
    document.ptviewer.gotoView(Math.floor(currentPan)-Math.floor(currentRefAngle) , currentTilt , currentFoV);
    if(nopanoshotspot >= 0) 
    {
      document.ptviewer.HideSHSImage(nopanoshotspot);
    }
  }
}

function loadPanoFromFile(filename)
{
  filename=filename.toLowerCase();
  if(currentPanoFile != filename)
  {
    for(var i=0;i < numpanos;i++)
    {
      if(panolist[i].toLowerCase() == filename)
      {
        break;
      }
    }
    loadPanoFromList(i);
  }
}

function navigateToFile(file)
{
  bodyOnUnload();
  location.replace(file);
}

function getVar(name)
{
  var s = document.location.search;
  return getVarFromSearchString(s,name);
}

function getVarFromUrl(url,name)
{
  var comps=url.split("?");
  if(comps.length < 2) return "";
  var s = "?"+comps[1];
  comps=s.split("#");
  s=comps[0];
  return getVarFromSearchString(s,name);
}

function getVarFromSearchString(s,name)
{
  s = "&"+s.substr(1,s.length-1);
  var p=s.indexOf("&"+name+"=");
  if(p >= 0)
  {
    s=s.substr(p+name.length+2,s.length-p-name.length-2);
    var pp=s.indexOf("&");
    if(pp >= 0)
    {
      s=s.substr(0,pp);
    }
    return(urlUnescape(s));
  }
  return "";
}

function urlUnescape(t)
{
  var tt="";
  var i;
  for (i=0; i<=t.length;i++)
  {
    var c=t.charAt(i);
    if(c == "+") c=" ";
    tt=tt+c;
  }
  return(unescape(tt));
}

function createViewer(appletwidth,appletheight,viewerwidth,viewerheight)
{
// the following code is to make sure that the progress bar is displayed at the right place
// even if the viewer window is larger or smaller than the wait image
// Written by Joost Nieuwenhuijse / joost@newhouse.nl
  var bar_x=99;
  var bar_y=187;
  var bar_width=202;
  var bar_height=10;
  var wait_width=398;
  var wait_height=250;
  
  bar_x = bar_x + Math.floor( (appletwidth-wait_width)/2 +0.5);
  bar_y = bar_y + Math.floor( (appletheight-wait_height)/2 +0.5);

  var tags="";
// the APPLET tag itself should be generated dynamically by Javascript too, otherwise
// IE ignores the PARAM tags that we are generating now. 
  tags += "<APPLET name=ptviewer archive=ptviewer.jar codebase=\"./\" code=ptviewer.class width=\""+appletwidth+"\" height=\""+appletheight+"\" mayscript=true>";
  tags += "<PARAM name=bar_x value=\""+bar_x+"\">\n";
  tags += "<PARAM name=bar_y value=\""+bar_y+"\">\n";
  tags += "<PARAM name=bar_width value=\""+bar_width+"\">\n";
  tags += "<PARAM name=bar_height value=\""+bar_height+"\">\n";
  tags += "<PARAM name=wait 	value=\"wait.jpg\">\n";
  tags += "<PARAM name=view_width 	value=\""+viewerwidth+"\">\n";
  tags += "<PARAM name=view_height value=\""+viewerheight+"\">\n";
  tags += "<PARAM name=view_x value=\"0\">\n";
  tags += "<PARAM name=view_y value=\"0\">\n";
  tags += "<PARAM name=cursor value=\"move\">\n";
  tags += "<PARAM name=bgcolor value=\"003F7F\">\n";
  return tags;
}

function fillListBox(listbox,texts,firsttxt)
{
  listbox.options[0]=new Option(firsttxt);
  for(var i=0;i<=texts.length;i++)
  {
    listbox.options[i+1]=new Option(texts[i]);
  }
  for(var i=listbox.options.length;i>texts.length;i--)
  {
    listbox.options[i]=null;
  }
  listbox.selectedIndex=0;
}

function emptyListBox(listbox)
{
  for(var i=listbox.options.length;i>=0;i--)
  {
    listbox.options[i]=null;
  }
  listbox.selectedIndex=0;
}



function htmlEncode(s)
{
  // to do
  return s;
}

function createStreetListbox(streettxt,numbertxt)
{
  var tags="";
  housenumberlistboxtxt=numbertxt;

  tags += "<select name=streets onChange=\"streetChanged(this.selectedIndex,this.form.housenumbers);\"><option selected>"+htmlEncode(streettxt)+"</option>";
  for(var i=0;i<streets.length;i++)
  {
    tags += "<option>"+htmlEncode(streets[i])+"</option>";
  }
  tags += "</select>";

  tags += "<select name=housenumbers onChange=\"housenumberChanged(this.form.streets.selectedIndex,this.selectedIndex);\"><option>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>";
  tags += "</select>";
  return tags;
}

function streetChanged(streetno,housenumberslistbox)
{
  if(streetno > 0)
  {
    fillListBox(housenumberslistbox,housenumbers[streetno-1],housenumberlistboxtxt);
  }
  else
  {
    emptyListBox(housenumberslistbox);
  }
}

function housenumberChanged(streetno,housenumberno)
{
  if(streetno < 1) return;
  if(housenumberno< 1) return;
  var urllist=urls[streetno-1];
  var url=urllist[housenumberno-1];
  if( (window.opener) && (!window.opener.closed) )
  {
    if( (window.opener.bodyLoaded) && (extractFileNameFromLocation(window.opener.location.href) == extractFileNameFromLocation(url)))
    {
      var newpano=getVarFromUrl(url,"pano")
      var newangle=0;
      var hasangle=false;
      if(getVarFromUrl(url,"angle") != "")
      {
        hasangle=true;
        newangle=getVarFromUrl(url,"angle");
      }
      window.opener.openPanoramaFile(newpano,hasangle,newangle);      
    }
    else
    {
//alert(url);
      window.opener.location.replace(url);
    }
  }
  else
  {
    window.opener=null;
    window.opener=window.open(url,"citytour_main");
  }
}

function extractFileNameFromLocation(p)
{
  var comps=p.split("#");
  p=comps[0];
  comps=p.split("?");
  p=comps[0];
  comps=p.split("/");
  if(comps.length < 1) return p;
  var filename;
  if(comps.length > 1)
  {
    filename=comps[comps.length-2]+"/"+comps[comps.length-1];
  }
  else
  {
    filename=comps[comps.length-1];
  }
  return filename;
}

function getScreenWidth()
{
  var w=800;

  if( parseInt ( navigator.appVersion ) >= 4 )
  {
    if(screen)
    {
      if(screen.width)
      {
        w=screen.width;
      }
    }
  }
  return w;
}

function getScreenHeight()
{
  var w=600;

  if( parseInt ( navigator.appVersion ) >= 4 )
  {
    if(screen)
    {
      if(screen.height)
      {
        w=screen.height;
      }
    }
  }
  return w;
}

var popupwin=null;
var sayHelloTimer=null;
var currentCompassFile="";
var currentCompassFileIsOnMap=false;

function openPanoramaFile(filename,setangle,angle)
{
  var i=findPanorama(filename);
  if(i >= 0)
  {
    openPanorama(i,setangle,angle)
  }
}

function openPanorama(index,setangle,angle)
{
  if(!setangle) setangle=false;  // un-null;
  angle -= 0;
  hideCompass();
  currentCompassFile="";
  currentCompassFileIsOnMap=false;
  var filename=panolist[index];
  var north=anglelist[index];
  if(1 || (!popupwin) || (popupwin.closed) || (!popupwin.bodyloaded) || (popupwin.document.ptviewer.getAutoPan()) )
  {
    if(sayHelloTimer) clearTimeout(sayHelloTimer);
    sayHelloTimer=null;
    popupwin=null;
    onSayHelloTimer();  // schedule
//    popupwin = window.open("","citytour_viewer",'fullscreen=1,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1');
//    self.focus();
//    popupwin.resizeTo(viewerwidth,viewerheight);
//    popupwin.moveTo((getScreenWidth()-viewerwidth)/2,(getScreenHeight()-viewerheight)/2);

    popupwin = window.open("","citytour_viewer","fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width="+viewerwidth+",height="+viewerheight);
    var l="../pano/pano.html?pano="+filename+"&north="+north+"&setangle="+(setangle? 1:0)+"&angle="+angle;
//    alert(l);
    popupwin.location=l;
  }
  else
  {
    onSayHelloTimer();
    if(hastry)
    {
      tryEval("popupwin.startPano('"+filename+"',"+north+","+setangle+","+setangle+","+angle+")");
    }
    else
    {
      popupwin.startPano(filename,north,setangle,setangle,angle);
    }
  }
  popupwin.focus();
}

function tryEval(f)
{
  if(hastry)
  {
    f="try{"+f+"}catch(e){}";
  }
  eval(f);
}

// this function tries to pass our own window handle to the viewer window
// will try this every second until succeeding
function onSayHelloTimer()
{
//  return;
  
  sayHelloTimer=setTimeout("onSayHelloTimer()",2000);
  if(popupwin)
  {
    if(!popupwin.closed)
    {
      if(popupwin.bodyloaded)
      {
        if( isMinNS4 || ((typeof popupwin.setCaller)=="object"))
        {
          if(hastry)
          {
            tryEval("popupwin.setCaller(window);");
          }
          else
          {
            popupwin.setCaller(window);
          }
          // success; we don't set the timer again
//          clearTimeout(sayHelloTimer);
          return; 
        }
      }
    }
  }
}

// call this before this document is closed
// we notify the viewer window that we're gone
function bodyOnUnload()
{
  bodyLoaded=false;
  if(popupwin)
  {
    if(!popupwin.closed)
    {
      if(popupwin.bodyloaded)
      {
//        popupwin.setCaller(null);
      }
    }
  }
}

function bodyOnLoad()
{
  bodyLoaded=true;
  if(getVar("pano") != "")
  {
    var newpano=getVar("pano");
    var newangle=0;
    var hasangle=false;
    if(getVar("angle") != "")
    {
      hasangle=true;
      newangle=getVar("angle");
    }
    var cmd="openPanoramaFile(\""+newpano+"\","+hasangle+","+newangle+");";
//    alert(cmd);
    setTimeout(cmd,1100);
  }
}

function findPanorama(filename)
{
  for(var i=0;i<panolist.length;i++)
  {
    if(panolist[i] == filename)
    {
      return i;
    }
  }
  return -1;
}

function viewerIsClosed()
{
  popupwin=null;
  hideCompass();
}

var hideCompassTimer=null;
// called by the viewer window
function setCompass(filename,angle,w)
{
//  window.status=filename+","+angle;
  if(!bodyLoaded) return;
  if(hideCompassTimer)
  {
    clearTimeout(hideCompassTimer);
  }
  if(sayHelloTimer) 
  {
    // the viewer is calling us, so we don't need to say hello
    clearTimeout(sayHelloTimer);
    sayHelloTimer=null;
  }
  popupwin=w;
  if(filename != currentCompassFile)
  {
    if(panolist)
    {
      currentCompassFile=filename;
      currentCompassFileIsOnMap=false;
      for(var i=0; i<panolist.length; i++)
      {
        if(panolist[i] == filename)
        {
          currentCompassFileIsOnMap=true;
          moveCompass(compassx[i],compassy[i]);
        }
      }
    }
  }
  if(currentCompassFileIsOnMap)
  {
    rotateCompass(angle);
  }
  hideCompassTimer=setTimeout("onHideCompassTimer()",2000);
}

// hide the compass if we don't receive a compass update within 2 seconds
// after the last update.
function onHideCompassTimer()
{
//  hideCompass();
}

var compassvisible=false;
function showCompass()
{
  if(!compassvisible)
  {
    var l=getLayer("compasslayer");
    showLayer(l);
    compassvisible=true;
  }
}

function hideCompass()
{
  if(compassvisible)
  {
    var l=getLayer("compasslayer");
    hideLayer(l);
    compassvisible=false;
  }
}

function moveCompass(x,y)
{
  var l1=getLayer("compasslayer");
  var l2=getLayer("maplayer");
  x -= 0;
  y -= 0;
  x+=(getPageLeft(l2)-0);
  y+=(getPageTop(l2)-0);
//  y -= getHeight(l2);
//  y += getHeight(l1);
  moveLayerTo(l1,x,y);
}

var lastangle=-1;
function rotateCompass(angle)
{
  while(angle < 0) angle += 360;
  angle=Math.floor((angle+10)/20)*20;
  while(angle >= 360) angle -= 360;
  if(angle == 0) angle="0";
  if(isNaN(angle))
  {
    hideCompass();
  }
  else
  {
    var imagefile="../images/compass"+angle+".gif";
    if(angle != lastangle)
    {
//    getLayer("compasslayer").compassimage.src=imagefile;
//      document.compassimage.src=imagefile;
//      document.images["compassimage"].src=imagefile;
  var l1=getLayer("compasslayer");
        l1.document.compassimage.src=imagefile;
      lastangle=angle;
    }
    showCompass();
  }
}
