/**
* Javascript functions to support cite box / OpenURL functionality
* JQuery based.
* 
*/

$(document).ready(function(){

  // create div to house cite box
  $(".toolbox").append('<div class="cite-box-wrapper"></div>');

  // onclick of 'cite this' go get contents of box and display
  $(".cite-this-link").click(function(e){
    show_box($(this), " #cite-box-content .cite-box", e)
  });

});

function show_box(el, url, e)
{

  e.preventDefault();

  // instantiate jquery object
  var toolbox = el.parents(".toolbox");
  var cite_box = toolbox.children(".cite-box-wrapper"); 
  var toolbox_position = toolbox.position();

  // show loading spinner
  cite_box.html('<img class="cite-box-loading" src="/ourl/images/loading.gif" alt="loading"/>');

  // load cite box html into new div
  cite_box.load(el.attr('href') + nocache() + url, '', function(responseText, textStatus, XMLHttpRequest){

    var ok = false;

    // ajax request was a success
    if (textStatus == 'success')
    {

      // make returned data a jquery object
      var box = $(this);

      // set focus to the new box
      box.show().focus();

      // show the close button and have it close the box
      var close = box.find(".cite-box-close");

      // if close button found then page should be displayed properly
      if (close.length > 0) { 

        close.show();
        close.click(function(e){
          e.preventDefault();
          box.empty();
        });

        // automatically select all the text
        box.find("input").select();
  
        // everything is ok
        ok = true;

      }
    } 

    // something went wrong
    if (!ok) {
      problem(cite_box);
    }

    // position box
    cite_box.css('left', toolbox_position.left - cite_box.children().width() + toolbox.width());

  });

}

// tell user there was a problem
function problem(el)
{
  var email_address = 'error.report-rapport.erreur@lac-bac.gc.ca';
  el.html('<div class="problem"><p>An error has occurred, please contact <a href="mailto:' + email_address + '">' + email_address + '</a> to report the problem.</p><p>Une erreur s\'est produite, veuillez communiquer avec <a href="mailto:' + email_address + '">' + email_address + '</a> pour signaler le problème.</p><p class="problem-close"><a href="#" onclick="$(this).parents(\'.problem\').remove(); return false;">Close / Fermer</a></p></div>');
  el.focus();
}

// make sure IE doesn't cache the ajax response
function nocache()
{
  var d = new Date();
  return '&t=' + d.getTime();
}

