// ==UserScript==
// @name          Craigslist image preview
// @namespace     http://jeffpalm.com/craigslist
// @description    View craigslist image previews
// @include       http://*craigslist.org/*
// ==/UserScript==

/*
 * Copyright 2006 Jeffrey Palm.
 */

var VERSION = 0.2;
var HOST = "jeffpalm.com";
//var HOST = "localhost/~jeff";

// --------------------------------------------------
// misc
// --------------------------------------------------

/**
 * String[tag] (Node) -> Node
 * Creates a new node.
 */
function $n(tag,on) {
  var e = document.createElement(tag);
  if (on) on.appendChild(e);
  return e;
}

/**
 * String[text] (Node) -> Node
 * Creates a new text node.
 */
function $t(text,on) {
  var e = document.createTextNode(text);
  if (on) on.appendChild(e);
  return e;
}

/**
 * Node Node -> Void
 * Inserts newNode before target.
 * http://lists.xml.org/archives/xml-dev/200201/msg00873.html
 */
function insertBefore(newNode,target) {
  var parent   = target.parentNode;
  var refChild = target; //target.nextSibling;  
  if(refChild) parent.insertBefore(newNode, refChild);
  else parent.appendChild(newNode);  
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function urlencode( plaintext )
{
  // The Javascript escape and unescape functions do not correspond
  // with what browsers actually do...
  var SAFECHARS = "0123456789" +          // Numeric
          "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +  // Alphabetic
          "abcdefghijklmnopqrstuvwxyz" +
          "-_.!~*'()";          // RFC2396 Mark characters
  var HEX = "0123456789ABCDEF";

  var encoded = "";
  for (var i = 0; i < plaintext.length; i++ ) {
    var ch = plaintext.charAt(i);
      if (ch == " ") {
        encoded += "+";        // x-www-urlencoded, rather than %20
    } else if (SAFECHARS.indexOf(ch) != -1) {
        encoded += ch;
    } else {
        var charCode = ch.charCodeAt(0);
      if (charCode > 255) {
          alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
                  "(URL encoding only supports 8-bit characters.)\n" +
              "A space (+) will be substituted." );
        encoded += "+";
      } else {
        encoded += "%";
        encoded += HEX.charAt((charCode >> 4) & 0xF);
        encoded += HEX.charAt(charCode & 0xF);
      }
    }
  } // for

  return encoded;
};

/**
 * Node[a] -> (Details -> Void)
 * Returns a new closure for the Ajax call.
 */
function newFunction(_a) {
  var a = _a;
  return function(details) {
    if (details.responseText) {
      //
      // The text is lines of links
      //
      src = details.responseText;
      ss = src.split("\n");
      if (ss) {
        //
        // Go thru the links
        // div will hold the new div below the links parent
        //
        var div;
        for (j=0; j<ss.length; j++) {
          s = ss[j];
          if (!s) continue;
          //
          // For the first time create the div to hold the links
          //
          if (!div) {
            var d = $n("div",a.parentNode);
            var br = $t(" ",a.parentNode);
            div = $n("div",a.parentNode);
          }
          //
          // Create the link and image and add them
          //
          var newA = $n("a",div);
          var img = $n("img",newA);
          img.src = s;
          img.style.width = "100px";
          img.style.height = "100px";
          $t(" ",div);
          newA.href = s;
        }
      }
    }
  };
}

function main() {
  //
  // find all the links to listings and display the images
  //
  var as = new Array();
  var links = document.getElementsByTagName("a");
  for (i=0; i<links.length; i++) {
    var link = links[i];
    if (link.href && link.href.match(/.*craigslist.org.*\/\d+\.html/)) {
      as.push(link);
    }
  }
  //
  // search all the images in all these links
  //
  for (i=0; i<as.length; i++) {
    var a = as[i];
    var href = a.href;
    if (!href) continue;
    GM_xmlhttpRequest({
      method:"GET",
          url:"http://"+HOST+"/craigslist/get_images.php?max=1&q=" 
          +   urlencode(href),
          headers:{
          "User-Agent":"monkeyagent",
            "Accept":"text/monkey,text/xml,text/plain",
            },
          onload: newFunction(a)
      });
  }
}

main();


