//
//  Lookup/XFDF Specifics for HTML
//
//  Author: Micah Dubinko
//  Date:   5/14/2001
//
//  Requires: CS4_Library_HTML_*
//

//<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
//  <fields>
//    <field name="Entry1">
//      <value>125.00</value>
//..

CSExt.Form_OnLoad_bEP.Lookup = function() {
  if (!window.ActiveXObject)
    return;
    
  var ct = 0;
  for( var ref1 in document.htmlform.DFS__lookups)
    ++ct;

  for( var ref2 in document.htmlform.DFS__validations)
    ++ct;

  if (ct == 0)
    return;

  var xobj;

  try {
    new ActiveXObject( "Msxml2.XMLHTTP" );
  } catch(e1) {
    try {
      xobj = new ActiveXObject( "Msxml2.XMLHTTP" );
    } catch(e2) {
      CSExt.flags.msxml_warn = true;
      alert( CS_MSXML_WARN );
    }
  }
}

function csxmlhttp_create() {
  var XMLHTTP = null;
  if (CSExt.flags.msxml_warn == true)
    return null;
  if (window.ActiveXObject) {
    cstrace("ie");
    try {
      XMLHTTP = new ActiveXObject( "Msxml2.XMLHTTP" );
    } catch(e) {
      XMLHTTP = null;
      CSExt.flags.msxml_warn = true;
    }
  } else if (window.XMLHttpRequest) {
    cstrace("w3c-ish");
    XMLHTTP = new XMLHttpRequest();
  } else {
    cstrace( "unsupported browser" );
  }
  return XMLHTTP;
}

function csxmlhttp_open( XMLHTTP, sURL ) {
  var rc = true;
  try {
    //alert( "about to open" );
    XMLHTTP.open( "POST", sURL, false );
    //alert( sURL );
  } catch( e ) {
    cs_show_exception( "XMLHttpRequest.open ", e );  
    rc = false;
  }
  return rc;
}

function csxmlhttp_set_header( XMLHTTP, header, value ) {
  var rc = true;
  try {
    XMLHTTP.setRequestHeader( header, value );
  } catch( e ) {
    cs_show_exception( "XMLHttpRequest.setRequestHeader ", e );
    rc = false;
  }
  return rc;
}

function csxmlhttp_send( XMLHTTP , xdom ) {
  var rc = true;
  try {
    //alert( "about to send" );
    XMLHTTP.send( xdom );
    //alert( "back from send" );
  } catch( e ) {
    cs_show_exception( "XMLHttpRequest.send ", e );  
    rc = false;
  }
  return rc;
}

function csxmhlttp_get_response_xml( XMLHTTP ) {
  var rv = null;
  try {
    rv = XMLHTTP.responseXML;
  } catch( e ) {
    cs_show_exception( "XMLHttpRequest.responseXML ", e );  
  }
  return rv;
}

function cs_show_exception( sMsg, errObj ) {
  if (errObj.message) {
    sMsg += errObj.message;
  } else if (errObj.description) {
    sMsg += errObj.description;
  }
  alert( sMsg );
}

function cs_create_document() {
  if (document.implementation && document.implementation.createDocument) {
    // W3C technique
    cstrace( "w3c" );
    csxmlDoc = document.implementation.createDocument("", "", null);
    csxmlDoc.onload = cs_init;
  } else if (window.ActiveXObject) {
    // IE technique, checking for ActiveXObject constructor
    cstrace( "ie" );
    csxmlDoc = new ActiveXObject( "Microsoft.XMLDOM" );
    cstrace( "created ActiveXObject" );
    //csxmlDoc.onreadystatechange = cs_tmp;
  } else {
    // unsupported browser
    cstrace("unsupported");
    csxmlDoc = null;
  }
  cstrace( "returning" + csxmlDoc );
  return csxmlDoc;
}

function cs_tmp() { // hack for IE support
  alert( "state change " );
  //if (csxmlDoc.readyState == 4) cs_init();
}

function cs_init() {
  // do initialization here
  alert( "XML document loaded!");
}

function cs_submit_xfdf_load_xfdf( URL, sendMsg ) {
  var XMLHTTP = csxmlhttp_create();
  if (XMLHTTP != null && CSExt.flags.msxml_pending==false) {
    CSExt.flags.msxml_pending = true;
    if ( sendMsg.length > 0 ) alert ( sendMsg );
    var good = true;
    var xdom = null;
    var counter = 3;
    while (counter > 0) {
      --counter;
      xdom = cs_create_document();
      good = (xdom != null);
      if (!good) continue;
      cs_assemble_xfdf( xdom );
      good = csxmlhttp_open( XMLHTTP, URL );
      if (!good) continue;
      good = csxmlhttp_set_header( XMLHTTP, "Content-Type", "application/vnd.adobe.xfdf");
      if (!good) continue;
      good = csxmlhttp_send( XMLHTTP, xdom );
      if (good) break;
    }
    
    if (good) cs_apply_xfdf( csxmhlttp_get_response_xml( XMLHTTP ), document.htmlform );
    CSExt.flags.msxml_pending = false;
    
    return good;
  }
}

function cs_assemble_xfdf( doc ) {
  var dh = document.htmlform;
  var formobj = new CSForm_Obj( dh );
  formobj.getNumberOfFields();
  var all_array = dh.DFS__PrivateFieldList.concat( dh.DFS__UserFieldList );
  
  //ignoring namespaces for now...
  var xfdlelem = doc.createElement( "xfdf" );
  var fieldselem = doc.createElement( "fields" );
  xfdlelem.appendChild( fieldselem );
  doc.appendChild( xfdlelem );

  for (var idx=0; idx<all_array.length; idx++) {
    var csfld = new CSField_Obj( dh[all_array[idx]] );

    var fieldelem = doc.createElement( "field" );
    fieldelem.setAttribute( "name", csfld.getName() );
    
    val_array = csfld.getValues();
    for (var jdx=0; jdx<val_array.length; jdx++) {
      var valueelem = doc.createElement( "value" );
      valueelem.appendChild( doc.createTextNode( val_array[jdx] ));
      fieldelem.appendChild( valueelem );
    }
    fieldselem.appendChild( fieldelem );
  }
  
  // <debug>
  // alert( "Outgoing xml:\n" + doc.xml );
  // </debug>
}

function cs_apply_xfdf( doc, htmlform ) {
  // return true if a popup message is shown
  if (!doc) return;
  
  // step 1, prune the tree and build array
  var chgs = [];
  var cidx = 0;
  document.htmlform.DFS__RedirectURL.value = "";
  document.htmlform.DFS__StatusMsg.value = "";
  document.htmlform.DFS__SetFocusTo.value = "";
  
  var fieldelems = doc.getElementsByTagName( "field" );
  // <debug>
  // alert( "incoming XML:\n" + doc.xml );
  // </debug>
  for( var idx=0; idx<fieldelems.length; idx++) {
    var val_array = new Array();
    var ofs = 0;
    var hasValue = false;
    var fieldelem = fieldelems[idx];
    for (var jdx=0; jdx<fieldelem.childNodes.length; jdx++) {
      if (fieldelem.childNodes[jdx].nodeType==1 && fieldelem.childNodes[jdx].nodeName.toLowerCase()=="value") {
        hasValue = true;
        if (fieldelem.childNodes[jdx].firstChild == null) {
          val_array[ofs++] = "";
        } else {
          val_array[ofs++] = fieldelem.childNodes[jdx].firstChild.nodeValue;
        }
      }
    }
    var fname = fieldelem.getAttribute( "name" );
    //alert( "field:" + fname + " new value: " + val_array.toString() );
    var csfld = new CSField_Obj( htmlform.elements[fname] );

    // step 1.5, add <option>s
    var options = fieldelem.getElementsByTagName( "option" );
    for( var kdx=options.length-1; kdx>=0; kdx-- ) {
      var delem = options[kdx].getElementsByTagName("display")[0];
      var selem = options[kdx].getElementsByTagName("value")[0];
      var dstr = delem.firstChild.nodeValue;
      var sstr = selem.firstChild.nodeValue;
      if (csfld.getChoices()!= null && delem != null && selem != null && !csfld.getChoices().choiceExists( sstr, dstr ) ) {
        csfld.getChoices().insertAt( 0, sstr, dstr );
      }
    }

    if (hasValue && (csfld.getValues().toString() != val_array.toString()) ) {
      chgs[cidx++] = { fld:csfld, vals:val_array };
    }
  }
  
  // step 2, update
  for( var udx = 0; udx < chgs.length; udx++ ) {
    chgs[udx].fld.setValues( chgs[udx].vals );
  }
  
  // step 3, show message
  // NOTE: This is a separate mechanism than DFS__StatusMsg. These should be merged someday.
  var dbElems = doc.getElementsByTagName( "status" );
  if ( (dbElems.length > 0) && (dbElems[0].firstChild)) {
    document.htmlform.DFS__StatusMsg.value = dbElems[0].firstChild.nodeValue;
  }
  // Redirect URL
  dbElems = doc.getElementsByTagName( "f" );
  if ( dbElems.length > 0) {
    document.htmlform.DFS__RedirectURL.value = dbElems[0].getAttribute("href");
  }
  
}

CSExt.OnChange_aEP.Lookup = function( f ) {
  if (f.value == "") {
    return;
  }
  if (!document.htmlform.DFS__SubmitURL) {
    if (document.htmlform.DFS__lookups[f.name] || document.htmlform.DFS__validations[f.name]) {
      alert( CS_ERR_NOTPUBLISHED );
    }
    return;
  }
  var urlstr = document.htmlform.DFS__SubmitURL.value;
  
  // Lookup
  if (document.htmlform.DFS__lookups[f.name] && 
      document.htmlform.DFS__lookups[f.name].action &&
      document.htmlform.DFS__lookups[f.name].action == "tabout" ) {
    document.htmlform.DFS__Action.value = "DBCommandsOnTabOut";
    document.htmlform.DFS__Field.value = f.name;
    cs_submit_xfdf_load_xfdf( urlstr, document.htmlform.DFS__lookups[f.name].sending );
    // status message
    if (document.htmlform.DFS__StatusMsg && document.htmlform.DFS__StatusMsg.value.length > 0) {
      alert( document.htmlform.DFS__StatusMsg.value );
      document.htmlform.DFS__StatusMsg.value = "";
    }
  } else
  // Validation
  if (document.htmlform.DFS__validations[f.name] && 
      document.htmlform.DFS__validations[f.name].onTabOut &&
      document.htmlform.DFS__validations[f.name].onTabOut == true ) {
    document.htmlform.DFS__Action.value = "DBCommandsOnTabOut";
    document.htmlform.DFS__Field.value = f.name;
    
    cs_submit_xfdf_load_xfdf( urlstr, "" );
    // status message
    if ((document.htmlform.DFS__StatusMsg != null) && (document.htmlform.DFS__StatusMsg.value.length > 0)) {
      alert( document.htmlform.DFS__StatusMsg.value );
      document.htmlform.DFS__StatusMsg.value = "";
      // is message shown, return focus to field
      cstrace( "scheduling focus() and select() for " + f.name );
      if (f.type != "hidden") {
        document.htmlform.DFS__SetFocusTo.value = f.name;
        document.htmlform.DFS__focustimer = setTimeout( "cs_focus_hack();", 0);
      }
      //var fldobj = new CSField_Obj( f );
      //fldobj.setFocus();
    }
  }
}

CSExt.OnButtonClick_aEP.Lookup = function( f ) {
  if (document.htmlform.DFS__lookups && document.htmlform.DFS__lookups[f.name] && document.htmlform.DFS__lookups[f.name].action &&
  document.htmlform.DFS__lookups[f.name].action == "click") {
    // do the lookup
    if (document.htmlform.DFS__SubmitURL) {
      var urlstr = document.htmlform.DFS__SubmitURL.value;
      document.htmlform.DFS__Action.value = "DBCommandsOnButton";
      document.htmlform.DFS__Field.value = f.name;
      cs_submit_xfdf_load_xfdf( urlstr, document.htmlform.DFS__lookups[f.name].sending );
    } else {
      alert( CS_ERR_NOTPUBLISHED );
    }
  }
}

/**
 * Valid before submit (not for submit button).
 */
function cs_OnSubmitLookup() {
  var isValid = true;
  if ((document.htmlform.DFS__SubmitURL != null) && (document.htmlform.DFS__SubmitURL.value.length > 0)) {
    var urlstr = document.htmlform.DFS__SubmitURL.value;
    var good = cs_submit_xfdf_load_xfdf( urlstr, "" );
    if (good) {
      //  No redirect = validation is not valid.
      if ((document.htmlform.DFS__RedirectURL.value == null) || 
          (document.htmlform.DFS__RedirectURL.value.length == 0)) {
        isValid = false;
        // status message
        if ((document.htmlform.DFS__StatusMsg.value != null) && (document.htmlform.DFS__StatusMsg.value.length > 0)) {
          alert(document.htmlform.DFS__StatusMsg.value);
        }
        // set focus
        if ((document.htmlform.DFS__SetFocusTo.value != null) && (document.htmlform.DFS__SetFocusTo.value.length > 0)) {
          document.htmlform.DFS__focustimer = setTimeout( "cs_focus_hack();", 0);
        }
      }
    }
  }
  
  return isValid;
}

/** Select the good value for the DFS__Action hidden field.
 *  Get the value form the CRP tag in the DFS__ActionList drop list.
 */
CSExt.Form_OnSubmit_bEP.StaticLookup = function( f ) {
  var isValid = true;
  //  Validation.
  var formobj = new CSForm_Obj( document.htmlform );
  formobj.getNumberOfFields();
  var entries = document.htmlform.DFS__UserFieldList;
  for (var i = 0; (i < entries.length) && isValid; i++) {
    isValid = CSExt.validate( document.htmlform[entries[i]], "strict" );
  }
  if (!isValid) {
    CSExt.preventDefault();
  }
}