/**
 * This function is used in conjunction with filechooser.js to link two files together
 *
 * Requires an element called 'sourceObjectId' to have its value set in the webpage
 * */

function doLink(params)
{
  var listToUpdate = '#linkUList';

  if (this.params != undefined && this.params.listToUpdate !== undefined)
  {
    listToUpdate = this.params.listToUpdate;
  }

  var linkURL = "../servlets/fileapi?method=createLink";
  var sinkObjectId = this.filechooser.documentRecord.id;
  var sinkObjectName = this.filechooser.documentRecord.label;
  var sourceObjectId = $('#sourceObjectId').val();

  if (sinkObjectName != null && sinkObjectName != "" && sinkObjectId != null && sinkObjectId != "" && sourceObjectId != null && sourceObjectId != "")
  {
    var callData = {file: sinkObjectName, sinkObjectId: sinkObjectId, sourceObjectId: sourceObjectId};
    var callString = YAHOO.lang.JSON.stringify(callData);


    //prepare our callback object
    var callback = {

      success: function(oResponse)
      {
        //get the results into a JS assoicative array
        var oResults = eval("(" + oResponse.responseText + ")");


        //deal with the response
        if ((oResults.Result == "success"))
        {
          //link succeded

          var color = '#2D962D';
          var text = 'Link Created';
          var element = document.getElementById('linkStatus');
          notifyStatus(color, text, element);
          if ($(listToUpdate).length)
          {
            $(listToUpdate).append('<li id="link_' + oResults.sinkId + '">' + oResults.Link + '</li>');
          }
        }
        else
        {
          //link failed
          var color = '#D24747';
          var text = 'Link failed';
          var element = document.getElementById('linkStatus');
          notifyStatus(color, text, element);
        }
      },

      //log failure
      failure: function(oResponse)
      {
        alert("XHR call failed");
      },

      timeout: 7000
    };

    //call the server to store the link
    YAHOO.util.Connect.asyncRequest('POST', linkURL, callback, callString);
    this.filechooser.panel.hide();
  }
  else
  {
    alert("Please specify a file to link from and to");
  }
}


function deleteLink(sourceObjectId, sinkObjectId)
{

  if (sourceObjectId != undefined && sinkObjectId != undefined)
  {
    // Define various event handlers for Dialog
    var handleYes = function()
    {
      this.hide();
      var linkURL = "../servlets/fileapi?method=deleteLink";

      var callData = {sourceId: sourceObjectId, sinkId: sinkObjectId};
      var callString = YAHOO.lang.JSON.stringify(callData);

      //prepare our callback object
      var callback = {

        success: function(oResponse)
        {
          //get the results into a JS assoicative array
          var oResults = eval("(" + oResponse.responseText + ")");


          //deal with the response
          if ((oResults.Result.result === "success"))
          {
            //delete link succeded
            var deletedLinkId = '#link_' + oResults.Result.linkId;

            if ($(deletedLinkId).length)
            {
              $(deletedLinkId).remove();
            }
          }
          else
          {
            //delete link failed
            alert("Deleting attachment failed");
          }
        },

        //call failure
        failure: function(oResponse)
        {
          alert("XHR call failed " + oResponse);
        },

        timeout: 7000
      };

      //call the server to store the link
      YAHOO.util.Connect.asyncRequest('POST', linkURL, callback, callString);
    };

    var handleNo = function()
    {
      this.hide();
    };

    // Instantiate the Dialog
    var deleteDialog = new YAHOO.widget.SimpleDialog("si",
    { width: "300px",
      fixedcenter: true,
      visible: false,
      draggable: false,
      close: true,
      text: "Are you sure you want to delete the link?",
      icon: YAHOO.widget.SimpleDialog.ICON_HELP,
      constraintoviewport: true,
      buttons: [
        {
          text:"Yes",
          handler:handleYes,
          isDefault:true
        },
        {
          text:"No",
          handler:handleNo
        }
      ]
    });
    deleteDialog.setHeader("Are you sure?");

    // Render the Dialog
    deleteDialog.render("dialog");

    //display the dialog
    deleteDialog.show();
  }
}


function constructHyperLink(event, editorName)
{

  var ed = tinyMCE.get(this.params.editorName);
  var currentContent = ed.selection.getContent();
  var link = "";

  if (this.filechooser.documentRecord.path.match("/blogs/") !== null)
  {
    link = '<a href="../secure/viewpost.jsp?id=' + this.filechooser.documentRecord.id + '">';
  }
  else if (this.filechooser.documentRecord.path.match("/publications/") !== null)
  {
    link = '<a href="../secure/pubs.jsp?id=' + this.filechooser.documentRecord.id + '">';

  }
  else if (this.filechooser.documentRecord.path.match("/notes/") !== null)
    {
      link = '<a href="../secure/notes.jsp?id=' + this.filechooser.documentRecord.id + '">';
    }
    else
    {
      link = '<a href="../secure/dataproperties.jsp?id=' + this.filechooser.documentRecord.id + '">';
    }

  ed.selection.setContent(link + currentContent + "</a>");
  this.filechooser.panel.hide();
}

function constructInlineImage(event, editorName)
{

  var ed = tinyMCE.get(this.params.editorName);
  var currentContent = ed.selection.getContent();

  var imgSrc = '../servlets/download/' + this.filechooser.documentRecord.label + '?documentid=' + this.filechooser.documentRecord.id;
  ed.execCommand('mceInsertContent', false, '<img src="' + imgSrc + '" />', {skip_undo : 1});

  this.filechooser.panel.hide();
}
