// ==UserScript==
// @name           NRAOpapers update report / edit / ads linkage
// @namespace      http://nrao.edu/~kgroner/
// @description    Add links from the NRAOpapers ADS update report to both the edit form and the ADS record
// @include        https://staff.nrao.edu/php/library/retrieve_ads_update?*
// @require	   http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js
// ==/UserScript==

$(function() {

  var searchForm = null;

  unsafeWindow._resolveBibcodePaperId = function(bibcode, onresolved) {
    loadBibcodeResolverForm(function(form) {
	form.find('input[name="BibCode"]').val(bibcode);
	var postData = form.serialize();
	var formUrl = form.get(0).action;
	jQuery.post(formUrl, postData, function(data, status) {
	    if (status == 'success') {
	      var dData = $(data);
	      var resultRows = dData.find('table.data-element > tbody > tr');
	      if (resultRows.length > 1) {
		alert('unable to resolve bibcode: multiple papers found!');

	      } else if (resultRows.length < 1) {
		alert('unable to resolve bibcode: no papers found!');

	      } else {
		var paperId = resultRows.find('td:eq(1) > a').text();
		unsafeWindow.console.log('resolved: ', bibcode, '=', paperId);

		if (onresolved)
		  onresolved(bibcode, paperId);

	      }

	    } else {
	      alert('unable to resolve bibcode: ' + status + '\n' + data);

	    }

	  }, 'html');
      }
    );
  };

  var loadBibcodeResolverForm = function(onload) {
    if (searchForm == null) {
      var searchFrame = $('<iframe style="display: none;" />');
      searchFrame.appendTo('body');
      searchFrame.get(0).contentWindow.addEventListener('load', function() {
	  var searchFrameDoc = searchFrame.get(0).contentDocument;
	  searchForm = $('form', searchFrameDoc);
	  onload(searchForm);
	}, false);
      searchFrame.attr({ src: 'show_search' });

    } else {
      onload(searchForm);

    }
  };

  var resolveBibcodeRewriteAndActivateLinkSrc = (function(e) {
    var bibcode = $(e.target).attr('bibcode');
    _resolveBibcodePaperId(bibcode, function(bibcode, paperid) {
	$(e.target)
	  .attr({ href: 'show_edit_paper?paperid='+paperid })
	  .removeAttr('onclick');
	  open(e.target.href, e.target.target);
      }
    );
    e.preventDefault();
  }).toSource();
  $('<script type="text/javascript">_resolveBibcodeRewriteAndActivateLink = '+resolveBibcodeRewriteAndActivateLinkSrc+'</script>').appendTo('body');

  var style = $('<style type="text/css"></style>').appendTo('head').get(0);
  style.sheet.insertRule('.nraopapers-gm-link { white-space: nowrap; vertical-align: super; font-size: 80%; }', 0);

  $('.change-field-header:contains("bibcode") ~ .change-field-content')
    .each(function() {
      var bibcode = this.textContent || this.innerText;
      $('<a class="nraopapers-gm-link" target="adsTarget" href="http://adsabs.harvard.edu/abs/'+encodeURIComponent(bibcode)+'"> [ ads ] </a>').appendTo(this);
      $('<a class="nraopapers-gm-link" target="editTarget" href="#edit" onclick="_resolveBibcodeRewriteAndActivateLink(event);" bibcode="'+bibcode+'"> [ nrao ] </a>')
	.appendTo(this);
    }
  );

});


