var randno = ''
var yaw = ''
var loc = ''
var pitch = ''
var zoom = ''
var temploc = ''
var templat = ''
var templng = ''
var diff = 0
var randno=parseInt(Math.random()*99999999);  // cache buster
var marker = [];
var pmarker = '';

function getQueryVariable(variable) { 
  var query = window.location.search.substring(1); 
  var vars = query.split("&"); 
  for (var i=0;i<vars.length;i++) { 
     var pair = vars[i].split("="); 
     if (pair[0] == variable) { 
          return pair[1]; 
     } 
   }
   return 0
} 

//query string variables
var sortby = getQueryVariable('sortby');
if (sortby==0) {
  var sortby = 'newest';
  }
var mycity = getQueryVariable('city');
if (mycity==0) {
  var mycity = '27';
  }
var mylimit = getQueryVariable('limit');

function startMap(latitude,longitude) {
  // sets the global variable related to the actual lat,long
  if (GBrowserIsCompatible()) {
    //global variables - initialise the map
    map = new GMap2(document.getElementById("map_canvas"));
    loc = new GLatLng(latitude,longitude)
    map.setCenter(loc, 14); //get the center of each city (start out with NYC)
    svOverlay = new GStreetviewOverlay();
    map.addOverlay(svOverlay);
    var myPano = new GStreetviewPanorama(document.getElementById("pano"));
    map.addControl(new GSmallMapControl());
    
    //set the streetview
    myPano.setLocationAndPOV(loc);
    
    //initialise the temporary locations
    temploc = '(' + latitude + ',' + longitude + ')';
    //var locte = temploc.replace("(","");
    //var locte = locte.replace(")","");
    //var loctarray = locte.split(",");
    //templat = loctarray[0];
    templat = latitude;
    //templng = loctarray[1];
    templng = longitude;
    
    //icons
    //Person icon
    var picon = new GIcon();
    picon.image = "http://www.mapofstrange.com/images/person.png";
    picon.iconSize = new GSize(16, 16);
    picon.iconAnchor = new GPoint(8, 8);
    
    pmarker = new GMarker(loc,picon);
    
    //flags
    var ricon = new GIcon();
    ricon.image = "http://www.mapofstrange.com/images/flag.png";
    //ricon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    ricon.iconSize = new GSize(16, 16);
    //ricon.shadowSize = new GSize(22, 20);
    ricon.iconAnchor = new GPoint(2, 14);
    //ricon.infoWindowAnchor = new GPoint(5, 1);
    
    //move the person icon around the map
    function myMan(latlng) {
      map.removeOverlay(pmarker);
      pmarker = new GMarker(latlng,picon);
      map.addOverlay(pmarker);
      //redoXml(latlng);
      }
    
    function redoXml(latlng) {
      var ll = latlng.toString()
      var loct = ll.replace("(","");
      var loct = loct.replace(")","");
      var locarray = loct.split(",");
      var tlat = locarray[0];
      var tlng = locarray[1];
    
      var diff = Math.abs(Math.abs(tlat-templat) + Math.abs(tlng - templng))
      if (diff >=0.004) {
        templat = tlat;
        templng = tlng;
        randno=parseInt(Math.random()*99999999);
        loc = new GLatLng(templat,templng)
        openXml();
        }
    }
    
    //what to do when the map gets moved
    function initialise(gd) {
      var loc = gd.latlng;
      var ll = loc.toString()
      setformloc(loc);
      // check whether to open a new XML file or not
      var loct = ll.replace("(","");
      var loct = loct.replace(")","");
      var locarray = loct.split(",");
      var tlat = locarray[0];
      var tlng = locarray[1];
      
      var pnt = new GLatLng(tlat,tlng);
      myMan(pnt);
      //move the center of the map and move the icon on the map
      }

    // write the values of the current view to the 'add point of interest' form
    // sets the global variable related to the rotation
    function yawch(tyaw) {
      var formyaw=document.getElementById('formyaw');
      formyaw.setAttribute("value", tyaw);
      yaw = tyaw;
      }
    // sets the global variable related to the zoom
    function zoomch(tzoom) {
      var formzoom=document.getElementById('formzoom');
      formzoom.setAttribute("value", tzoom);
      zoom = tzoom;
      }
    // sets the global variable related to the pitch
    function pitchch(tpitch) {
      var formpitch=document.getElementById('formpitch');
      formpitch.setAttribute("value", tpitch);
      pitch = tpitch;
      }
    //set the form location
    function setformloc(loc) {
      var formloc=document.getElementById('formloc');
      formloc.setAttribute("value", loc);
      }

    //put the markers on screen
    function createIconMarker(htmlStr,zoom,pitch,rotation,lat,lng) {
      //adds the marker
      var pnt = new GLatLng(lat,lng);
      var rmarker = new GMarker(pnt,ricon);
      
      //if the marker is clicked
      GEvent.addListener(rmarker, 'click', function() {
        myPOV = {yaw:rotation,pitch:pitch,zoom:zoom};
        myPano.setLocationAndPOV(pnt, myPOV); //needs to also set zoom etc
        map.setCenter(pnt, 14);
        myMan(pnt);
        var mapdetail=document.getElementById('mapdetail');
        while(mapdetail.hasChildNodes())
          {
          mapdetail.removeChild(mapdetail.childNodes[0]);
          }
        mapdetail.innerHTML = htmlStr;
        });
      return rmarker;
      }
    
    //read the XML file
    function openXml() {
      //alert('streetmap_xml.php?randno=' + randno + '&latlng=' + loc);
      // add markers at the locations specified in the XML file
      //GDownloadUrl('streetmap_xml.php?randno=' + randno + '&latlng=' + loc, function(data, responseCode){
      
      GDownloadUrl('streetmap_xml.php?randno=' + randno + '&latlng=' + loc + '&city_id=' + mycity + '&sortby=' + sortby + '&limit=' + mylimit, function(data, responseCode){
        var mxml = GXml.parse(data);
        var myList = '';
        var listid = document.getElementById('list');
        while(listid.hasChildNodes()){
          listid.removeChild(listid.childNodes[0]); 
          }
        
        var previous = 'NO';
        var next = 'NO';
          
        var markers = mxml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var htmlString = ''
          //lat/longitudes
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var llstring = '(' + lat + ',' + lng + ')';
          var point = new GPoint(lat,lng);
          
          //variables read from the XML file - lat, long, added by, title, description, created etc
          var mapRefId=markers[i].getAttribute("mapRefId");
          var user = markers[i].getAttribute("created_by");
          var created = markers[i].getAttribute("created");
          var theTitle = markers[i].getAttribute("title")
          var theDesc = markers[i].getAttribute("desc")
          var rotation = markers[i].getAttribute("rotation")
          var zoom = markers[i].getAttribute("zoom")
          var pitch = markers[i].getAttribute("pitch")
          
          var j = i + 1;
          var myList = myList + '<div class="listitem" onMouseOver="this.className=\'listitemo\'" onMouseOut="this.className=\'listitem\'" ';
          var myList = myList + ' onClick="javascript:GEvent.trigger(marker[' + i + '],\'click\');">';
          var myList = myList + '<p><b>' + j + '. '+ theTitle + '</b></p></div>';
          
          //HTML to put onto the screen
          var htmlString = '<h4><img src="../images/flag.png" alt="go to here" border="0" onClick="javascript:GEvent.trigger(marker[' + i + '],\'click\');"> ' + theTitle + '</h4>'
          var htmlString = htmlString + '<p>' + theTitle + '<br/>' + theDesc + '</p>'
          var htmlString = htmlString + '<span class="added_by">Added by ' + user + ' <span class="small">[' + created + ']</span><br/>'
          var htmlString = htmlString + '<p><br/><a href="#" onClick="add_again();">Click here to add another entry</a>.</p>';
          //var htmlString = htmlString + '<span class="added_by"><a href="#" onClick="myPano.setLocationAndPOV(point);">View this record...</a></span>' // need to set POV using the zoom etc as well
          // add (lat,long) to an array
          marker[i] = createIconMarker(htmlString, zoom, pitch, rotation, lat, lng);
          //put the marker on screen
          //creates problems in IE...
          map.addOverlay(marker[i]);
          //alert(htmlString + ', ' +  zoom + ', ' +  pitch + ', ' +  rotation + ', ' + lat + ', ' + lng);
          var previous = markers[i].getAttribute("prev");
          var next = markers[i].getAttribute("next");
          }
          
        if (previous == 'NO') { }
        else {
          var myList = myList + '<a href="index.php?limit=' + previous + '&city=' + mycity + '">&lt;&lt;Previous</a> &nbsp;  &nbsp; '
          }
        if (next == 'NO') { }
        else {
          var myList = myList + '<a href="index.php?limit=' + next + '&city=' + mycity + '">Next&gt;&gt;</a>'
          }
        // order by buttons
        /*
        if (sortby == 'newest') {
        var myList = myList + '<br/><br/><a href="index.php?tag=' + myview + '&sortby=rated">Order this list by Top Rated</a>'
        }
        else {
        var myList = myList + '<br/><br/><a href="index.php?tag=' + myview + '&sortby=newest">Order this list in date order</a>'
        }*/

        if (myList == '') {
            var myList = '<div style="color:#fff;">We don\'t have any records here. Please try again.</div>';
            }
        listid.innerHTML = myList;
        });
      }
    
    //map initialisation (continued)
    GEvent.addListener(myPano, "error", handleNoFlash);  
    GEvent.addListener(myPano, "yawchanged", yawch);  
    GEvent.addListener(myPano, "zoomchanged", zoomch);  
    GEvent.addListener(myPano, "pitchchanged", pitchch);  
    GEvent.addListener(myPano, "initialized", initialise);  

    // click on the map - go to that location
    GEvent.addListener(map,"click", function(overlay,latlng) {
      
      myPano.setLocationAndPOV(latlng);
      //move the person icon
      setformloc(latlng);
      myMan(latlng);
      map.setCenter(latlng, 14);
    });

    // reset the 'viewing near' to the current location and load the XML file
    
    openXml();
    myMan(loc);
    setformloc(temploc);
  }
}

function handleNoFlash(errorCode) {
  if (errorCode == 'FLASH_UNAVAILABLE') {
    alert("Error: Flash doesn't appear to be supported by your browser");
    return;
  }
}  


//add the marker 
function add_marker() {    
  var latlong = document.getElementById("formloc").value;
  var zoom = document.getElementById("formzoom").value;
  var pitch = document.getElementById("formpitch").value;
  var yaw = document.getElementById("formyaw").value;
  var username = document.getElementById("formname").value;
  var title = document.getElementById("formtitle").value;
  var desc = document.getElementById("formdesc").value;
  var city = document.getElementById("formcity").value;
  var xmlfile = "add_marker.php?username=" + username + "&latlong=" + latlong + "&zoom=" + zoom + "&title=" + title + "&pitch=" + pitch + "&desc=" + desc + '&yaw=' + yaw + '&randno=' + randno + '&city=' + city;
//alert("add_comment.php?username=" + username + "&mapref=" + mapRef + "&comment=" + comment);

  if (window.ActiveXObject) {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); //creates a temporary active x object containing the contents of the XML file
    xmlDoc.onreadystatechange = function () {
      if (xmlDoc.readyState == 4){ 
        //if something is returned, refresh the comments and display a nice 'thanks'
        new_marker();//when the file has loaded call the 'typechanged' function
        }
      };
    xmlDoc.load(xmlfile); //load the XML
    //alert(document.getElementById("commentBox").value);   
    }
  // code for Mozilla, Firefox, Opera, etc.
  else if (document.implementation && document.implementation.createDocument)
    {
    xmlDoc=document.implementation.createDocument("","",null);  //create a temporary file containing the contents of the XML file
    xmlDoc.load(xmlfile);
    xmlDoc.onload=new_marker;  
    }
  //unsupported browsers
  else 
    {
    alert('sorry, but your browser is crap');          
    }     
  }

//HTML to render after the entry is added
function new_marker(){
  var mapadd=document.getElementById('mapdetail');
  while(mapadd.hasChildNodes())  {
    mapadd.removeChild(mapadd.childNodes[0]); 
    }

  var htmlStr = '<h4>Thanks</h4><p>Thanks for adding that record.  Try the site again soon to see if it\'s been added to the site.</p>';
  var htmlStr = htmlStr + '<p>Why don\'t you <a href="#" onClick="add_again();">add another</a>?</p>';
  var htmlStr = htmlStr + '<input type="hidden" name="zoom" value="0" id="formzoom"/>';
  var htmlStr = htmlStr + '<input type="hidden" name="yaw" value="0" id="formyaw"/>';
  var htmlStr = htmlStr + '<input type="hidden" name="pitch" value="0" id="formpitch"/>';
  var htmlStr = htmlStr + '<input type="hidden" name="loc" value="0" id="formloc"/>';
  var htmlStr = htmlStr + '<input type="hidden" name="city" value="' + mycity + '" id="formcity"/>'
  mapadd.innerHTML = htmlStr
}

//reset the form
function add_again()  {
  var mapadd=document.getElementById('mapdetail');

  while(mapadd.hasChildNodes()){
    mapadd.removeChild(mapadd.childNodes[0]); 
    }
  var htmlStr = 'Add an entry here: '
  var htmlStr = htmlStr + '  <form method="get" action="">'
  var htmlStr = htmlStr + '<input type="hidden" name="zoom" value="' + zoom + '" id="formzoom"/>'
  var htmlStr = htmlStr + '<input type="hidden" name="yaw" value="' + yaw + '" id="formyaw"/>'
  var htmlStr = htmlStr + '<input type="hidden" name="pitch" value="' + pitch + '" id="formpitch"/>'
  var htmlStr = htmlStr + '<input type="hidden" name="loc" value="' + loc + '" id="formloc"/>'
  var htmlStr = htmlStr + '<input type="hidden" name="city" value="' + mycity + '" id="formcity"/>'
  var htmlStr = htmlStr + 'Your Name: <input type="text" name="myname" value="" id="formname"/><br/>'
  var htmlStr = htmlStr + 'Title:  <input type="text" name="mytitle" value="" id="formtitle"/><br/>'
  var htmlStr = htmlStr + 'Description: <textarea cols="30" rows="3" name="mydesc" id="formdesc"></textarea><br/>'
  var htmlStr = htmlStr + '<input type="button" onClick="add_marker();" name="button" value="add" />'
  var htmlStr = htmlStr + '</form>'
  mapadd.innerHTML = htmlStr
}