// click2dl.js
// Usage:
// 1) add a form element: <body onload="AddForm(&quot;theForm&quot;);">
//    (or add a call to AddForm to your onload function)
// 2) for each (preferably img) element add:
//    <a name="#UniqueName" class="clickwrap" href="#UniqueName"><img ... /></a>
//    where UniqueName should be replaced with some identifier that is unique
//    to the img element
// 3) include: <link rel="stylesheet" type="text/css" href="click2dl.css" />
//    in <head> (defines clickwrap and imgclick style classes)
// 4) may have to add class="imgclick" to images to remove their borders
//    (if img already has a class, append imgclick: class="class1 imgclick")
function ClickToDownload(id,name,local)
{
// check for license cookie
 // alert("start ClickToDownload: "+document.URL);

if (checkLicense(document.URL))  // from license.js
{
  // id is the id of the form we are using
  // set local to true to have the http stripped off of name
  if (id)
  {
    var frm = document.getElementById(id);
    if (frm)
    {
      // name is a full url typically, strip http://<server>/
      // saveas3.php will accept either of these:
      if (local==null || local==true)
        basename=name.replace(/http:\/\/[^/]*\//,"");
      else
        basename=name;
      frm.action = "/cgi-bin/php/saveas3.php?link="+basename;
      frm.enctype = "application/x-www-form-urlencoded";
      var retval = frm.submit();
//	  alert("ClickToDownload: "+retval+" "+document.URL);
    }
  }
}
} // end ClickToDownload

function AddForm(id)
{
  var frm = document.createElement("form");
  frm.id = id;
  frm.name = id;
  frm.method = "post";
  frm.enctype = "application/octet-stream";
  frm.action = "saveas3.php";
  document.body.appendChild(frm);
} // end AddForm

function WrapToClick(id,formid,srcname)
{ // input: id of div that contains an image to be wrapped
  // get div with id
  var d = document.getElementById(id);
  if (d)
  {
    //alert("got "+d.id);
    // get first img element and remove it (hold on to it)
    var c = d.childNodes;
    var i = 0;
    while (i in c && (c[i].nodeType!=1 || c[i].tagName!="IMG"))
    {
      //alert(c[i].nodeType+" "+c[i].tagName+" "+c[i].nodeName);
      i++;
    }
    if (c[i].tagName=="IMG")
    {
      //alert("found "+c[i]);
      var ie = c[i];
      d.removeChild(ie);
      // append anchor child of div
      var ae = document.createElement("a");
      ae.name = "#"+id;
      ae.href = "#"+id;
      ae.className = "clickwrap";
      d.appendChild(ae);
      // append img child of anchor
      ie.className = "imgclick";
if (srcname==null)
      ie.onclick = function () {ClickToDownload(formid,this.src);};
else
      ie.onclick = function () {ClickToDownload(formid,srcname);};
      //ie.onclick = function () {alert("\""+formid+"\""+this.src);};
      ae.appendChild(ie);
    }
    //else alert("img not found");
  }  
} // end WrapToClick

