// Our section twisties
function bodySectionTwisty(linkEl,action) {
  var showEl=linkEl.parentNode.firstChild
  var hideEl=linkEl.parentNode.lastChild
  var bodyEl=linkEl.parentNode.parentNode.lastChild
  if (action=='show') {
    showEl.style.display='none'
    hideEl.style.display='inline'
    bodyEl.style.display='block'
  } else {
    showEl.style.display='inline'
    hideEl.style.display='none'
    bodyEl.style.display='none'
  }
}
// Variable used to track last show dialogue box
var dialogueBoxLastId;
function popupDialogue(boxId,relativeTo) {
  var boxEl=getel(boxId)
  if (boxId==dialogueBoxLastId && boxEl.style.display=='block') {
    return
  }
  boxEl.style.display = 'block'
  var viewPortWidth=(document.documentElement && document.documentElement.clientWidth) || (document.body && document.body.clientWidth) || 2
  var leftPos=(viewPortWidth/2)-(boxEl.clientWidth/2)
  if (leftPos<0) {
    leftPos=0
  }
  if (relativeTo) {
    var topPos=relativeTo.offsetHeight + relativeTo.clientHeight
  } else {
    var topPos=document.body.scrollTop || 100
  }
  boxEl.style.left = leftPos + 'px'
  boxEl.style.top = topPos + 'px'
  dialogueBoxLastId=boxId
}

// Variable used to track last accessed help
var fieldHelpLastText;
// Perform the field help popup
function fieldHelp(linkEl) {
  var divEl=getel('fieldHelpDiv')
  if(divEl.style.display=='block' && linkEl.title==fieldHelpLastText) {
    divEl.style.display='none'
    return
  }
  fieldHelpLastText=linkEl.title
  divEl.style.display='none'
  var helpTextNode=document.createTextNode(linkEl.title)
  linkElPos=getElementXY(linkEl)
  tdPos=getElementXY(linkEl.parentNode.previousSibling)
  divEl.lastChild.replaceChild(helpTextNode,divEl.lastChild.firstChild)
  divEl.style.width=linkEl.parentNode.offsetWidth+linkEl.parentNode.previousSibling.offsetWidth-2 + 'px'
  positionElement(divEl, tdPos[0], linkElPos[1]+linkEl.offsetHeight+2, 1)
  divEl.style.display='block'
}
// Variable used to track last accessed help
var expFieldHelpLastText;
// Perform the field help popup
function expFieldHelp(linkEl) {
  var divEl=getel('fieldHelpDiv')
  if(divEl.style.display=='block' && linkEl.title==expFieldHelpLastText) {
    divEl.style.display='none'
    return
  }
  expFieldHelpLastText=linkEl.title
  divEl.style.display='none'
  var helpTextNode=document.createTextNode(linkEl.title)
  linkElPos=getElementXY(linkEl)
  tdPos=getElementXY(linkEl.parentNode)
  divEl.lastChild.replaceChild(helpTextNode,divEl.lastChild.firstChild)
  //  divEl.style.width=(linkEl.parentNode.offsetWidth-2) + 'px'
  divEl.style.width='200px'
  positionElement(divEl, tdPos[0], linkElPos[1]+linkEl.offsetHeight+2, 1)
  divEl.style.display='block'
}
// Toggle field readonlyness and change colours to indicate
function makeFieldReadOnly(fieldEl,value) {
    fieldEl.readOnly=true
    fieldEl.style.backgroundColor='#dddddd'
    fieldEl.style.color='#444444'
    fieldEl.value=value
}
function makeFieldEditable(fieldEl,value) {
    fieldEl.readOnly=false
    fieldEl.style.backgroundColor=''
    fieldEl.style.color=''
    fieldEl.value=value
}
// When allowing picking or new entry this warns if trying to enter value into field.
function recordInfoEntryWarning(checkFieldId,recordType,key) {
  if (key) {
    checkFieldId+='___'+key;
  }
  var recordField=getel(checkFieldId)
  var recordId=formFieldGetValue([recordField])
  if(recordId) {
    alert('Please clear the selected ' + recordType + ' before entering a new ' + recordType)
  }
}
// Set up aliases for actual uses of the above function
function supplierEntryWarning(key) { recordInfoEntryWarning('picker_field_supplierPicker','supplier',key); }
function supplierContactEntryWarning(key) { recordInfoEntryWarning('picker_field_supplierContactPicker','supplierContact',key); }
function deptEntryWarning(key) { recordInfoEntryWarning('picker_field_deptPicker','department',key); }
function deptContactEntryWarning(key) { recordInfoEntryWarning('picker_field_deptContactPicker','department contact',key); }

// **** These are used on the contract entry ****
// parentOrgId is used by some filters on pickers
var parentOrgId='';

function addContractAdditionalSupplier(spaceName) {
  var supplierAddHelper=getel('supplierAddHelper')
  var tbodyTemplateEl=getel('supplierSection___TEMPLATE')
  var j=supplierSectionCounter
  supplierSectionCounter+=1
  // done this way as IE gets upset at messing with innerHTML on table
  // elements
  supplierAddHelper.innerHTML='<table><tbody id="supplierSection___' + j + '">' + tbodyTemplateEl.innerHTML.replace(/___TEMPLATE/g,'___' + j) + '</tbody></table>'
  var tbody=getel("supplierSection___" + j)
  tbodyTemplateEl.parentNode.insertBefore(tbody,tbodyTemplateEl)
}
function deptOnChange(recordType) {
  var dept=getel('picker_field_deptPicker');
  var value=formFieldGetValue([dept],1);
  var displayEl=getel('DepartmentDisplay');
  if(value && value[0]) {
    displayValue=value[1];
    displayEl.style.fontStyle="normal";
  } else {
    displayValue="(none selected)";
    displayEl.style.fontStyle="italic";
  }    
  displayEl.firstChild.nodeValue=displayValue;
  picker_popupHideEv('deptPicker');
}
function lookupDept() {
  var pickerFrame=getel('picker_popupiframe_deptPicker')
  if(pickerFrame.contentWindow && pickerFrame.contentWindow.updateFilter) {
    pickerFrame.contentWindow.updateFilter()
  }
  picker_showPopupPicker('deptPicker')
}
function deptContactOnChange() {
  var deptContact=getel('picker_field_deptContactPicker')
  var value=formFieldGetValue([deptContact],1)
  var displayEl=getel('DepartmentContactDisplay');
  if(value && value[0]) {
    displayValue=value[1];
    displayEl.style.fontStyle="normal";
  } else {
    displayValue="(none selected)";
    displayEl.style.fontStyle="italic";
  }    
  displayEl.firstChild.nodeValue=displayValue;
  picker_popupHideEv('deptContactPicker');
}
function lookupDeptContact() {
  var pickerFrame=getel('picker_popupiframe_deptContactPicker')
  if(pickerFrame.contentWindow && pickerFrame.contentWindow.updatePrefixFilter) {
    pickerFrame.contentWindow.updatePrefixFilter()
  }
  picker_showPopupPicker('deptContactPicker')
}
function orgOnChange() {
  // clear the department picker if it has a value set
  var dept=getel('picker_field_deptPicker')
  var value=formFieldGetValue([dept],1)
  if(value && value[0]) {
    picker_clearValue('deptPicker');
  }
  var deptContact=getel('picker_field_deptContactPicker')
  value=formFieldGetValue([deptContact],1)
  if(value && value[0]) {
    picker_clearValue('deptContactPicker');
  }
}
function addSupplierAdditionalSite() {
  var supplierAddHelper=getel('siteAddHelper')
  var tbodyTemplateEl=getel('siteSection___TEMPLATE')
  var j=siteSectionCounter
  siteSectionCounter+=1
  // done this way as IE gets upset at messing with innerHTML on table
  // elements
  supplierAddHelper.innerHTML='<table><tbody id="siteSection___' + j + '">' + tbodyTemplateEl.innerHTML.replace(/___TEMPLATE/g,'___' + j) + '</tbody></table>'
  var tbody=getel("siteSection___" + j)
  tbodyTemplateEl.parentNode.insertBefore(tbody,tbodyTemplateEl)
}
function contractFormRefreshSupplierDependent(instanceId,refreshSites,refreshContacts,pickSiteId,pickContactId) {
  if (!refreshSites && !refreshContacts) {
    return;
  }
  var urlArgs='';
  var valueEl=getel('supplier___' + instanceId);
  var supplierId=valueEl.value;

  if (refreshSites) {
    urlArgs+='&refreshSites=1';
    if (pickSiteId) {
      urlArgs+='&supplierSiteId=' + encodeURIComponent(pickSiteId);
    }
    var siteSpan=getel('SitesSelectSpan___' + instanceId);
    var noSupSiteSpan=getel('SitesMsgSelectSupplier___' + instanceId);
    var noSiteSpan=getel('SitesMsgNoSites___' + instanceId);
    var newSiteLink=getel('newSupplierSiteLink___' + instanceId);
    var updatingSiteSpan=getel('SitesMsgUpdating___' + instanceId);

    siteSpan.style.display='none';
    noSiteSpan.style.display='none';
    if (supplierId) {
      newSiteLink.style.display='inline';
      noSupSiteSpan.style.display='none';      
      updatingSiteSpan.style.display='inline';
    } else {
      newSiteLink.style.display='none';
      noSupSiteSpan.style.display='inline';
      updatingSiteSpan.style.display='none';
    }
  }

  if (refreshContacts) {
    urlArgs+='&refreshContacts=1';
    if (pickContactId) {
      urlArgs+='&supplierContactId=' + encodeURIComponent(pickContactId);
    }

    var contactSpan=getel('ContactsSelectSpan___' + instanceId);
    var noSupContactSpan=getel('ContactsMsgSelectSupplier___' + instanceId);
    var noContactSpan=getel('ContactsMsgNoContacts___' + instanceId);
    var newContactLink=getel('newSupplierContactLink___' + instanceId);
    var updatingContactSpan=getel('ContactsMsgUpdating___' + instanceId);

    contactSpan.style.display='none';
    noContactSpan.style.display='none';
    if (supplierId) {
      newContactLink.style.display='inline';
      noSupContactSpan.style.display='none';
      updatingContactSpan.style.display='inline';
    } else {
      newContactLink.style.display='none';
      noSupContactSpan.style.display='inline';
      updatingContactSpan.style.display='none';
    }
  }
  var updateIframe=getel('supplierDependentRefresh___' + instanceId);
  updateIframe.src=execPrefix +'/contractpickers?pickerType=refreshSupplierDependentPicklists&instanceId=' + encodeURIComponent(instanceId) + '&supplierId=' + encodeURIComponent(supplierId) + urlArgs;
}
function contractFormPickerSetValue(pickerType,instanceId,value,displayValue,otherArgs) {
  otherArgs = otherArgs ? otherArgs : {};
  var keyExtra=instanceId ? '___' + instanceId : '';
  var valueEl=getel(pickerType + keyExtra);
  var displayEl=getel(pickerType + 'Display' + keyExtra);
  valueEl.value=value;
  if (displayValue=="") {
    displayValue="(none selected)";
    displayEl.style.fontStyle="italic";
  } else {
    displayEl.style.fontStyle="normal";
  }
  displayEl.firstChild.nodeValue=displayValue;
  if (pickerType=='supplier') {
    var pickSiteId=otherArgs['pickPrimarySite'] ? 'primary' : '';
    contractFormRefreshSupplierDependent(instanceId,1,1,pickSiteId);
  }
}
function contractFormPicker(pickerType,positionElement,instanceId,clickEvent) {
  if(clickEvent) {
    clickEvent.cancelBubble = true;
  }
  var instanceId = instanceId ? instanceId : '';
  var iFrame=getel('contractPickerFrame');
  var iFrameDiv=getel('contractPickerFrameDiv');
  var otherArgs='';
  if (pickerType=='newSupplierSite' || pickerType=='newSupplierContact') {
    supplierId=getel('supplier___' + instanceId).value;
    otherArgs='&supplierId=' + encodeURIComponent(supplierId);
  } else if (pickerType=='newDepartment' || pickerType=='newDepartmentContact' || pickerType=='existingDepartment' || pickerType=='existingDepartmentContact') {
    var orgEl=getel('picker_field_parentOrgPicker');
    if (orgEl) {
      org=parent.formFieldGetValue([orgEl]);
    } else {
      org=parent.parentOrgId;
    }
    otherArgs+='&organisationId=' + encodeURIComponent(org)
    if (pickerType=='newDepartmentContact' || pickerType=='existingDepartmentContact') {
      var deptEl=getel('department');
      if (deptEl && deptEl.value) {
        otherArgs+='&departmentId=' + encodeURIComponent(deptEl.value);
      }
    }
  }
  iFrame.src=execPrefix + '/contractpickers?pickerType=' + encodeURIComponent(pickerType) + '&instanceId=' + encodeURIComponent(instanceId) + '&space=' + encodeURIComponent(spaceName) + otherArgs;
  positionElementRelativeTo(iFrameDiv,positionElement,20,0,1);
  iFrameDiv.style.display='block';
  if (window.addEventListener) {
    window.addEventListener("click", contractFormPickerHideEvent,false)
  } else if (document.attachEvent) {
    document.attachEvent("onclick",contractFormPickerHideEvent)
  }
  return false;
}
function contractFormPickerHideEvent() {
  var iFrame=getel('contractPickerFrame');
  var iFrameDiv=getel('contractPickerFrameDiv');
  iFrameDiv.style.display='none';
  if (window.removeEventListener) {
    window.removeEventListener("click",contractFormPickerHideEvent,false)
  } else if (document.detachEvent) {
    document.detachEvent("onclick",contractFormPickerHideEvent)
  }
  iFrame.src='about:blank';
}
function contractFormPickerFrameResize(frDocument) {
  var iFrame=getel('contractPickerFrame');
  var iFrameDiv=getel('contractPickerFrameDiv');
  popupframeautosize(iFrameDiv,iFrame,frDocument);
}
