//
// Support functions for the Star list and data editing
//

//
// Functions for de/highlighting the star table
//

function highlight_with_partner(link, otherId, color) {
  link.style.backgroundColor = color;

  if (null !== otherId) {
    var other = document.getElementById(otherId);
    if (other !== null) {
      other.style.backgroundColor = color;
    }
  }
}

function dehighlight_with_partner(link, otherId, color) {
  link.style.backgroundColor = color;

  if (null !== otherId) {
    var other = document.getElementById(otherId);
    if (other !== null) {
      other.style.backgroundColor = color;
    }
  }
}

// Required inputs or outputs for the clipboard star data
// Keep this in sync with the $this->required_keys in Include/StarManager.php!
//
// requiredKeyData holds data about validation:
//  0 = none, 1 = present (anything), 2 = numeric, 3 = console type (DELME?)

// Needed for completeness, combination of those values needed for
// screen display and launching the applet
var requiredKeys = Array('name', 'planet', 'error1', 'separation', 'unc1', 'period', 'unc2', 'ecc', 'node', 'phase', 'duration', 'interval', 'error2', 'mstar', 'vmax', 'inclination', 'vs');

// The bare minimum keys needed to launch the applet
var requiredKeysBareMin = Array('name', 'mstar','planet','separation','ecc','inclination','node','phase','duration','interval','error2','vs');

var requiredKeyData = Array(1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3);

//
// Validation of the form on the EditStarData.php page
//

function delayedValidateOnSubmit(namePrefix, prefix, skipName, displayError) {
  //alert('validateOnSubmit("'+namePrefix+'","'+prefix+'",'+skipName+')');
  setTimeout('validateOnSubmit("'+namePrefix+'","'+prefix+'",'+skipName+','+displayError+')', 200);
}

function validateOnSubmit(namePrefix, prefix, skipName, displayError) {
  var errors = 0;
  for (var i = (requiredKeys.length - 1); i >= 0; --i) {
    if ((requiredKeys[i] == 'vs') || (requiredKeys[i] == 'phase')) {
      // Don't validate vs, user can no longer set it
      continue;
    }
    else if (requiredKeys[i] == 'name') {
      if (skipName) {
        continue;
      }
      else {
        inputName = namePrefix + requiredKeys[i];
        infoName = 'info_' + inputName;
      }
    }
    else {
      inputName = prefix + requiredKeys[i];
      infoName = 'info_' + inputName;
    }

    inputNode = document.getElementsByName(inputName).item(0);

    switch (requiredKeyData[i]) {
    case 1:
      // Validate something present (can be anything)
      if (!validatePresent(inputNode, infoName, true)) {
        ++errors;
      }
      break;

    case 2:
      // Validate field in only numeric
      if (!validateNumeric(inputNode, infoName, true, true)) {
        ++errors;
      }
      break;

    case 3:
      // Validate field is 0, 1, or 2
      if (!validateConsoleType(inputNode, infoName, true, true)) {
        alert(inputNode);
        ++errors;
      }
      break;

    default:
      // Do nothing
      break;

    }
  }

  if (displayError && (errors != 0)) {
    alert('There are fields which need correction');
  }

  return (errors == 0);
}

function delayedValidateOnSubmitSet12(namePrefix, prefixSet1, prefixSet2) {
  //alert('validateOnSubmitSet12("'+namePrefix+'","'+prefixSet1+'",'+prefixSet2+')');
  setTimeout('validateOnSubmitSet12("'+namePrefix+'","'+prefixSet1+'","'+prefixSet2+'")', 200);
}

function validateOnSubmitSet12(namePrefix, prefixSet1, prefixSet2) {
  var errorsSet2 = validateOnSubmit(namePrefix, prefixSet2, true, false);
  var errorsSet1 = validateOnSubmit(namePrefix, prefixSet1, false, false);
  
  //DELME
  if (!errorsSet1 || !errorsSet2) {
    alert('There are fields which need correction');
  }

  return (errorsSet1 && errorsSet2);
}


//
// Launch an applet to test the data
//

function launch_test_applet(inpt, namePrefix, prefix) {
  if (!validateOnSubmit(namePrefix, prefix, false, true)) {
    return;
  }

  url = '../Applets/LaunchPlanetFinderApplet.php?';
  var i = 0;
  url = url + 'style=test' + "&";
  url = url + requiredKeys[i] + "=" + inpt.form[namePrefix + requiredKeys[i]].value;
  for (i = 1; i < requiredKeys.length; ++i) {
    url = url + "&" + requiredKeys[i] + "=" + inpt.form[prefix + requiredKeys[i]].value;
  }
  window.location.href = url;
  return;
}


//
// AJAX
//

// TODO: make more unified way to do AJAX
function GetXmlHttpObject()
{
  var xmlHttp=null;
  try
    {
      // Firefox, Opera 8.0+, Safari
      xmlHttp=new XMLHttpRequest();
      xmlHttp.overrideMimeType('text/xml');
    }
  catch (e)
    {
      // Internet Explorer
      try
        {
          xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
      catch (e)
        {
          xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
  return xmlHttp;
}


// xmlHttp - an xmlhttp object
// cbFunction - ref to the function callback of form:
//    func(xmlHttp, data)
// data - data that will be passed to the callback 
function xmlHttpCallback(xmlHttp, cbFunction, data) {
  try {
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
        cbFunction(xmlHttp, data);
      }
      else {
        alert('There was a problem with the request.');
      }
    }  
  }
  catch( e ) {
    alert('Caught Exception: ' + e.description);
  }  
}

function copy_xml_data_to_document(xmldoc, requiredKeys, namePrefix, prefix) {
  // First do the name
  var rootNode = xmldoc.getElementsByTagName('name').item(0);
  var inputNode = document.getElementsByName(namePrefix + 'name').item(0);
  var clipboardNode = document.getElementById('full_' + 'name');

  inputNode.value = rootNode.firstChild.data;
  clipboardNode.innerHTML = inputNode.value;

  for (i = 1; i < requiredKeys.length; ++i) {
    /*
    if (requiredKeys[i] == 'vs') {
      // Don't do anything with vs, user can no longer set it
      continue;
    }
    */

    rootNode = xmldoc.getElementsByTagName(requiredKeys[i]).item(0);
    inputNode = document.getElementsByName(prefix + requiredKeys[i]).item(0);
    clipboardNode = document.getElementById('full_' + requiredKeys[i]);
    inputNode.value = rootNode.firstChild.data;
    clipboardNode.innerHTML = inputNode.value;
  }
}

function update_clipboard_state(xmldoc) {
  rootNode = xmldoc.getElementsByTagName('clipboard_state').item(0);
  state = rootNode.firstChild.data;
  if (state == 'empty') {
    result = document.getElementById('clipboard_empty');
    result.style.display = 'block';
    result = document.getElementById('clipboard_full');
    result.style.display = 'none';
    result = document.getElementById('clipboard_checked');
    result.style.display = 'none';
  }
  else if ((state == 'full') || (state == 'used')) {
    result = document.getElementById('clipboard_empty');
    result.style.display = 'none';
    result = document.getElementById('clipboard_full');
    result.style.display = 'block';
    result = document.getElementById('clipboard_checked');
    result.style.display = 'none';

  }
  else {
    alert('Error: Cannot update clipboard state!');
    return;
  }

}

function paste_callback(xmlHttp, data) {
  var xmldoc = xmlHttp.responseXML;
  var rootNode;
  
  requiredKeys = data['requiredKeys'];
  namePrefix = data['namePrefix'];
  prefix = data['prefix'];

  if (typeof(xmldoc.getElementsByTagName('clipboard_state')[0]) != 'undefined') {
    rootNode = xmldoc.getElementsByTagName('clipboard_state').item(0);
    state = rootNode.firstChild.data;
    if (state == 'empty') {
      alert('Clipboard is empty, nothing to paste');
    }
    else if ((state == 'full') || (state == 'full')) {
      copy_xml_data_to_document(xmldoc, requiredKeys, namePrefix, prefix);
      update_clipboard_state(xmldoc);
    }
  }
  else if (typeof(xmldoc.getElementsByTagName('error')[0]) != 'undefined') {
    rootNode = xmldoc.getElementsByTagName('error').item(0);
    alert(rootNode.firstChild.data);
  }
}

function copy_callback(xmlHttp, data) {
  var xmldoc = xmlHttp.responseXML;
  var rootNode;

  requiredKeys = data['requiredKeys'];
  namePrefix = data['namePrefix'];
  prefix = data['prefix'];
  
  if (typeof(xmldoc.getElementsByTagName('clipboard_state')[0]) != 'undefined') {
    copy_xml_data_to_document(xmldoc, requiredKeys, namePrefix, prefix);
    update_clipboard_state(xmldoc);
    alert('Data copied successfully');
  }
  else {
    if (typeof(xmldoc.getElementsByTagName('error')[0]) != 'undefined') {
      rootNode = xmldoc.getElementsByTagName('error').item(0);
      alert(rootNode.firstChild.data);
    }
    else {
      alert('There was an error, copy unsuccessful!');
    }
  }
}

function clear_callback(xmlHttp, data) {
  var xmldoc = xmlHttp.responseXML;
  var rootNode;

  if (typeof(xmldoc.getElementsByTagName('clipboard_state')[0]) != 'undefined') {
    alert('Clipboard cleared');
    update_clipboard_state(xmldoc);
  }
  else {
    if (typeof(xmldoc.getElementsByTagName('error')[0]) != 'undefined') {
      rootNode = xmldoc.getElementsByTagName('error').item(0);
      alert(rootNode.firstChild.data);
    }
    else {
      alert('There was an error, copy unsuccessful!');
    }
  }
}

function paste_from_clipboard(inpt, namePrefix, prefix, instructorId) {

  // Base URL
  url = 'clipboard.php?';

  // Add the action to take
  url = url + encodeURIComponent('action')  + '=' +
    encodeURIComponent('get_clipboard_data'); 

  // Add the instructor id
  url = url + '&' + encodeURIComponent('instructor_id')  + '=' +
    encodeURIComponent(instructorId); 
  
  // Get the xmlHttp object
  xmlHttp = GetXmlHttpObject(); 
  if (!xmlHttp) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  data = Array();
  data['requiredKeys'] = requiredKeys;
  data['namePrefix'] = namePrefix;
  data['prefix'] = prefix;
  xmlHttp.onreadystatechange = function() { xmlHttpCallback(xmlHttp, paste_callback, data); };
  xmlHttp.open('GET', url, true);
  xmlHttp.send('');
}

function copy_to_clipboard(inpt, namePrefix, prefix, instructorId) {
  if (!validateOnSubmit(namePrefix, prefix, false, true)) {
    return;
  }

  // Base URL
  url = 'clipboard.php?';

  // Add the action to take
  url = url + encodeURIComponent('action')  + '=' +
    encodeURIComponent('set_clipboard_data'); 

  // Add the instructor id
  url = url + '&' + encodeURIComponent('instructor_id')  + '=' +
    encodeURIComponent(instructorId); 

  // Add the star name 
  url = url + '&' + encodeURIComponent('name')  + '=' +
    encodeURIComponent(inpt.form[namePrefix + 'name'].value); 
  
  // Add the rest of the data
  for (i = 1; i < requiredKeys.length; ++i) {
    url = url + '&' + encodeURIComponent(requiredKeys[i]) + '=' +
      encodeURIComponent(inpt.form[prefix + requiredKeys[i]].value);
  }

  xmlHttp = GetXmlHttpObject(); 
  if (!xmlHttp) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  data = Array();
  data['requiredKeys'] = requiredKeys;
  data['namePrefix'] = namePrefix;
  data['prefix'] = prefix;

  xmlHttp.onreadystatechange = function() { xmlHttpCallback(xmlHttp, copy_callback, data); };
  xmlHttp.open('GET', url, true);
  xmlHttp.send('');
}

function clear_clipboard(instructorId) {
  // Base URL
  url = 'clipboard.php?';

  // Add the action to take
  url = url + encodeURIComponent('action')  + '=' +
    encodeURIComponent('clear_clipboard_data'); 

  // Add the instructor id
  url = url + '&' + encodeURIComponent('instructor_id')  + '=' +
    encodeURIComponent(instructorId); 

  xmlHttp = GetXmlHttpObject(); 
  if (!xmlHttp) {
    alert('Giving up :( Cannot create an XMLHTTP instance');
    return false;
  }

  data = null;
  xmlHttp.onreadystatechange = function() { xmlHttpCallback(xmlHttp, clear_callback, data); };
  xmlHttp.open('GET', url, true);
  xmlHttp.send('');
}
