var UNLOAD_MSG = "You will lose any unsaved changes!";
var IGNORE_UNLOAD = true;

// json_field_id = 'orientation_studies_json'
// item_field_id = 'orientation_studies_items'
function m2m_add(prefix, item_fields, autocomplete_fields)
{
  //var p = document.forms['bla']; var JSONObject = new Object; JSONObject.email = p['email'].value; JSONstring = JSON.stringify(JSONObject);
  
  // get current array of objects
  var myarray = json2array(prefix + 'm2m_json');
  
  // create new object
  var newobj = new Object;

  // fill in fields  
  for (var i=0; i<item_fields.length; i++)
  {
    // newobj.FIELDNAME = $('PREFIX_FIELDNAME').value;
    if ($(prefix + item_fields[i]) === null) {
      // try hour and minute
      newobj[item_fields[i]] = {hour:$(prefix + item_fields[i] + '_hour').value,minute:$(prefix + item_fields[i] + '_minute').value};
    } else {
      newobj[item_fields[i]] = $(prefix + item_fields[i]).value;
    }
    if (item_fields[i] == 'id') {
      $(prefix+'id').value = '';
    }
  }
  for (var i=0; i<autocomplete_fields.length; i++)
  {
    // newobj.FIELDNAME_visible_value = $('PREFIX_FIELDNAME_visible_value').value;
    newobj[autocomplete_fields[i] + "_visible_value"] = $(prefix + autocomplete_fields[i] + '_visible_value').value;
  }

  newobj.isNew = 1;
  newobj.isModified = 1;
  newobj.id = null;
 
  newobj.field_to_show = getM2mFieldToShow(prefix);
  
  // add item to the array
  myarray.push(newobj);
  
  // put array in json
  array2json(prefix + 'm2m_json', myarray);
  
  // update the list for viewing
  updateM2mList(prefix + 'm2m_items', myarray);
  
  // hide edit buttons
  hideM2mUpdateButtons(prefix);

  IGNORE_UNLOAD = false;
}

function m2m_update(prefix, item_fields, autocomplete_fields)
{
  var myarray = json2array(prefix + 'm2m_json');
  var idx = $(prefix + 'm2m_items').selectedIndex;
  
  myarray[idx].isModified = 1;
  for (var i=0; i<item_fields.length; i++)
  {
    // myarray[idx].FIELDNAME = $('PREFIX_FIELDNAME').value;
    if ($(prefix + item_fields[i]) === null) {
      // try hour and minute
      myarray[idx][item_fields[i]] = {hour:$(prefix + item_fields[i] + '_hour').value,minute:$(prefix + item_fields[i] + '_minute').value};
    } else {
      myarray[idx][item_fields[i]] = $(prefix + item_fields[i]).value;
    }
  }
  for (var i=0; i<autocomplete_fields.length; i++)
  {
    // newobj.FIELDNAME_visible_value = $('PREFIX_FIELDNAME_visible_value').value;
    myarray[idx][autocomplete_fields[i] + "_visible_value"] = $(prefix + autocomplete_fields[i] + '_visible_value').value;
  }
  myarray[idx].field_to_show = getM2mFieldToShow(prefix);
  
  // put array in json
  array2json(prefix + 'm2m_json', myarray);
  
  // update the list for viewing
  updateM2mList(prefix + 'm2m_items', myarray);
  
  // hide edit buttons
  hideM2mUpdateButtons(prefix);

  IGNORE_UNLOAD = false;
}

function m2m_delete(prefix, item_fields, autocomplete_fields)
{
  var myarray = json2array(prefix + 'm2m_json');
  var idx = $(prefix + 'm2m_items').selectedIndex;
  
  // remove the selected item from the array
  myarray.splice(idx, 1);
  
  // put array in json
  array2json(prefix + 'm2m_json', myarray);
  
  // update the list for viewing
  updateM2mList(prefix + 'm2m_items', myarray);
  
  // hide edit buttons
  hideM2mUpdateButtons(prefix);

  IGNORE_UNLOAD = false;
}

function m2m_select(prefix, item_fields, autocomplete_fields)
{
  var myarray = json2array(prefix + 'm2m_json');
  
  // if we have items
  if (myarray.length > 0) {
    var obj = myarray[$(prefix + 'm2m_items').selectedIndex];
    // and the selected item is in json
    if (obj) {
      // get all fields to the display
      for (var i = 0; i<item_fields.length; i++) {
        if ($(prefix + item_fields[i]) === null && $(prefix + item_fields[i] + '_hour') !== null) {
          if (typeof(obj[item_fields[i]]) == 'object') {
            $(prefix + item_fields[i] + '_hour').value = obj[item_fields[i]]['hour'];
            $(prefix + item_fields[i] + '_minute').value = obj[item_fields[i]]['minute'];
          } else {
            var mytime = obj[item_fields[i]].split(':');
            $(prefix + item_fields[i] + '_hour').value = mytime[0];
            $(prefix + item_fields[i] + '_minute').value = mytime[1];
          }
        } else {
          $(prefix + item_fields[i]).value = obj[item_fields[i]];
        }
      }
      for (var i=0; i<autocomplete_fields.length; i++) {
        $(prefix + autocomplete_fields[i] + "_visible_value").value = eval('obj.'+autocomplete_fields[i]+'_visible_value');
      }
      // show edit buttons
      showM2mUpdateButtons(prefix); 
      return;
    }
  }
  // hide buttons
  hideM2mUpdateButtons(prefix)
}

function m2m_cancel(prefix, item_fields)
{
  // just deselect the item and hide the buttons
  $(prefix + 'm2m_items').selectedIndex = -1;
  hideM2mUpdateButtons(prefix);
}

function getM2mFieldToShow(prefix)
{
  return eval("getM2mFieldToShow_" + prefix + "();");
}

function json2array(json_field_id)
{
  // read json string and return the array that is in it
  var old_json = $(json_field_id).value;
  var myarray = eval(old_json);
  if (myarray === undefined) myarray = new Array();
  return myarray;
}

function array2json(json_field_id, myarray)
{
  // put array in json field
  var new_jason = myarray.toJSON();
  $(json_field_id).value = new_jason;
}

function updateM2mList(list_field_id, myarray)
{
  // sync the select box with the given array of objects
  $(list_field_id).options.length=0;
  for (var i=0; i<myarray.length; i++) {
    var newElement = new Element('option', {'value': i}).update(myarray[i].field_to_show);
    $(list_field_id).insert(newElement);
  }
}

function updateM2mListFromJsonField(prefix)
{
  var myarray = json2array(prefix + 'm2m_json');
  updateM2mList(prefix + 'm2m_items', myarray);
}

function hideM2mUpdateButtons(prefix)
{
  $(prefix + 'button_update').style.display = 'none';
  $(prefix + 'button_delete').style.display = 'none';
  $(prefix + 'button_cancel').style.display = 'none';
}

function showM2mUpdateButtons(prefix)
{
  $(prefix + 'button_update').style.display = '';
  $(prefix + 'button_delete').style.display = '';
  $(prefix + 'button_cancel').style.display = '';
}


function doBeforeUnload() {
  if(IGNORE_UNLOAD) return; // Let the page unload
  if(window.event) {
    window.event.returnValue = UNLOAD_MSG; // IE
  } else {
    return UNLOAD_MSG; // FX
  }
}

if(window.body) {
  window.body.onbeforeunload = doBeforeUnload; // IE
} else {
  window.onbeforeunload = doBeforeUnload; // FX
}


