//
// AJAX request against the Flickr API (using a PHP proxy script
// to get around browser sandbox).  
//
// First do the request, then parse the XML return document and
// spit HTML out into the requested block element ID.
//

function flickr(vars, divid) {

  var url = "flickr.php";

  if (window.XMLHttpRequest){
    var xml = new XMLHttpRequest();
  }
  else {
    var xml = new ActiveXObject("MSXML2.XMLHTTP.3.0");
  }
  
  xml.open("GET", url + vars, true);

  xml.onreadystatechange = function() {
  
    if (xml.readyState == 4 && xml.status == 200) {
      if (xml.responseXML){
        writepanel(divid, xml.responseXML);
      }
    }
  }
  xml.send("");
}

function writepanel(divid, xmldoc) {

  var picdiv = document.getElementById(divid);
  var pics = xmldoc.getElementsByTagName("photo");
  var html = "";

  for ( var i = 0; i < pics.length; i++ ) {

    var id = pics[i].getAttribute("id");
    var server = pics[i].getAttribute("server");
    var title = pics[i].getAttribute("title");
    var secret = pics[i].getAttribute("secret");
    var farm = pics[i].getAttribute("farm");
    var owner = pics[i].getAttribute("owner");

    var src = "http://farm";
    src += farm + ".static.flickr.com/";
    src += server + "/";
    src += id + "_";
    src += secret;
    src += "_s.jpg";

    var link = "http://www.flickr.com/photos/" + owner + "/" + id + "/";

    html += "<a href=\"" + link + "\""
    html += " target=\"fosspic\">";
    html += "<img";
    html += " src=\"" + src + "\"";
    html += " class=\"flickr\"";
    html += " alt=\"" + title + "\"";
    html += " /></a>";
  }

  picdiv.innerHTML = html;

}

//
// Example call for use in HTML  page
// First load this .js file in a <script> tag.
// Then call the function, as below. Note that the URL is
// a verbatim Flickr API call: anything in the FlickR API can be 
// passed in.
//
// ajax("flickr.php", "?method=flickr.photos.search&api_key=55ac739b48b32b4f964dd82efe5da72d&tags=foss4g2007&per_page=4");
//

