$BP = BrowserPlus;

var Strings = {
  inactive : "Drag vCards From Desktop",
  active   : "Drop 'em Here!"
};

function setDropAreaText(txt) {
  var div = document.getElementById("drop-zone");
  while (div.firstChild) div.removeChild(div.firstChild);
  var p = document.createElement("p");
  p.innerHTML = txt;
  div.appendChild(p);
}

function hovering(hoverOn) {
  if (hoverOn) {
    console.log("asdfs")
    setDropAreaText(Strings['active']);
    document.getElementById("drop-zone").className = "active";
  }
  else {
    setDropAreaText(Strings['inactive']);
    document.getElementById("drop-zone").className = "inactive";
  }
} 

function dropped(args) {
  var div = document.getElementById("results");
  while (div.firstChild) div.removeChild(div.firstChild);

  var textarea = document.createElement("textarea");
  textarea.cols = "40";
  textarea.rows = "5";
  textarea.value = '';

  for (var i = 0; i < args.length; i++) {
    console.log(args);
    BrowserPlus.FileAccess.Read(  
    { file: args[i] },  
    function (result) { 
      console.log(result)
      if (result.success) {  
        var hcard = document.createElement("div");
        var html = vCard.initialize(result.value).to_html();
        textarea.value += html;
        hcard.innerHTML = html;
    
        div.appendChild(hcard);
        div.appendChild(document.createElement("br"));
      } else {  
        contents = result.error + ": " + result.verboseError;  
      }  
      //textArea.value = contents;  
    });
  }
  var h3 = document.createElement("h3");
  h3.innerHTML = "HTML Output (Copy-paste this into your web page)";
  div.appendChild(h3);
  div.appendChild(textarea);
  
  document.getElementById("drop-zone").className = "inactive";
}

BrowserPlus.init(function(res) {
  if (res.success) {
    BrowserPlus.require(
      {services: [
        {service: 'DragAndDrop'},  
        {service: 'FileAccess'}  
      ]},

      function(res) {
        if (res.success) {
          console.log("Success");
          var dnd = BrowserPlus.DragAndDrop;
          dnd.AddDropTarget(
            {id: "drop-zone"
            // mimeTypes: ["application/vcard", "text/x-vcard", "text/directory;profile=vCard", "text/directory", "application/unknown", "application/octet-stream"]
            },
            function(res) {
              dnd.AttachCallbacks({
                                    id:     "drop-zone",
                                    hover:  hovering,
                                    drop:   dropped
                                  },
                                  function(){});
              setDropAreaText(Strings['inactive']);
            });
        } else {
          alert("Error Loading Corelets: " + res.error);
        }
      });
  } else {
    alert("Failed to initialize BrowserPlus: " + res.error);
  }
}); 