<?php
function saveAsCopy_addJavascript() {

  // only show for add/edit pages
  if (!@$GLOBALS['tableName']) { return; }
  if (!in_array(@$GLOBALS['action'], array('add','edit'))) { return; }

  // add javascript -------------------------------------------------------------------------
?><script type="text/javascript"><!--

// create function - or append code to existing function
if (typeof('edit_postSave') == 'function') {
  pre_saveAsCopy_function = edit_postSave;
  edit_postSave = function(recordNum) {
    pre_saveAsCopy_function(recordNum);
    saveAsCopy_postSave(recordNum);
  };
}
else {
  edit_postSave = saveAsCopy_postSave;
}


//
function saveAsCopy_postSave(recordNum) {
  // only run this code if "Save As Copy" button has been clicked
  if (typeof(window.SAVE_AS_COPY_CLICKED) === 'undefined') { return false; }
  window.SAVE_AS_COPY_CLICKED = undefined;

  //
  var tableName = '<?php echo escapeJs($GLOBALS['tableName']) ?>';
  saveAsCopy_resetEditForm(tableName, recordNum);
  return true;
}


//
function saveAsCopy_resetEditForm(tableName, recordNum) {

  // reset num and preSaveTempId
  var pseudoRandomNumber = new Date().getTime();
  $('#num').val('');
  $('#preSaveTempId').val( pseudoRandomNumber );

  // Copy uploads from
  //alert("Debug: Copy uploads from " +recordNum+ " to " +pseudoRandomNumber );
  var copyUploadsUrl = '?_plugin=saveAsCopy&_pluginAction=copy&menu=' +escape(tableName)+ '&recordNum=' +escape(recordNum)+ '&preSaveTempId=' +escape(pseudoRandomNumber)+ '&ajax=1';
  $.ajax({
    url: copyUploadsUrl,
    success: function(errorMessage){
      if (errorMessage)   { return alert("Error: " + errorMessage); }

      // refresh upload lists
      //<iframe id="upload_iframe" src="?menu=every_field&amp;action=uploadList&amp;fieldName=upload&amp;num=1&amp;preSaveTempId=
      $("iframe[id$='_iframe']").each(function(index) {
        var newSrc  = $(this).attr('src');
        newSrc = newSrc.replace(/num=\w*/, 'num=');
        newSrc = newSrc.replace(/preSaveTempId=\w*/, 'preSaveTempId=' + pseudoRandomNumber);
        $(this).attr('src', newSrc);
      });
      // end: refresh upload lists

    },
    error:  function(XMLHttpRequest, textStatus, errorThrown){
      alert("There was an error sending the ajax request! (" +XMLHttpRequest['status']+" "+XMLHttpRequest['statusText'] +", " +textStatus+ ", " +errorThrown+ ")");
    }
  });

  // Add "Copy of " to first text field or text box
  var selector = "input[type=text]:visible:first";
  var oldValue = $(selector).val();
  var newValue = "<?php echo escapeJs(t('Copy Of ')); ?>" + oldValue;
  $(selector).val(newValue);

  // update upload links
  // eg: <a href="?menu=every_field_multi&amp;action=uploadForm&amp;fieldName=upload&amp;num=2&amp;preSaveTempId=&amp;TB_iframe=true&amp;height=350&amp;width=700&amp;modal=true" class="thickbox"><b>Add or Upload File(s)</b></a>
  $("a[href*='uploadForm']").each(function() {
    this.href = this.href.replace(/\bnum=[^&]*/,           "num=");
    this.href = this.href.replace(/\bpreSaveTempId=[^&]*/, "preSaveTempId=" +escape(pseudoRandomNumber) );
  });

  // update all uploadify flash objects // match: <div id="fieldname_uploadButton"></div>
  $("div[id$='_uploadButton']").each(function() {
    var jselector = '#'+this.id;
    //window.console && console.log(  $(jselector).uploadifySettings('scriptData') );
    $(jselector).uploadifySettings('scriptData', { num: '', preSaveTempId: pseudoRandomNumber} );
    //window.console && console.log(  $(jselector).uploadifySettings('scriptData') );
  });

  // show saved message
  alert("<?php echo t('Saved'); ?>");

  //
  return true;
}


//--></script><?php //--------------------------------------------------------------------------------
}
