// <script src="/sb/core/source/web/ui.js"></script>
// <script src="/sb/core/source/web/uploads.js"></script>
// <script src="http://titan.itools.dev/sb/software/Article_Manager_2/includes/common.js"></script>
// <script src="http://titan.itools.dev/sb/core/addons/innerHTML/RC1/dom_innerHTML.js"></script>


// ----------------------------------------------------------------------------

function _uploadlist_getSortedArray(fieldname) {  // return sorted array of uploaded files

  // get a list of all the uploads for this upload field
  var myElements = document.getElementsByName(fieldname); 
  var uploadList  = new Array();
  for (var n=0; n<myElements.length; n++) {
    uploadList.push( { placeholders: query2obj(myElements[n].value) } ); // placeholders
  }

  // sort list by order key
  var mysort = function(value1, value2) {
    var order1 = parseInt(value1.placeholders.order) || 0;
    var order2 = parseInt(value2.placeholders.order) || 0;
    if      (order1 < order2)  { return -1; }
    else if (order1 == order2) { return 0; }
    else if (order1 > order2)  { return 1; }
  };
  uploadList.sort(mysort);

  return uploadList;

}

// ----------------------------------------------------------------------------

function _uploadlist_getModifyArray(fieldname) { // save after modify

  // get a list of all the uploads for this upload field
  var uploadList  = _uploadlist_getSortedArray(fieldname);
 
  // get array of images to modify
  uploadList = uploadList; // modify them all for now
//  for (var n=0; n<uploadList.length; n++) { 
//    unums += templateCell('uploadlist_'+ltype+'_row', uploadList[n].placeholders);
//  }

  return uploadList;

}

// ----------------------------------------------------------------------------

function _uploadlist_updateHiddenFields(fieldname, uploadList) {  // update hidden fields with upload data

  // create hidden field html
  var hiddenFields = "";
  for (var n=0; n<uploadList.length; n++) {
    if (uploadList[n] == null) { continue; }
    var fieldData = obj2query( uploadList[n].placeholders );
    hiddenFields += '<input type="hidden" name="'+fieldname+'" value="'+fieldData+'">\n';
  }

  // update hidden fields in page
  setInnerHTML(fieldname + '_hidden_fields', hiddenFields);

}
// ----------------------------------------------------------------------------

function _uploadlist_getNewUploadNum(fieldname) {  // return a new upload num that hasn't been used before

  var highestUsed   = document.getElementById(fieldname + '_highestnum');
  highestUsed.value++;

  return highestUsed.value;
}

// ----------------------------------------------------------------------------

function uploadlist_generate(fieldname, ltype) {
  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }

  // get a list of all the uploads for this upload field
  var uploadList  = _uploadlist_getSortedArray(fieldname);
 
  // generate table rows
  templateCell.globals.fieldname = fieldname;
  var tableRows = "";
  for (var n=0; n<uploadList.length; n++) {
    var placeholders = uploadList[n].placeholders;
    placeholders.thumbnail_bool = parseInt(placeholders.thumbnail) ? "Yes" : "No";
    placeholders.linkto_bool    = placeholders.linkto.length       ? "Yes" : "No";
    tableRows += templateCell('uploadlist_'+ltype+'_row', placeholders);
  }

  // generate table and add rows
  var tableHTML = "";
  tableHTML += '<table border=0 cellspacing=1 cellpadding=0 width=680>';
  if (document.getElementById('uploadlist_'+ltype+'_header')) { 
    tableHTML += getInnerHTML('uploadlist_'+ltype+'_header');
  }
  tableHTML += tableRows ? tableRows : templateCell('uploadlist_'+ltype+'_emptylist');
  tableHTML += '</table>';
  if (document.getElementById('uploadlist_'+ltype+'_footer_menu')) { 
    tableHTML += templateCell('uploadlist_'+ltype+'_footer_menu', {});
  }
  
  // display table
  setInnerHTML(fieldname + '_ui', tableHTML);
}

// ----------------------------------------------------------------------------

function uploadlist_add(fieldname, ltype, queryData) {

  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }
  if (queryData == null) { return alert("uploadlist_add: no new record data defined!"); }
  var newRecords = "";

  // get a list of all the uploads for this upload field
  var uploadList  = _uploadlist_getSortedArray(fieldname);

//  // create new record with default values
//  var newRec = new Object();
//  newRec.placeholders = {
//    filename:   "somegears3.jpg",
//    title:      "file123 title",
//    caption:    "this is the desc",
//
//    thumbnail:  "1",      // 0, 1
//    align:      "right",  // left, center, right
//    alignwrap:  "0",      // 0, 1
//    linkto:     "url",    // "", url, image
//    linktarget: "mainwin",
//    linkurl:    "www.yahoo123.com"
//  };

  // do we have one upload or an array of uploads
  var newUploads = [];
  if (typeof queryData == 'object') { newUploads = queryData; }
  else                              { newUploads.push(queryData); }

  // create new record
  for (n=0; n<newUploads.length; n++) { 
    queryData = newUploads[n];
    var newRec  = { placeholders: new Object() };
    var newData = query2obj(queryData);
    var rFields = ['filename','filepath','title','caption','thumbnail','align','alignwrap','linkto','linktarget','linkurl'];
    for (var idx in rFields) {
      var rField = rFields[idx];
      if (typeof newData[rField] != 'undefined') {
        newRec.placeholders[rField] = newData[rField];
      } else {
        newRec.placeholders[rField] = '';
      }
    }
    
    // set unum and sort order
    newRec.placeholders.unum  = _uploadlist_getNewUploadNum(fieldname);
    newRec.placeholders.order = newRec.placeholders.unum;               // set sort order to num
    
    // add new number to new record numbers list
    if (newRecords) { newRecords += ","; }
    newRecords += newRec.placeholders.unum;

    uploadList.push(newRec);                                     // add new record to list

  }

  // check that we haven't accidently added a second image to a single image field
  if (ltype == 'single') {
    uploadList = [ uploadList[uploadList.length-1] ];                             // replace entire array with its last element
  }

  _uploadlist_updateHiddenFields(fieldname, uploadList);       // update hidden fields
  uploadlist_generate(fieldname, ltype);                      // update uploadlist UI

  return newRecords;

}

// ----------------------------------------------------------------------------

function uploadlist_modify(fieldname, ltype, unum) {  // unum can be number or comma separated list of numbers
  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }

  // create list of record numbers to modify
  var modifyAllRecords = false;
  var recordsToModify = new Object();
  if (unum == null)                 { modifyAllRecords = true; }
  else if (typeof unum == 'number') { recordsToModify[ unum ] = 1; }
  else {                                                        // number of comma separated list
    var myArray = unum.split(",");
    for (var n=0; n<myArray.length; n++) { recordsToModify[ parseInt(myArray[n]) ] = 1; }
  }
  
  // create object with actual records to modify
  var uploadList = _uploadlist_getSortedArray(fieldname);
  var modifyList = new Array();
  for (var n=0; n<uploadList.length; n++) {
    var unum = uploadList[n].placeholders.unum;
    if (modifyAllRecords || recordsToModify[unum]) { modifyList.push( uploadList[n] ); }
  }

  // store modify list for child window
  objStore('save','uploadlist', uploadList);
  objStore('save','modifylist', modifyList);
  objStore('save','fieldname',  fieldname);
  objStore('save','ltype',      ltype);

  // launch modify popup
  var maxHeight = 110 + (120 * 3);
  var reqHeight = 110 + (120 * modifyList.length);
  var height = Math.min(reqHeight, maxHeight);

  var width  = 760;
  var r = popup(_weburl + 'media_modify.html', width, height, 'uploadlist_popup');

  // popup window loads data from objStore and runs it's own code

}
// ----------------------------------------------------------------------------

function uploadlist_upload(fieldname, ltype, table_name) {
  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }

  // store modify list for child window
  objStore('save','table',      table_name);
  objStore('save','fieldname',  fieldname);
  objStore('save','ltype',      ltype);
  objStore('save','_cgiurl',    _cgiurl);                                       // global variable set in interface header

  // which upload form to use?
  var upload_form;
  if (ltype == 'single') { upload_form = 'media_upload_single.html'; }
  else                   { upload_form = 'media_upload_list.html'; }

  // launch modify popup
  var height = 425;
  var width  = 760;
  var r = popup(_weburl + upload_form, width, height, 'uploadlist_popup');

  // popup window loads data from objStore and runs it's own code

}



// ----------------------------------------------------------------------------

function uploadlist_remove(fieldname, ltype, unum) {

  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }

  // get a list of all the uploads for this upload field
  var uploadList  = _uploadlist_getSortedArray(fieldname);
 
  // remove specified record
  var removed = false;
  for (var n=0; n<uploadList.length; n++) {
    if (uploadList[n].placeholders.unum == unum) {
      delete uploadList[n];
      removed = true;
    }
  }
  if (!removed) { return alert("unable to find record for upload #"+unum); }  

  // update hidden fields
  _uploadlist_updateHiddenFields(fieldname, uploadList)
  
  // update uploadlist UI
  uploadlist_generate(fieldname, ltype);

}
// ----------------------------------------------------------------------------

function uploadlist_move(fieldname, ltype, unum, dir) {
  // error checking
  if (ltype == "") { return alert("error: no upload list type defined!"); }
  if (ltype != 'single' && ltype != 'placeholder' && ltype != 'attachment' && ltype != 'single_pdf') { return alert("error: unknown upload list type '"+ltype+"'!"); }

  // get a list of all the uploads for this upload field
  var uploadList  = _uploadlist_getSortedArray(fieldname);
 
  // find specified record
  var source;
  var target;
  var idx;
  for (var n=0; n<uploadList.length; n++) {
    if (uploadList[n].placeholders.unum == unum) { source = uploadList[n]; idx = n; }
  }

  // find record we want to switch with
  if (dir == 'up') { // move up
    if (idx == 0) { target = uploadList[ uploadList.length-1 ]; } // switch with bottom
    else          { target = uploadList[ idx-1 ]; }
  } else {           // move down
    if (idx == uploadList.length-1) { target = uploadList[ 0 ]; } // switch with top
    else                           { target = uploadList[ idx+1 ]; }  
  }

  // switch records
  targetOrder = target.placeholders.order;
  sourceOrder = source.placeholders.order;
  source.placeholders.order = targetOrder;
  target.placeholders.order = sourceOrder;

  // update hidden fields
  _uploadlist_updateHiddenFields(fieldname, uploadList)
  
  // update uploadlist UI
  uploadlist_generate(fieldname, ltype);

}

function objStore(action, oName, oValue) {       // load, save objects
  if (this.cache == null) { this.cache = new Object(); }

  if      (action == 'save') { this.cache[oName] = oValue; }
  else if (action == 'load') { return this.cache[oName]; }
  else                       { return alert('Unknown action: ' + action); }
}

// ----------------------------------------------------------------------------

function advancedMenuHander(fieldname, ltype) {
  var advMenu_fieldname = fieldname + '_advmenu';
  var el = document.getElementById(advMenu_fieldname);

  if      (el.value == "modifyall") { uploadlist_modify(fieldname, ltype); }
  else if (el.value == "modifyall") { uploadlist_modify(fieldname, ltype); }

  // debug methods
  else if (el.value == "generate")   { uploadlist_modify(fieldname, ltype); }
  else if (el.value == "add")        { uploadlist_add(fieldname, ltype,'filename=somegears1.jpg&title=file title&caption=this is the desc&thumbnail=0&align=left&alignwrap=0&linkto=url&linktarget=mainwin&linkurl=www.yahoo.com'); }
  else if (el.value == "modifysome") { uploadlist_modify(fieldname, ltype, '6,7'); }
  else if (el.value == "modifyone")  { uploadlist_modify(fieldname, ltype,'8'); }
  
  el.selectedIndex = 0; // reset menu
}
