
$(document).ready(function(){ init(); });

//
function init() {

  // submit form with ajax
  $('FORM').ajaxForm({
    beforeSubmit:  function() {    },
    success: function(response) {  // post-submit callback - close window
      var recordNum   = 0;  // the record number is returned on success
      var errors      = ''; // anything else is an error message
      if (parseInt(response) == response)  { recordNum = response; }
      else                                 { errors    = response; }

      // show errors
      if (errors.match(/loginSubmit/gi)) { return self.location = "?"; } // redirect to login screen if session expired
      if (errors != '') { return alert(errors); }

      // javascript plugin hook
      if (typeof edit_postSave == 'function') {
        var doReturn = edit_postSave(recordNum); // return false to continue or true to return
        if (doReturn) { return true; }
      }

      // redirect or reload page on success
      var url = '';
      if ($('#returnUrl').val()) { url = '?' + $('#returnUrl').val(); }
      else                       { url = '?menu=' + $('#menu').val() + '&saved=' + recordNum; } // display default list page
      self.location = url;
      return true;
    }
  });

}

function editCancel() {
  if ($('#returnUrl').val()) {
    self.location = '?' + $('#returnUrl').val();
  }
  else {
    self.location = '?menu=' + $('#menu').val();
  }
}

function reloadIframe(id, errors) {
  if (errors == undefined) { errors = ''; }
  var el = document.getElementById(id);
  el.contentWindow.location = el.contentWindow.location + '&errors=' + escape(errors);
}

// resize iframe to fit content (up to max)
function resizeIframe(id) {
  var maxHeight     = 800;
  var iframeEl      = document.getElementById(id);
  var contentHeight = iframeEl.contentWindow.document.body.clientHeight;

  // set height
  if (contentHeight > 0 && contentHeight <= maxHeight) {
    iframeEl.height = contentHeight;
  }
  else {
    iframeEl.height = maxHeight;
  }
}


//
function wysiwygUploadBrowser(field_name, url, type, win) {

  // get editorId
  var editorId  = tinyMCE.activeEditor.id;
  var editorObj = tinyMCE.editors[editorId];
  if (editorObj.settings['fullscreen_is_enabled']) {
    editorId = editorObj.settings['fullscreen_editor_id'];
  }
  var fieldname = editorId.replace(/^field_/, '');

  // get uploadBrowser url
  var uploadBrowserUrl = "?menu=" + escape( $('#menu').val() )
                       + "&action=wysiwygUploads"
                       + "&fieldName="     + escape(fieldname)
                       + "&num="           + escape( $('#num').val() )
                       + "&preSaveTempId=" + escape( $('#preSaveTempId').val() )

  // open upload browser
  tinyMCE.activeEditor.windowManager.open({
    file : uploadBrowserUrl,
    width : 590,
    height : 435,
    resizable : "yes",
    inline : "yes",
    close_previous : "no"
  }, {
    browseType   : type,
    parentWindow : win,
    inputFieldId : field_name
  });

  //
  return false;
}

function showCreatedByUserPulldown() {

  // get pulldown options
  var options = "1";
  $.ajax({
    url: '?',
    type: "POST",
    data: {
      menu:   $('#menu').val(),
      action: 'ajaxGetUsersAsPulldown'
    },
    error:  function(XMLHttpRequest, textStatus, errorThrown){
      alert("There was an error sending the request! (" +XMLHttpRequest['status']+" "+XMLHttpRequest['statusText'] +")");
    },
    success: function(pulldownHTML){
      $('#createdByUserNumHTML').html(pulldownHTML);
      $('#createdByUserNumChangeLink').hide();
    }
  });
}

function doAdvancedCommand() {

  var cmdValue = document.getElementById('advancedAction').value;
  if (cmdValue) {
    window.location = cmdValue;
  }
}


function updateListFieldOptions(fieldname, newFilterValue) {
  //alert("update '" +fieldname+ "' with new filter value '" +newFilterValue+ "' and selected Value: '" +selectedValue+ "'");

  // show loading...
  $("[name='" +fieldname+ "']").html("<option value=''>Loading...</option>\n");

  // update pulldown options
  var selectedValue = $("[name='" +fieldname+ "']").val();
  $.ajax({
    url: '?',
    type: "POST",
    data: {
      menu:           $('#menu').val(),
      fieldname:      fieldname,
      newFilterValue: newFilterValue,
      selectedValue:  selectedValue,
      action:         'ajaxUpdateListFieldOptions'
    },
    error:  function(XMLHttpRequest, textStatus, errorThrown){
      alert("There was an error sending the request! (" +XMLHttpRequest['status']+" "+XMLHttpRequest['statusText'] +")");
    },
    success: function(html){
      // show errors
      if (!html.match(/^<option/)) { alert("Error: " + html); }

      // update list options
      $("[name='" +fieldname+ "']").html(html);       // for single pulldowns
      $("[name='" +fieldname+ "\\[\\]']").html(html); // for multi-pulldowns
    }
  });
}

// configure uploadify
function generateUploadifyOptions( config ) {
  var fileExt = '*.' + (config['fileExtCSV'].split(',').join(';*.'));
  var newUploadNumsAsCSV = '';
  var errors             = '';
  var onAllCompleteAlreadyFired = false; // workaround a bug where onAllComplete gets called twice if there was an error?!
  var options = {
    'uploader'    : '3rdParty/jqueryPlugins/uploadify/uploadify.swf',
    'script'      : config['script'],
    'cancelImg'   : '3rdParty/jqueryPlugins/uploadify/cancel.png',
    'auto'        : true,
    'multi'       : true,
    'fileExt'     : fileExt,
    'fileDesc'    : config['fileExtCSV'], // this is required for fileExt to work
    'width'       : 400,
    'height'      : 24,
    'hideButton'  : true,
    'wmode'       : 'transparent',
    'queueID'     : config['queueID'],
    'scriptData'  : {
      'flashUploader'          : '1',
      '_defaultAction'         : 'uploadForm',
      'menu'                   : config['menu'],
      'fieldName'              : config['fieldName'],
      'num'                    : config['num'],
      'preSaveTempId'          : config['preSaveTempId'],
      'submitUploads'          : '1',
      '_action'                : 'uploadForm',
      '_FLASH_COOKIE_BUG_FIX_' : config['session_id'] // pass session info to circumvent of flash/session bug
    },
    'onInit' : function() {
      $('#'+config['fieldName']+'_uploadTips').show();
    },
    'onSelect' : function() {
      // now is as good a time as any to reset this
      onAllCompleteAlreadyFired = false;
    },
    'onComplete' : function( event, queueID, fileObj, response, data ) {

      // show flash errors
      var matches;
      matches = response.match(/^SHOW_FLASH_ERROR:\s*(.*)/m);
      if (matches) {
        errors += matches[1];
      }

      // show login errors
      else if (response.match(/<h3>Login<\/h3>/)) {
        return alert("Please login again. (or 'Disable Flash Uploader' under: Admin > General > Advanced Settings).");
      }

      // else process uploads
      else {
        matches = response.match(/&uploadNums=([\d,]+)/);
        if (matches) {
          if (newUploadNumsAsCSV.length > 0) { newUploadNumsAsCSV += ','; }
          newUploadNumsAsCSV += matches[1];
        }
      }
    },
    'onError' : function( event, queueID, fileObj, errorObj ) {
      var filename  = htmlspecialchars(fileObj['name']);
      var errorType = htmlspecialchars(errorObj.type);   // Either: HTTP, IO, Security, File Size
      var errorInfo = htmlspecialchars(errorObj.info);   // An error message describing the type of error returned
      errors += "Error uploading '" +filename+ "', ";
      if      (errorType == 'HTTP')      { errors += "server returned: HTTP " +errorInfo+ "\n"; }
      else if (errorType == 'File Size') { errors += "max filesize of " +errorInfo+ " bytes exceeded\n"; }
      else                               { errors += errorType+" error: '" +errorInfo+ "\n"; }
    },
    'onAllComplete' : function( event, data ) {
      if (onAllCompleteAlreadyFired) { return false; }
      onAllCompleteAlreadyFired = true;

      // reload uploadlist
      if (config['modifyAfterSave']) {
        reloadIframe(config['fieldName']+'_iframe');          // reload uploadlist, don't show errors
      } else {
        reloadIframe(config['fieldName']+'_iframe', errors);  // reload uploadlist, SHOW errors
      }


      if (config['modifyAfterSave']) {
        targetUrl = "?menu=" + config['menu'] + "&action=uploadModify&fieldName=" + config['fieldName'] + "&num=" + config['num'] + "&preSaveTempId=" + config['preSaveTempId']
        targetUrl += "&uploadNums=" + newUploadNumsAsCSV;
        targetUrl += '&errors=' + escape(errors);
        targetUrl += '&TB_iframe=true&height=350&width=700&modal=true';
        tb_show('', targetUrl);                             // thickbox to add captions, etc.
      }

      // reset variables for reuse
      newUploadNumsAsCSV = '';
      errors             = '';

      // finally, clear any errors out of the queue
      $('#' + config['fieldName'] + '_uploadButton').uploadifyClearQueue();
    }
  };
  if (config['maxUploadSizeKB'] > 0) {
    options['sizeLimit'] = config['maxUploadSizeKB'] * 1024;
  }
  return options;
}
