/*********************************************************************
 * This file contains proprietary information of Cardiff Software.
 * Copying or reproduction without prior written approval is prohibited.
 * Copyright (c) 2000
 *********************************************************************/

//
//  Extra features for HTML forms (pages, combo boxes, etc.)
//
//  Author: Micah Dubinko, Stephane Chauvin
//  Date:   3/29/2001
//
//  Requires: CS4_Library_HTML_csdom.js
//

function cs_Print() {
  document.htmlform.DFS__PrintingWindow = window.open( "", "DFS__PrintingWindow", "menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=yes");
  // IE takes a long time to open windows...
  document.htmlform.DFS__PrintWndTimer = setTimeout( "CS__GenPrintContent();", 1000);
}

function CS__GenPrintContent() {
  clearTimeout(document.htmlform.DFS__PrintWndTimer);
  var printWindow = document.htmlform.DFS__PrintingWindow;
  //  Duplicate the window.
  var percent = document.htmlform.DFS__PageZoom1.value;
  cs_ZoomPage( 80, document );
  
  if( document.documentElement.outerHTML ) {
    printWindow.document.write( document.documentElement.outerHTML );
    printWindow.document.close();
  } else {
    var tree = document.documentElement.cloneNode(true);
    printWindow.document.documentElement.appendChild( tree );
  }
   
  // double coverage to make it work in all browsers
  cs_ZoomPage( 80, printWindow.document ); // IE6
  
  cs_ZoomPage( percent, document ); // put back our src doc
  //  Seek Pages.
  printWindow.document.body.style.backgroundColor = "white";
  for (var i = 1; i <= document.htmlform.DFS__countPage; i++) {
    var container = printWindow.document.getElementById( "DFS__container" + i);
    var page      = printWindow.document.getElementById( "DFS__page" + i);
    var pageHeight = parseFloat(document.getElementById( "DFS__page" + i).style.height);
    //  Page position
    container.style.position = "relative";
    if (container.style.pageBreakAfter) container.style.pageBreakAfter = "always";
    page.style.position = "relative";
    page.style.top = "0in";
    page.style.left = "0in";
    page.style.width = "100%";
    page.style.height = "100%";
    //  Visibility
    container.style.display = "block";
    container.style.visibility = "hidden";
    page.style.visibility = "visible";
  }
  //  Reset values.
  for( var idx=0; idx < document.htmlform.elements.length; idx++ ) {
    var fld = document.htmlform.elements[idx];
    var newFld = printWindow.document.htmlform.elements[idx];
    //  dontPrint
    if (fld.dontprint) {
      newFld.style.visibility = "hidden";
    } else
    //  All fields
    if (fld.name.indexOf("DFS__") != 0) {
      if ((fld.type == "text") || (fld.type == "textarea")) {
        newFld.value = fld.value;
      } else
      if ((fld.type == "checkbox") || (fld.type == "radio")) {
        newFld.checked = fld.checked;
      } else
      if ((fld.type == "select-one") || (fld.type == "select-multiple")) {
        for (var ofs = 0; ofs < fld.options.length; ofs++) {
          newFld.options[ofs].selected = fld.options[ofs].selected;
        }
      }
      newFld.readOnly = true;
      newFld.disabled = true;
    }
  }
}

/** Select the page by index and display it.
 */
function cs_ShowPage( index ) {
  for (var i = 1; i <= document.htmlform.DFS__countPage; i++) {
    document.getElementById( "DFS__container" + i ).style.display = "none";
    document.getElementById( "DFS__container" + i ).style.visibility = "visible";    
    document.getElementById( "DFS__PageBotSlt" + i ).selectedIndex = index - 1;
    document.getElementById( "DFS__PageUpSlt" + i ).selectedIndex = index - 1;
  }
  document.getElementById( "DFS__container" + index ).style.display = "block";
  document.getElementById( "DFS__container" + index ).style.zIndex = "9999";
}

function cs_ZoomPage( percent, doc ) {
  if (!doc)
    doc = document;
  
  doc.body.style.fontSize = document.htmlform.DFS__physSize.baseFontSize * percent / 100 + document.htmlform.DFS__physSize.units;
  
  for( var idx=1; idx<=document.htmlform.DFS__countPage; idx++) {
    var baseW = document.htmlform.DFS__physSize.pages[idx].w;
    var baseH = document.htmlform.DFS__physSize.pages[idx].h;
    var pgNum = "DFS__page" + idx;
    var ctNum = "DFS__container" + idx;
    var zmNum = "DFS__PageZoom" + idx;
    var btnPg = "DFS__PageBottom" + idx;
    var units = document.htmlform.DFS__physSize.units;
    doc.getElementById( pgNum ).style.width = (baseW * percent / 100) + units;
    doc.getElementById( pgNum ).style.height = (baseH * percent / 100) + units;
    doc.getElementById( ctNum ).style.width = (0.1 + baseW * percent / 100) + units;
    doc.getElementById( ctNum ).style.height = (0.6 + baseH * percent / 100) + units;
    doc.getElementById( btnPg ).style.top = ((baseH * percent / 100) + 0.3) + units;
    
    // adjust zoom controls on all pages
    doc.getElementById( zmNum ).value = percent;
    
    // refresh Netscape ? http://bugzilla.mozilla.org/show_bug.cgi?id=88154
    var oldval = doc.getElementById( ctNum ).style.display;
    doc.getElementById( ctNum).style.display = "none";
    doc.getElementById( ctNum).style.display = oldval;
  }
}

/** Get an entry field to make a combo list.
 *  @param comboName The ID of the combo (drop list).
 */
function cs_AddInCombo( comboName ) {
  var droplistcombodiv = document.getElementById( "droplistdiv" + comboName );
  var entrycombodiv = document.getElementById( "entrydiv" + comboName );
  var droplistcombo = document.getElementById( "droplist" + comboName );
  var entrycombo = document.getElementById( "entry" + comboName );
  if (droplistcombo.options[droplistcombo.selectedIndex].value == "DFS__OtherInCombo") {
    droplistcombodiv.style.visibility = "hidden";
    entrycombodiv.style.visibility = "inherit";
    entrycombo.value = "";
    entrycombo.focus();
    entrycombo.select();
  }
}

/** Add the value of the entry field in the drop list (to do a combo list).
 *  @param comboName The ID of the combo (drop list).
 */
function cs_BlurredEntryConbo( comboName ) {
  var droplistcombodiv = document.getElementById( "droplistdiv" + comboName );
  var entrycombodiv = document.getElementById( "entrydiv" + comboName );
  var droplistcombo = document.getElementById( "droplist" + comboName );
  var entrycombo = document.getElementById( "entry" + comboName );
  if ( entrycombo.value != "" ) {
    droplistcombo.options[droplistcombo.options.length] = new Option( entrycombo.value, entrycombo.value, false, true);
    droplistcombo.selectedIndex = droplistcombo.options.length - 1;
  } else {
    droplistcombo.selectedIndex = 0;
  }
  entrycombodiv.style.visibility = "hidden";
  droplistcombodiv.style.visibility = "inherit";
}

/** Set the multilingual for the combo.
 *  @param entity The list name.
 *  @param value The value to add.
 */
function cs_SetCombo( entity, value ) {
  var combo = CSForm.getField( entity ).getChoices();
  var index = -1;
  //  Empty list.
  if (combo.getCount() == 0) {
    if (value.length > 0) {
      combo.insertAt(0, value, value);
    } else {
      combo.insertAt(0, "", CS_CHOOSE_COMBO_STR);
    }
    combo.insertAt(1, "DFS__OtherInCombo", CS_OTHER_COMBO_STR);
    index = 0;
  } else {  //  List not empty.
    //  Seek selected.
    var found = false;
    for(var i= 0; (i < combo.getCount()) && (!found); i++) {
      if(combo.getAt(i, false) == value){
        index = i;
        found = true;
      }
    }
    //  Add value.
    if ((value.length > 0) && (!found)) {
      combo.insertAt(0, value, value);
      index = 0;
    }
    combo.insertAt(combo.getCount(), "DFS__OtherInCombo", CS_OTHER_COMBO_STR);
  }
  if (index >= 0) {
    combo.setSelections( [index] );
  }
}

/** Create a new structure for the calculation.
 *  Read the document.htmlform.DFS__calculationsTarget {targetFieldName, functionName, order, operandsFieldName[]} array,
 *  and convert it in the document.htmlform.DFS__calculationsOperand {operandFieldName, targetIndex[]} array.
 *  The order of the target is the order of the calculations.
 */
function cs_CalculationStructure() {
  // For all operand.
  var calculationsTarget = document.htmlform.DFS__calculationsTarget;
  var calculationsOperand = document.htmlform.DFS__calculationsOperand;
  for (var calculation in calculationsTarget) {
    for (var operandIndex = 0; operandIndex < calculationsTarget[calculation].operandsFieldName.length; operandIndex++) {
      var operandInCalculation = calculationsTarget[calculation].operandsFieldName[operandIndex];
      // Add the reference in DFS__calculationsOperand.
      if (calculationsOperand[operandInCalculation] == null) {
        calculationsOperand[operandInCalculation] = new Object();
        calculationsOperand[operandInCalculation].operandFieldName = operandInCalculation;
        calculationsOperand[operandInCalculation].targetIndex = new Array();
      }
      var lastIndex = calculationsOperand[operandInCalculation].targetIndex.length;
      calculationsOperand[operandInCalculation].targetIndex[lastIndex] = calculation;
    }
  }
  // Sort.
  for (var calculation in calculationsOperand) {
    var targetIndex = calculationsOperand[calculation].targetIndex;
    targetIndex.sort(function(a, b) {
      return (calculationsTarget[a].order - calculationsTarget[b].order);
    });
  }
//  // Display
//  for (var calculation in calculationsOperand) {
//    var targets = "  Targets: ";
//    for (i = 0; i < calculationsOperand[calculation].targetIndex.length; i++) {
//      targets += calculationsOperand[calculation].targetIndex[i];
//      targets += "; ";
//    }
//    alert( "FieldName: " + calculationsOperand[calculation].operandFieldName + targets );
//  }
}

/** Execute all calculation involved with this field.
 *  @param textField The text entry field.
 */
function cs_CalculationAction(entryTextField) {
  var operand = document.htmlform.DFS__calculationsOperand[entryTextField.name];
  if (operand) {
//    alert( "Calculation on: " + entryTextField.name + "; Number of targets: " + operand.targetIndex.length );
    for (var targetIndex = 0; targetIndex < operand.targetIndex.length; targetIndex++) {
      var targetName = operand.targetIndex[targetIndex];
//      alert( "Target: " + targetName + "; Index: " + targetIndex );
      var target = document.htmlform.DFS__calculationsTarget[targetName];
      var result = 0;
      var operands = new Array();
      for (var i = 0; i < target.operandsFieldName.length; i++) {
        var tmpValue = document.htmlform[target.operandsFieldName[i]];
        if (tmpValue.rsvd == null) {
          if (CSExt.validate( tmpValue, "loose" ) ) {
            CSExt.format( tmpValue );
          }
        }
        if (tmpValue.rsvd != null) {
          var powers = Math.pow( 10, tmpValue.fmtnmbr.dp );
          operands[i] = Math.round(tmpValue.rsvd.ival * powers ) / powers;
          //alert( tmpValue.name + ".rsvd.ival: " + tmpValue.rsvd.ival );
        } else {
          // (untyped) hidden fields take this path
          operands[i] = (tmpValue.value == "") ? 0 : parseFloat(tmpValue.value);
          //alert( tmpValue.name + ".value: " + tmpValue.value);
        }
        
      }
      // Do the calculation.
      switch(target.functionName) {
        // Add
        case "sum":
          result = 0;
          for (var operandIndex = 0; operandIndex < operands.length; operandIndex++) {
            result += operands[operandIndex];
          }
        break;
        // Subtract
        case "dif":
          result = operands[0];
          for (var operandIndex = 1; operandIndex < operands.length; operandIndex++) {
            result -= operands[operandIndex];
          }
        break;
        // Multiply
        case "product":
          result = operands[0];
          for (var operandIndex = 1; operandIndex < operands.length; operandIndex++) {
            result *= operands[operandIndex];
          }
        break;
        // Divide
        case "div":
          result = operands[0];
          for (var operandIndex = 1; operandIndex < operands.length; operandIndex++) {
            result /= operands[operandIndex];
          }
        break;
        // Minimum
        case "min":
          result = operands[0];
          for (var operandIndex = 1; operandIndex < operands.length; operandIndex++) {
            if (operands[operandIndex] < result) {
              result = operands[operandIndex];
            }
          }
        break;
        // Maximum
        case "max":
          result = operands[0];
          for (var operandIndex = 1; operandIndex < operands.length; operandIndex++) {
            if ((operands[operandIndex]) > result) {
              result = operands[operandIndex];
            }
          }
        break;
        // Average
        case "avg":
          result = 0;
          for (var operandIndex = 0; operandIndex < operands.length; operandIndex++) {
            result += operands[operandIndex];
          }
          result /= operands.length;
        break;
        // Count non-empty
        case "nonempty":
          result = 0;
          for (var operandIndex = 0; operandIndex < operands.length; operandIndex++) {
            if (document.htmlform[target.operandsFieldName[operandIndex]].value.length > 0) {
              result++;
            }
          }
        break;
      }
      var targetField = CSForm.getField( targetName );

      //massage the result
      var resultStr = "" + result;
      switch (resultStr) {
        case "Infinity":
        case "-Infinity":
        case "NaN":
          resultStr = "0";
          break;
        default:
          if (document.htmlform[targetName].fmtnmbr) {
            var resultStrTemp = resultStr.replace( /\./ , document.htmlform[targetName].fmtnmbr.ds);
            resultStr = resultStrTemp;
          }
      }
      
      // Refresh the result.
      //alert ( "target field: " + targetName + "; operands:{" + operands.toString() + "} result:" + resultStr );
      targetField.setValue( resultStr );
      //alert( targetName + " updated:" + targetField.getValue() + "; Index: " + targetIndex);
    }
  }
}

/** Send request to server to manage attachments.
 *  @param sURL The URL to the server.
 */
function cs_ManageAttachments( sURL ) {
  var fAction = document.htmlform.DFS__Action;
  var fURL      = document.htmlform.DFS__SubmitURL;
  var useURL    = sURL;
  //  Get dynamic submission URL if any. (Remove typeof latter when designer/server builds match)
  if (fURL !=  null && fURL.value != null && fURL.value.length != 0) {
    useURL = fURL.value;
  }
  if (fAction == null || useURL == "") {
    alert( CS_ERR_NOTPUBLISHED );
    return;
  }
  fAction.value = "RoutePrepareAttachments";
  // field locking
  cs_prepare_for_submit();
  //document.htmlform.submit();
  var urlstr = document.htmlform.DFS__SubmitURL.value;
  cs_submit_xfdf_load_xfdf(urlstr, "");
  var redirect = document.htmlform.DFS__RedirectURL.value;
  if ((redirect != null) && (redirect.length > 0)) {
    location.replace(redirect);
  }
}


CSExt.OnButtonClick_bEP.Features = function( btn ) {

  var storf = document.htmlform[ btn.name.substr(5) ]; // chop "DFS__"

  if ((btn.name.substr(0, 5) == "DFS__") && storf && (storf != null) && !storf.readOnly && ((storf.authWith == "clickthrough") || (storf.authWith == "password"))) {
    var username = CS_DIGITAL_APPROVE_USER;
    if (document.htmlform.LF__User && document.htmlform.LF__User.value != "")
      username = document.htmlform.LF__User.value;
    var dname = CS_DIGITAL_APPROVE_USER;
    if (document.htmlform.DFS__DisplayName && document.htmlform.DFS__DisplayName.value.length > 0)
      dname = document.htmlform.DFS__DisplayName.value;
    var todaydate = new Date().toString();
    var formname = document.htmlform.DFS__title;
    
    var dispStr = CS_FormatMessage( CS_DIGITAL_APPROVE_CLICK,dname,todaydate,storf.affirmation,storf.role,formname,storf.name,storf.description );

    if ( storf.authWith == "clickthrough" ) { // handle ct
    
      if ( storf.value == "" ) {
        if (confirm(dispStr)) {
          CS_SetSig( btn, storf, username, dname, todaydate );
        }

      } else { // already signed
        if (CS_ClearPermission( storf, username )) { 
          if (confirm( CS_DIGITAL_APPROVE_CLEAR_MSG )) {
            CS_ClearSig( btn, storf );
          }
        }
      }

    } else if (storf.authWith == "password" ) { // handle pw
      if ( storf.value == "") {
        if (confirm( CS_DIGITAL_APPROVE_SUBMIT )) {
          // do the submit
          var oldRequired = storf.required;
          storf.required = false;
          document.htmlform.DFS__Action.value = "SignatureDoSubmit";
          document.htmlform.DFS__Field.value = storf.name;
          var isValid = csformsubmit();
          if (isValid) isValid = cs_OnSubmitLookup();
          if (isValid) {
            cs_prepare_for_submit();
            var redirect = document.htmlform.DFS__RedirectURL.value;
            if ((redirect != null) && (redirect.length > 0)) {
              location.replace(redirect);
            } else {
              document.htmlform.submit();
            }
          }
          storf.required = oldRequired;
        }
      } else {
        if (CS_ClearPermission( storf, username )) {
          if (confirm( CS_DIGITAL_APPROVE_CLEAR_MSG )) {
            CS_ClearSig( btn, storf );        
          }
        }
      }
    }
  }
}

function CS_SetSig( btn, storf, uname, dname, date ) {
  var saveVal = uname + "\t" + dname + "\t" + date;      
  storf.value = saveVal;
  CS_RefreshSig( btn, storf, false );
}

function CS_ClearSig( btn, storf ) {
  storf.value = "";
  CS_RefreshSig( btn, storf, false );
}

function CS_ClearPermission( storf, uname ) {
  var permission = false;
  var parseArr = storf.value.split("\t");

  if (storf.clearPolicy == "all")
    permission = true;

  if (storf.clearPolicy == "signer" && uname==parseArr[0])
    permission = true;

  return permission;
}

function CS_RefreshSig( btn, storf, init ) {
  // on initialize (init=true), don't unlock anything
  if (!btn) return;
  if (!storf) return;
  
  var locking = (storf.value != "");

  if (locking) {
    if (btn.DFS__storecolor)
      btn.style.backgroundColor = btn.DFS__storecolor;
    var parseArr = storf.value.split("\t");
    var fontstr = '\"Monotype Corsiva\"';
    btn.innerHTML = "<div><span style='font-family: " + fontstr + ", cursive;'>"+ parseArr[1] + "</span><br/>" + parseArr[2] + "</div>";
  } else {
    btn.innerHTML = "<div>" + storf.description + "</div>";
    btn.DFS__storecolor = btn.style.backgroundColor;
    btn.style.backgroundColor = "#C0C0C0";
  }
  var lockSet = false;
  if ( locking ) lockSet = true;

  if (document.htmlform.DFS__fl && document.htmlform.DFS__fl[storf.name] ) {

    var formobj = new CSForm_Obj( document.htmlform );
    var numfields = formobj.getNumberOfFields();
    var idx = 0;
    if (document.htmlform.DFS__fl[storf.name].all) {
      for( idx=0; idx < numfields; idx++ ) {
        if (!init || lockSet)
          formobj.getField( idx ).setReadOnly( lockSet );
      }
    
    } else if (document.htmlform.DFS__fl[storf.name].these) {
      for( var fname in document.htmlform.DFS__fl[storf.name].these ) {
        var namedfld = new CSField_Obj( document.htmlform[document.htmlform.DFS__fl[storf.name].these[fname]] );
          if (!init || lockSet)
            namedfld.setReadOnly( lockSet );
      }

    } else if (document.htmlform.DFS__fl[storf.name].except) {
      for( idx=0; idx < numfields; idx++ ) {
        var numberedfld = formobj.getField( idx );
        var name = numberedfld.getName();
        var excepted = false;
        for ( var jdx = 0; jdx < document.htmlform.DFS__fl[storf.name].except.length; jdx++ ) {
          if ( document.htmlform.DFS__fl[storf.name].except[jdx] == name ) excepted = true;
        }
        if (!excepted)
          if (!init || lockSet)
            numberedfld.setReadOnly( lockSet );
      }
    }
  }
}

CSExt.Form_OnLoad_bEP.Sigs = function( f ) {
  var hf = document.htmlform;
  var formobj = new CSForm_Obj( hf );
  formobj.getNumberOfFields();
  cs_prepare_after_reset(true);
}

CSExt.Form_OnLoad_bEP.Format = function( f ) {
  var hf = document.htmlform;
  var formobj = new CSForm_Obj( hf );
  formobj.getNumberOfFields();
  var entries = hf.DFS__UserFieldList;
  for (var idx = 0; idx < entries.length; idx++) {
    CSExt.format( hf[entries[idx]] );
  }
}

/** Perform the action selected in the action list.
 */
function cs_PerformActionList() {
  var dfsAction = document.htmlform.DFS__ActionList.options[document.htmlform.DFS__ActionList.selectedIndex].value;
  document.htmlform.DFS__Action.value = dfsAction;
  var doSubmit = true;
  //  Reset.  (note that with workflow plug-ins, the Action string can be like "RouteResetForm:Label=WFReset")
  var delimLoc = dfsAction.indexOf(":");
  var searchStr = dfsAction;
  if (delimLoc != -1)
      searchStr = dfsAction.substring(0, delimLoc);
      
  if (searchStr.indexOf("Reset") != -1) {
    document.htmlform.reset();
    cs_prepare_after_reset(false);
    doSubmit = false;
    // TODO: if EventID.value is not empty, we need to do a full submit and let the server reset
  }
  //  Validation
  if (dfsAction.length == 0) {
    doSubmit = false;
  } else
  if ((dfsAction.indexOf("Reset") < 0) && (dfsAction.indexOf("Save") < 0)) {
    doSubmit = csformsubmit();
  }
  //  Lookup validation
  if (doSubmit) doSubmit = cs_OnSubmitLookup();
  // Submit
  if (doSubmit) {
    cs_prepare_for_submit();
    var redirect = document.htmlform.DFS__RedirectURL.value;
    if ((redirect != null) && (redirect.length > 0)) {
      location.replace(redirect);
    } else {
      document.htmlform.submit();
    }
  }
}

