//Security Error: Content at http://www.doggiestyle.ie/loc/dsmaps.html may not load data from http://gazetteer.openstreetmap.org/namefinder/search.xml?find=cities%20near%2053.32355479748737%2c-6.366398620605482&max=2.
// ==================================================
/* the Where Am I button action... */
var maxdisplay = 10;

var nameds = new Array();
var nextnamed = 0;
var targetwidth = 0;
var bStopProcessing = false;

var whereamis = new Array('whereami1','whereami2','whereami3');

// --------------------------------------------------
function tellmewhereiam(lat,lon) {
  
  nameds = new Array();
  nextnamed = 0;

/* they pressed the 'where am i' button: get the lat/lon centre of the map and 
     look it up in th ename finder via Ajax */
//  var center = map.getCenter();
//  var lon = center.lon;
//  var lat = center.lat * 180.0 / 20037508.34;
//  lat = Math.atan( Math.exp(lat * (Math.PI / 180.0))) / (Math.PI / 360.0) - 90.0;
 // lon = lon * 180.0 / 20037508.34;

  /* we want to make sure we get at least some cities and towns; if we don't ask for these 
     separately we can get swamped with only lots of little nearby places */
	//53.275337275452806, -6.551404523849489
	//"http://gazetteer.openstreetmap.org/namefinder/search.xml?find=cities+near+53.275337275452806%2c-6.551404523849489&max=2"
  var url1 = "loadxml.asp?url=http://gazetteer.openstreetmap.org/namefinder/search.xml&find=cities%20near%20"+lat+"%2c"+lon+"&max=2";
  var url2 = "loadxml.asp?url=http://gazetteer.openstreetmap.org/namefinder/search.xml&find=towns%20near%20"+lat+"%2c"+lon+"&max=4";
  var url3 = "loadxml.asp?url=http://gazetteer.openstreetmap.org/namefinder/search.xml&find=places%20near%20"+lat+"%2c"+lon+"&max=10";
  loadxmldoc(url1, processwhereiam, 'whereami1');
  loadxmldoc(url2, processwhereiam, 'whereami2');
  loadxmldoc(url3, processwhereiam, 'whereami3');
}

// --------------------------------------------------
function processwhereiam() {

if (bStopProcessing == true){return};
  for (var w = 0; w < whereamis.length; w++) {
    if(! xmlcheckreadystate(xmlhttp[whereamis[w]])) { return; }
  }


  var bfirsttime = true;
  var sfinalArea = "";
  var sfinal10Areas = "";
  /* all three queries from tellmewhereiam completed,so process the results: firstly 
     collect the data we want from the subordinates of each of the result elements 
     into the top level of the results */

  for (var w = 0; w < whereamis.length; w++) {
    var nearbyplaces = xmlhttp[whereamis[w]].responseXML.documentElement;
    for (var i = 0; i < nearbyplaces.childNodes.length; i++) {
      var child = nearbyplaces.childNodes[i];
      if (child.nodeName == "named" && parseInt(child.getAttribute('rank')) > 0) {
        var id = child.getAttribute('id');
        for (var n = 0; n < nameds.length; n++) {
          if (nameds[n].getAttribute('id') == id) {
            // we've already seen it
            id = '0';
          }
        }
        if (id == '0') { continue; }
        if (child.getElementsByTagName("place").length == 0) { continue; }
        if (child.getElementsByTagName("place")[0].getElementsByTagName("named").length == 0) { 
          continue; 
        }
        var local = child.getElementsByTagName("place")[0].getElementsByTagName("named")[0];
        var distance = parseFloat(local.getAttribute("distance"));
        var approxdistance = parseFloat(local.getAttribute("approxdistance"));
        var direction = parseInt(local.getAttribute("direction"));
        child.setAttribute("distance", distance);
        child.setAttribute("approxdistance", approxdistance);
        child.setAttribute("direction", direction);
        nameds[nextnamed++] = child;
      }
    }
  }

  /* they would normally be sorted anyway, but we did it in 
     separate independently sorted queries,so we need to resort */

  nameds.sort(sortbyincreasingdistance);

  /* put the textual result in place */
  /*SJM Removed this
  var foundpanel = document.getElementById("foundpanel");
  if (nameds[0]) {
    var url = "<?php echo $config['maphref']; ?>?lat="+nameds[0].getAttribute("lat")+"&lon="+nameds[0].getAttribute("lon");
    foundpanel.innerHTML = "<p class='results'>"+ nameds[0].getElementsByTagName("description")[0].firstChild.data +"</p><p class='osmurl'>here's a url for it: <a href='"+url+"'>"+url+"</a>";
  } else {
    foundpanel.innerHTML = "<p>nothing found</p>";
    var sidepanel = document.getElementById("sidepanel");
    sidepanel.innerHTML = "";
    return;
  } */

  /* weight our results according to a combination of type of place
     and distance away, giving great preference to the
     nearest places of each type;sort by that weight */

  var firstofrank = 0;
  var myrank = new Array();
  myrank[10] = 1; // hamlet
  myrank[20] = 25; // village
  myrank[30] = 25; // suburb
  myrank[50] = 50; // town, small_town
  myrank[60] = 2000; // city
  myrank[70] = 2500; // metropolis

  for (var i = 0; i < nameds.length; i++) {
    var distance = parseFloat(nameds[i].getAttribute("distance"));
    if (distance < 0.1) { distance = 0.1; }
    var rank = myrank[parseInt(nameds[i].getAttribute("rank"))];
    var weight = rank / Math.sqrt(distance);
    if (rank > firstofrank) { 
      weight = weight * 20; 
      firstofrank = rank;
    }
    nameds[i].setAttribute("weight", weight);
  }

  nameds.sort(sortbydecreasingweight);

  /* pick out the first N highest weighted places, and note the farthest distance so we 
     can scale by this shortly */
  var results = new Array();
  if (nameds.length < maxdisplay) { maxdisplay = nameds.length; }
  var maxdistance = 0.0;
  for (var i = 0; i < maxdisplay; i++) {
    var distance = parseFloat(nameds[i].getAttribute("distance"));
    if (distance > maxdistance) { maxdistance = distance; }
    results[i] = nameds[i];
  }

  /* set up the target inage (concentric circles */
/*SJM Removed this
  
  var sidepanel = document.getElementById("sidepanel");
  if (targetwidth == 0) { targetwidth = parseInt(sidepanel.offsetWidth) - 10; }
  var targetheight = targetwidth;
  var xextent = targetwidth / 2.0;
  var yextent = targetheight / 2;
  sidepanel.innerHTML = "<div id='divtarget' class='divtarget'><img src='target.png' width='" + targetwidth + "' height='" + targetheight+ "' /><br /><br /><br /><br /><br /><br /><hr style='width: 50%;' /><div style='width: 100%; text-align: center;'>"+ parseInt(maxdistance+0.5) +"km</div></div>";
*/

  /* determine the cartesian coordinates of each place from their
     polar coordinates. For best presentation, then sort by the absolute
     distance aay horizontally from the target centre */

  for (var i = 0; i < maxdisplay; i++) {
    var distance = parseFloat(results[i].getAttribute("distance"));
    var direction = parseFloat(results[i].getAttribute("direction"));
    var x = Math.round(- distance * Math.cos(direction * Math.PI/180.0) /maxdistance * 1);
    var y = Math.round(distance * Math.sin(direction * Math.PI/180.0) /maxdistance * 1);
    results[i].setAttribute("x", x);
    results[i].setAttribute("y", y);
  }

  results.sort(sortbyabsx);

  /* Lay down the blob to mark the place. Then the complicated layout
     bit: divide the target into two columns, left and right, and
     however many rows are needed according to text line height. Try
     to put the text to the right of its blob if the blob is right of
     centre, or left if left of centre; but if that would go off the
     edge, reverse which side it is on. Mark the row/column as
     used. If we reversed, mark moth columns in the row as used. When
     we do the next one, if the row/column we need is used, alternate
     up and down until we find an unused location (both columns if
     required to fit the text), and in that case put a leader line to it */

  var takenleft = new Array();
  var takenright = new Array();
  var rowheight = 0;

  for (var i = 0; i < maxdisplay; i++) {
    var approxdistance = results[i].getAttribute("approxdistance");
    if (approxdistance == "0") { approxdistance = "<1"; }
    approxdistance = htmlspecialchars(approxdistance);
    var direction = parseFloat(results[i].getAttribute("direction"));
    var name = htmlspecialchars(results[i].getAttribute("name").replace(/ *\[.*\] */g, '')).replace(/ /g,'&nbsp;');
    var namefull = htmlspecialchars(results[i].getAttribute("name")).replace(/ /g,'&nbsp;');
    //var x = parseFloat(results[i].getAttribute("x")) + xextent;
    //var y = parseFloat(results[i].getAttribute("y")) + yextent;

/* SJM Removed
    var divtarget = document.getElementById("divtarget");
    var divplace = document.createElement("div");
    divtarget.appendChild(divplace);
    divplace.className = "placemarker";
    divplace.style.left = x + "px";
    divplace.style.top = y + "px";
    divplace.style.zIndex = "1";
*/
    var isin = results[i].getAttribute("is_in") ? " ( " + htmlspecialchars(results[i].getAttribute("is_in")) + ")" : "";
    var alt =  name + isin + " - " + approxdistance + "km";
	if ( bfirsttime == true){
	  bfirsttime = false;
	  sfinalArea = name;
	}else{
		sfinal10Areas = sfinal10Areas + "<br>"
	}
	sfinal10Areas = sfinal10Areas + alt;
  
/* SJM Removed
    divplace.innerHTML = "<img class='place' src='place.png' alt="+alt+" title="+alt+"/>";
    divtext = document.createElement("div");
    divtarget.appendChild(divtext);
    divtext.className = "placetext";
    divtext.innerHTML = name;
    var divtextlength = divtext.offsetWidth;
    if (rowheight == 0) { rowheight = parseFloat(divtext.offsetHeight); }
    var divtextrow = parseInt(Math.floor((y + rowheight/2)/rowheight));
    var yrow = divtextrow * rowheight;
    var adjustx = divplace.offsetWidth / 2.0 + 1;
    var thisadjustx = adjustx;
    var adjusty = - divplace.offsetHeight / 4.0;

    var sign = yrow > yextent ? 1 : -1;
    var inc = 1;
    var adjusted = 0;

    if (x < xextent) {
      if (x - divtextlength < 0) {
        while (takenleft[divtextrow] || takenright[divtextrow]) {
          divtextrow += sign * inc; sign = - sign; inc++;
          adjusted++;
          thisadjustx = -adjustx + 3;
        }
        takenleft[divtextrow] = takenright[divtextrow] = true;
        divtext.style.left = parseInt(x + thisadjustx) + "px";
        divtext.style.top = parseInt(divtextrow * rowheight + adjusty) + "px";
      } else {
        while (takenleft[divtextrow]) {          
          divtextrow += sign * inc; sign = - sign; inc++;
          thisadjustx = -adjustx;
          adjusted++;
        }
        takenleft[divtextrow] = true;
        divtext.style.right = parseInt(targetwidth - x + thisadjustx) + "px";
        divtext.style.top = parseInt(divtextrow * rowheight + adjusty) + "px";
      }
    } else {
      if (x + divtextlength > targetwidth) {
        while (takenleft[divtextrow] || takenright[divtextrow]) {
          divtextrow += sign * inc; sign = - sign; inc++;
          thisadjustx = -adjustx;
          adjusted++;
        }
        takenleft[divtextrow] = takenright[divtextrow] = true;
        divtext.style.right = parseInt(targetwidth - x + thisadjustx) + "px";
        divtext.style.top = parseInt(divtextrow * rowheight + adjusty) + "px";
      } else {
        while (takenright[divtextrow]) {
          divtextrow += sign * inc; sign = - sign; inc++;
          thisadjustx = -adjustx + 3;
          adjusted++;
        }
        takenright[divtextrow] = true;
        divtext.style.left = parseInt(x + thisadjustx) + "px";
        divtext.style.top = parseInt(divtextrow * rowheight + adjusty) + "px";
      }
    }

   // add leader line when we had to put the text on a different line from the blob 
   
    if (adjusted > 0) { 
      var leader = document.createElement("div");
      var texttop = parseInt(divtext.style.top);
      leader.style.width = "0";
      leader.style.height = parseInt(Math.abs(texttop + (texttop < y ? rowheight : 0) - y)) + "px";
      leader.style.position = "absolute";
      leader.style.border="1px solid #35E358";
      leader.style.top =  (texttop < y ? texttop + rowheight : y) + "px";
      leader.style.left = x + "px";
      leader.style.zIndex = "0";
      divtarget.appendChild(leader);
    }
*/
  }
  
  /* SJM Added*/
	//look at http://74.125.77.132/search?q=cache:4X1JHAO0lk8J:shiriru.blogspot.com/2007/10/flash-javascript-how-to-communicate.html+AS3+javascript+call+function&hl=en&ct=clnk&cd=3&gl=ie
	//for an explanation of whats happening
	var movie=getFlashMovie('DoggieStyle','DoggieStyle');
	movie.placesFoundJS(sfinalArea, sfinal10Areas);

}

// --------------------------------------------------
function sortbyincreasingdistance(a, b) {
  return parseFloat(a.getAttribute("distance")) - parseFloat(b.getAttribute("distance"));
}

function sortbydecreasingweight(a, b) {
  return parseInt(b.getAttribute("weight")) - parseInt(a.getAttribute("weight"));
}

function sortbyabsx(a, b) {
  return parseInt(Math.abs(parseFloat(a.getAttribute("x"))) - Math.abs(parseFloat(b.getAttribute("x"))));
}

// ==================================================
// ajax helperfunctions

function htmlspecialchars(s) {
  return s.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;');
}

var xmlhttp = new Array();

function loadxmldoc(url, response, i) {
if (bStopProcessing == true){return};
try
{

  xmlhttp[i]=null;
  if (window.XMLHttpRequest) { xmlhttp[i]=new XMLHttpRequest(); } // Mozilla etc
  else if (window.ActiveXObject) { xmlhttp[i]=new ActiveXObject("Microsoft.XMLHTTP"); } // IE
  if (xmlhttp[i] != null) {
    xmlhttp[i].onreadystatechange = response;
    xmlhttp[i].open("GET",url,true);
    xmlhttp[i].send(null);
  } else {
    alert("You are not using a suitable browser");
  }
 }
catch(e)
{
	bStopProcessing = true;
//	alert("Error opening XMLHttpRequest.\n"+ e); // show error
	var movie=getFlashMovie('DoggieStyle','DoggieStyle');
	movie.placesNotFoundJS("Error opening XMLHttpRequest.\n"+ e);

}
}
function xmlcheckreadystate(obj) {
  if(obj.readyState == 4) {
    var internalerror = false;
    if(obj.status == 200) {  
      if (obj.responseText.substring(0,5) == '<'+'?xml') { return true; }
      //alert("Problem retrieving data: bad or incomplete xml? javascript error?"); 
		bStopProcessing = true;
	  	var movie=getFlashMovie('DoggieStyle','DoggieStyle');
		movie.placesNotFoundJS("Problem retrieving data: bad or incomplete xml? javascript error?");

      return false;
    }
    if(obj.status == 500) { 
      //alert("server said error status 500"); 
		bStopProcessing = true;
	  	var movie=getFlashMovie('DoggieStyle','DoggieStyle');
		movie.placesNotFoundJS("server said error status 500");
    } else {
      //alert("Problem retrieving data: has you internet connecton gone down? Server crashed?");
		bStopProcessing = true;
	  	var movie=getFlashMovie('DoggieStyle','DoggieStyle');
		movie.placesNotFoundJS("Problem retrieving data: has you internet connecton gone down? Server crashed?");
    }
  }
  return false;
}
// ==================================================
/* window/object helper functions */

function windowWidth() {
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    return (window.innerWidth);
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return (document.documentElement.clientWidth);
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return (document.body.clientWidth);
  }
}
function windowHeight() {
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    return (window.innerHeight);
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    return (document.documentElement.clientHeight);
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    return (document.body.clientHeight);
  }
}
function findtop(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    curtop = obj.offsetTop;
    while (obj = obj.offsetParent) {
      curtop += obj.offsetTop;
    }
  }
  return curtop;
}

function getFlashMovie(objectId,embedId) {
  return (window[objectId]) ? window[objectId] 
              : document[embedId];
}


