function update_break_time(start_val, end_val, break_time_el, worked_time_el, start_date_time_el, end_date_time_el, date_el) {
  var b_str = break_time_el.val();
  var b_spstr = b_str.split(":", 2);
  var b_hours = Math.round(parseFloat(b_spstr[0]));
  if (isNaN(b_hours)) {
    b_hours = 0;
  }
  var b_mins = Math.round(parseFloat(b_spstr[1]));
  if (isNaN(b_mins)) {
    b_mins = 0;
  }
  // set the break time val to confirm
  var d_b_mins = b_mins;
  if (d_b_mins < 10) {
    d_b_mins = '' + '0' + d_b_mins;
  }
  break_time_el.val(b_hours + ':' + d_b_mins);

  var s_str = start_val.val();
  var s_spstr = s_str.split(":", 2);
  var s_hours = Math.round(parseFloat(s_spstr[0]));
  var s_mins = Math.round(parseFloat(s_spstr[1]));

  var e_str = end_val.val();
  var e_spstr = e_str.split(":", 2);
  var e_hours = Math.round(parseFloat(e_spstr[0]));
  var e_mins = Math.round(parseFloat(e_spstr[1]));

  var worked_total_mins = (e_hours - s_hours - b_hours) * 60 + (e_mins - s_mins - b_mins);
  if (worked_total_mins < 0) {
    worked_total_mins = 0;
  }
  var worked_hours = Math.floor(worked_total_mins / 60);
  var worked_mins = worked_total_mins - (worked_hours * 60);
  var worked_d_mins = worked_mins;
  if (worked_d_mins < 10) {
    worked_d_mins = '' + '0' + worked_d_mins;
  }
  worked_time_el.val(worked_hours + ':' + worked_d_mins);

  var date_el_str = date_el.val();
  var date_el_parts = date_el_str.split('-');

  var d_s_hours = s_hours;
  if (d_s_hours < 10) {
    d_s_hours = '' + '0' + d_s_hours;
  }
  var d_s_mins = s_mins;
  if (d_s_mins < 10) {
    d_s_mins = '' + '0' + d_s_mins;
  }
  start_date_time_el.val(date_el_str + "T" + d_s_hours + ":" + d_s_mins);

  var d = new Date(date_el_parts[0], date_el_parts[1]-1, date_el_parts[2]);
  var ed = new Date(d.getTime() + (((e_hours * 60) + e_mins) * 60 * 1000));
  // var dmonth = ed.getUTCMonth() + 1;
  var dmonth = ed.getMonth() + 1;
  if (dmonth < 10) {
    dmonth = '0' + dmonth;
  }
  // var dday = ed.getUTCDate();
  var dday = ed.getDate();
  if (dday < 10) {
    dday = '0' + dday;
  }
  // var dhours = ed.getUTCHours();
  var dhours = ed.getHours();
  if (dhours < 10) {
    dhours = '0' + dhours;
  }
  // var dmins = ed.getUTCMinutes();
  var dmins = ed.getMinutes();
  if (dmins < 10) {
    dmins = '0' + dmins;
  }
  // end_date_time_el.val(ed.getUTCFullYear() + '-' + dmonth + '-' + dday + 'T' + dhours + ':' + dmins);
  end_date_time_el.val(ed.getFullYear() + '-' + dmonth + '-' + dday + 'T' + dhours + ':' + dmins);

  // recalc award interpretation here
}

function get_rec_refs() {
  return $("input[name='reconciliation_reference']:checked").map(function () {
    return $(this).val();
  }).get().join(',');
}

function start_focus(id) {
  if (document.getElementById(id)) {
    $("#" + id).focus();
  }
  else {
    setTimeout(function () {
      start_focus(id);
    }, 500);
  }
}

function jq_wait(id, eid) {
  if (document.getElementById(id)) {
    jqueryit(id, eid);
  }
  else {
    setTimeout(function () {
      jq_wait(id, eid);
    }, 500);
  }
}

var account_autocomplete_data;
var account_value_2_id = {};
var account_id_2_value = {};

function load_account_data() {
  if (!account_autocomplete_data) {
    // account auto complete data
    var acc_data = $("#account_autocomplete_data").find("textarea");
    var xmlDoc = '';
    if (acc_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(acc_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(acc_data.val());
      }
      account_autocomplete_data = $(xmlDoc).find("[nodeName='gl-cor:account']").map(function() {
        var desc = $(this).find("[nodeName='gl-cor:accountMainDescription']").text();
        var id = $(this).find("[nodeName='gl-cor:accountMainID']").text();
        var result = {
          value: desc,
          id: id,
          accountMainID : id,
          accountMainDescription : desc,
          accountMainType : $(this).find("[nodeName='gl-cor:accountMainType']").text(),
          accountActive : $(this).find("[nodeName='gl-cor:accountActive']").text()
        };
        account_value_2_id[desc.toLowerCase()] = result;
        account_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      account_autocomplete_data = {};
    }
  }
}

function get_account_data() {
  if (!account_autocomplete_data) {
    load_account_data();
  }
  return account_autocomplete_data;
}

function get_account(str) {
  if (!account_autocomplete_data) {
    load_account_data();
  }
  if (account_id_2_value[str.toLowerCase()]) {
    return account_id_2_value[str.toLowerCase()];
  }
  else if (account_value_2_id[str.toLowerCase()]) {
    return account_value_2_id[str.toLowerCase()];
  }
}

var measurable_autocomplete_data;
var measurable_value_2_id = {};
var measurable_id_2_value = {};

function load_measurable_data() {
  if (!measurable_autocomplete_data) {
    // measurable auto complete data
    var meas_data = $("#measurable_autocomplete_data").find("textarea");
    var xmlDoc = '';
    if (meas_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(meas_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(meas_data.val());
      }
      measurable_autocomplete_data = $(xmlDoc).find("[nodeName='gl-bus:measurable']").map(function() {
        var desc = $(this).find("[nodeName='gl-bus:measurableDescription']").text();
        var id = $(this).find("[nodeName='gl-bus:measurableID']").text();
        var result = {
          value: desc,
          id: id,
          measurableUnitOfMeasure: $(this).find("[nodeName='gl-bus:measurableUnitOfMeasure']").text(),
          measurableCode: $(this).find("[nodeName='gl-bus:measurableCode']").text(),
          measurableCodeDescription: $(this).find("[nodeName='gl-bus:measurableCodeDescription']").text(),
          measurableID: $(this).find("[nodeName='gl-bus:measurableID']").text(),
          measurableDescription: desc,
          measurableCostPerUnit: $(this).find("[nodeName='gl-bus:measurableCostPerUnit']").text(),
          measurableActive: $(this).find("[nodeName='gl-bus:measurableActive']").text(),
          measurableApplyTax: $(this).find("[nodeName='gl-soc:measurableApplyTax']").text(),
          measurableApplySuper: $(this).find("[nodeName='gl-soc:measurableApplySuper']").text(),
          measurableApplyLeave: $(this).find("[nodeName='gl-soc:measurableApplyLeave']").text(),
          measurableTaxAuthority: $(this).find("[nodeName='gl-soc:measurableTaxAuthority']").text(),
          measurableTaxCode: $(this).find("[nodeName='gl-soc:measurableTaxCode']").text(),
          measurableRateMultiplier: $(this).find("[nodeName='gl-soc:measurableRateMultiplier']").text(),
          measurableAccountMainID: $(this).find("[nodeName='gl-soc:measurableAccountMainID']").text(),
          measurablePaymentType: $(this).find("[nodeName='gl-soc:measurablePaymentType']").text()
        };
        measurable_value_2_id[desc.toLowerCase()] = result;
        measurable_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      measurable_autocomplete_data = {};
    }
  }
}

function get_measurable_data() {
  if (!measurable_autocomplete_data) {
    load_measurable_data();
  }
  return measurable_autocomplete_data;
}

function get_measurable(str) {
  if (!measurable_autocomplete_data) {
    load_measurable_data();
  }
  if (measurable_id_2_value[str.toLowerCase()]) {
    return measurable_id_2_value[str.toLowerCase()];
  }
  else if (measurable_value_2_id[str.toLowerCase()]) {
    return measurable_value_2_id[str.toLowerCase()];
  }
}

function get_measurable_by_payment_type(paymenttype) {
  var filtered_data = new Array();
  var source_data = get_measurable_data();
  for (var i in source_data) {
    if (source_data[i].measurablePaymentType == paymenttype) {
      filtered_data[filtered_data.length] = source_data[i];
    }
  }
  return filtered_data;
}

var measurable_earnings_data;

function get_measurable_earnings_data() {
  if (!measurable_earnings_data) {
    measurable_earnings_data = new Array();
    var source_data = get_measurable_data();
    for (var i in source_data) {
      if (source_data[i].measurablePaymentType != 'time') {
        measurable_earnings_data[measurable_earnings_data.length] = source_data[i];
      }
    }
  }
  return measurable_earnings_data;
}

var taxes_autocomplete_data;
var taxes_value_2_id = {};
var taxes_id_2_value = {};

function load_taxes_data() {
  if (!taxes_autocomplete_data) {
    // taxes auto complete data
    var tax_data = $("#taxes_autocomplete_data").find("textarea");
    var xmlDoc = '';
    if (tax_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(tax_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(tax_data.val());
      }
      taxes_autocomplete_data = $(xmlDoc).find("[nodeName='gl-cor:taxes']").map(function() {
        var desc = $(this).find("[nodeName='gl-cor:taxDescription']").text();
        var id = $(this).find("[nodeName='gl-cor:taxCode']").text();
        var result = {
          value: desc,
          id: id,
          taxCode : id,
          taxDescription : desc,
          taxTableCode : $(this).find("[nodeName='gl-cor:taxTableCode']").text(),
          taxAuthority : $(this).find("[nodeName='gl-cor:taxAuthority']").text(),
          taxPercentageRate : $(this).find("[nodeName='gl-cor:taxPercentageRate']").text(),
          taxScale : $(this).find("[nodeName='gl-soc:taxScale']").text(),
          taxLeaveCode : $(this).find("[nodeName='gl-soc:taxLeaveCode']").text()
        };
        taxes_value_2_id[desc.toLowerCase()] = result;
        taxes_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      taxes_autocomplete_data = {};
    }
  }
}

function get_taxes_data() {
  if (!taxes_autocomplete_data) {
    load_taxes_data();
  }
  return taxes_autocomplete_data;
}

function get_taxes(str) {
  if (!taxes_autocomplete_data) {
    load_taxes_data();
  }
  if (taxes_id_2_value[str.toLowerCase()]) {
    return taxes_id_2_value[str.toLowerCase()];
  }
  else if (taxes_value_2_id[str.toLowerCase()]) {
    return taxes_value_2_id[str.toLowerCase()];
  }
}

var identifierReference_autocomplete_data;
var identifierReference_value_2_id = {};
var identifierReference_id_2_value = {};

function load_identifierReference_data() {
  if (!identifierReference_autocomplete_data) {
    // identifierReference auto complete data
    var idr_data = $("#identifier_autocomplete_data").find("textarea");
    var xmlDoc = '';
    if (idr_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(idr_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(idr_data.val());
      }
      identifierReference_autocomplete_data = $(xmlDoc).find("[nodeName='gl-cor:identifierReference']").map(function() {
        var desc = $(this).find("[nodeName='gl-cor:identifierDescription']").text();
        var id = $(this).find("[nodeName='gl-cor:identifierCode']").text();
        var result = {
          value: desc,
          id: id,
          identifierCode : id,
          identifierDescription : desc,
          identifierType : $(this).find("[nodeName='gl-cor:identifierType']").text(),
          identifierActive : $(this).find("[nodeName='gl-cor:identifierActive']").text()
        };
        identifierReference_value_2_id[desc.toLowerCase()] = result;
        identifierReference_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      identifierReference_autocomplete_data = {};
    }
  }
}

function get_identifierReference_data() {
  if (!identifierReference_autocomplete_data) {
    load_identifierReference_data();
  }
  return identifierReference_autocomplete_data;
}

function get_identifierReference(str) {
  if (!identifierReference_autocomplete_data) {
    load_identifierReference_data();
  }
  if (!str) {
    return null;
  }
  if (identifierReference_id_2_value[str.toLowerCase()]) {
    return identifierReference_id_2_value[str.toLowerCase()];
  }
  else if (identifierReference_value_2_id[str.toLowerCase()]) {
    return identifierReference_value_2_id[str.toLowerCase()];
  }
}

var division_autocomplete_data;
var division_value_2_id = {};
var division_id_2_value = {};

function load_division_data() {
  if (!division_autocomplete_data) {
    // division auto complete data
    var div_data = $("#division_autocomplete_data").find("textarea");
    var xmlDoc = '';
    if (div_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(div_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(div_data.val());
      }
      division_autocomplete_data = $(xmlDoc).find("[nodeName='gl-soc:division']").map(function() {
        var desc = $(this).find("[nodeName='gl-soc:divisionDescription']").text();
        var id = $(this).find("[nodeName='gl-soc:divisionCode']").text();
        var result = {
          value: desc,
          id: id,
          divisionCode : id,
          divisionDescription : desc,
          divisionActive : $(this).find("[nodeName='gl-soc:divisionActive']").text()
        };
        division_value_2_id[desc.toLowerCase()] = result;
        division_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      division_autocomplete_data = {};
    }
  }
}

function get_division_data() {
  if (!division_autocomplete_data) {
    load_division_data();
  }
  return division_autocomplete_data;
}

function get_division(str) {
  if (!division_autocomplete_data) {
    load_division_data();
  }
  if (division_id_2_value[str.toLowerCase()]) {
    return division_id_2_value[str.toLowerCase()];
  }
  else if (division_value_2_id[str.toLowerCase()]) {
    return division_value_2_id[str.toLowerCase()];
  }
}

var leave_autocomplete_data;
var leave_value_2_id = {};
var leave_id_2_value = {};

function load_leave_data() {
  if (!leave_autocomplete_data) {
    // leave auto complete data
    var leave_data = $("#leave_autocomplete_data").find("textarea");

    var xmlDoc = '';

    if (leave_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(leave_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(leave_data.val());
      }
      leave_autocomplete_data = $(xmlDoc).find("[nodeName='gl-soc:leaveEntitlement']").map(function() {
        var desc = $(this).find("[nodeName='gl-soc:leaveDescription']").text();
        var id = $(this).find("[nodeName='gl-soc:leaveCode']").text();
        var result = {
          value: desc,
          id: id,
          leaveCode : id,
          leaveDescription : desc,
          leaveCode : $(this).find("[nodeName='gl-soc:leaveCode']").text(),
          leaveTaxCode : $(this).find("[nodeName='gl-soc:leaveTaxCode']").text(),
          leaveAccrualScale : $(this).find("[nodeName='gl-soc:leaveAccrualScale']").text()
        };
        leave_value_2_id[desc.toLowerCase()] = result;
        leave_id_2_value[id.toLowerCase()] = result;
        return result;
      }).get();
    }
    else {
      leave_autocomplete_data = {};
    }
  }
}

function get_leave_data() {
  if (!leave_autocomplete_data) {
    load_leave_data();
  }
  return leave_autocomplete_data;
}

function get_leave(str) {
  if (!leave_autocomplete_data) {
    load_leave_data();
  }
  if (leave_id_2_value[str.toLowerCase()]) {
    return leave_id_2_value[str.toLowerCase()];
  }
  else if (leave_value_2_id[str.toLowerCase()]) {
    return leave_value_2_id[str.toLowerCase()];
  }
}

var identifier_amount_data;

function load_identifier_amount_data() {
  if (!identifier_amount_data) {
    // leave auto complete data
    var amount_data = $("#identifier_amount_data").find("textarea");

    var xmlDoc = '';

    if (amount_data.length > 0) {
      if (window.DOMParser) {
        var parser=new DOMParser();
        var xmlDoc=parser.parseFromString(amount_data.val(),"text/xml");
      }
      else {
        // Internet Explorer
        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(amount_data.val());
      }
      identifier_amount_data = {};
      $(xmlDoc).find("[nodeName='gl-cor:entryHeader']").each(function() {
        var amount = 0;
        $(this).find("[nodeName='gl-cor:amount']").each(function() {
          var amt = parseFloat($(this).text());
          if (!isNaN(amt)) {
            amount += amt;
          }
        });
        var id = $(this).find("[nodeName='gl-cor:identifierCode']").text().toLowerCase();
        if (!identifier_amount_data[id]) {
          identifier_amount_data[id] = new Array();
        }
        identifier_amount_data[id][identifier_amount_data[id].length] = {
          identifierCode : $(this).find("[nodeName='gl-cor:identifierCode']").text(),
          identifierDescription : $(this).find("[nodeName='gl-cor:identifierDescription']").text(),
          sourceJournalID : $(this).find("[nodeName='gl-cor:sourceJournalID']").text(),
          documentNumber : $(this).find("[nodeName='gl-cor:documentNumber']").text(),
          entryNumber : $(this).find("[nodeName='gl-cor:entryNumber']").text(),
          amount : amount,
          postingDate : $(this).find("[nodeName='gl-cor:postingDate']").text(),
          entryReconciledAmount : $(this).find("[nodeName='gl-soc:entryReconciledAmount']").text(),
          entryReconciliationReference : $(this).find("[nodeName='gl-soc:entryReconciliationReference']").text()
        };
      });
    }
    else {
      identifier_amount_data = {};
    }
  }
}

function get_identifier_amount_data() {
  if (!identifier_amount_data) {
    load_identifier_amount_data();
  }
  return identifier_amount_data;
}

function get_identifier_amounts(str) {
  var ia = get_identifier_amount_data();
  if (ia[str.toLowerCase()]) {
    return ia[str.toLowerCase()];
  }
  return false;
}


function jqueryit(top_el, entity_id) {

  var start = new Date();
  start = start.getTime();

  if (typeof(top_el) == 'string') {
    top_el = $('#' + top_el);
  }


  top_el.find("div.roundbox").wrap('<div class="predialog"><div class="dialog"><div class="bd">'+
    '<div class="c"><div class="s"></div></div></div></div></div>');
  top_el.find('div.predialog > div.dialog')
    .prepend('<div class="hd">'+
      '<div class="c"></div></div>')
    .append('<div class="ft">'+
      '<div class="c"></div></div>');
  top_el.find("div.roundbox").removeClass("roundbox");
  top_el.find("div.predialog").removeClass("predialog");

  // var debug_el = document.getElementById("debug");
  // var o_script_time = (new Date).valueOf();
  // debug_el.innerHTML += "1: " + o_script_time;

  // disable all form controls in read only sections
  top_el.find("*.readonly").find("input").each(function() {
    $(this).attr('disabled','disabled');
  });

  // add sortables
  top_el.find( "#sortable1, #sortable2" ).sortable({
    connectWith: ".connectedSortable"
  }).disableSelection();

  // style the tables
  last_row = 0;
  top_el.find("tbody tr").each(function() {
    last_row = (last_row + 1) % 2;
    if (last_row == 0) {
      $(this).css("background-color", "#EEEEEE");
    }
    else {
      $(this).css("background-color", "#DDDDDD");
    }
  });

  // enter default dates
  top_el.find(".recent_date").each(function() {
    var today = new Date();
    var recent = new Date();
    recent.setDate(today.getDate() - 30);
    $(this).val(recent.getFullYear() + '-' + (recent.getMonth() + 1) + '-' + recent.getDate());
    $(this).removeClass("recent_date");
  });
  top_el.find(".recent_month_date").each(function() {
    var today = new Date();
    var recent = new Date();
    recent.setDate(today.getDate() - 3);
    $(this).val(recent.getFullYear() + '-' + (recent.getMonth() + 1) + '-01');
    $(this).removeClass("recent_month_date");
  });
  top_el.find(".close_month_date").each(function() {
    var today = new Date();
    var recent = new Date();
    recent.setDate(today.getDate() - 3);
    recent.setMonth(recent.getMonth() + 1);
    recent.setDate(0);
    $(this).val(recent.getFullYear() + '-' + (recent.getMonth() + 1) + '-' + recent.getDate());
    $(this).removeClass("close_month_date");
  });
  top_el.find(".close_date").each(function() {
    var today = new Date();
    var close = new Date();
    close.setDate(today.getDate() + 7);
    $(this).val(close.getFullYear() + '-' + (close.getMonth() + 1) + '-' + close.getDate());
    $(this).removeClass("close_date");
  });

  // style the form_entry divs
  last_row = 0;
  top_el.find(".report").find(".form_entry").each(function() {
    last_row = (last_row + 1) % 2;
    if (last_row == 0) {
      $(this).css("background-color", "#EEEEEE");
      // $(this).css("border-bottom", "1px solid #FFFFFF");
      // $(this).css("border-right", "1px solid #FFFFFF");
    }
    else {
      $(this).css("background-color", "#DDDDDD");
      // $(this).css("border-bottom", "1px solid #FFFFFF");
      // $(this).css("border-right", "1px solid #FFFFFF");
    }
  });

  // var count = 0;

  var today = false;

  // $.datepicker.setDefaults({dateFormat: 'dd/mm/yyyy'});
  // top_el.find("input[name='datepicker']").datepicker();
  // top_el.find("input.datepicker").datepicker();

  top_el.find("#tabs").tabs();

  var pa = new Date();
  pa = pa.getTime();

  var pb = new Date();
  pb = pb.getTime();

  var end = new Date();
  end = end.getTime();

  return "jq time = " + (end - start) + "\nto point a = " + (pa - start) + "\na to point b = " + (pb - pa);
}

function format_input_time(el) {
  var t = $(el).val();
  t = t.split(":", 3);
  var hours = parseFloat(t[0]);
  if (isNaN(hours)) {
    hours = 0;
  }
  var mins = parseFloat(t[1]);
  if (isNaN(mins)) {
    mins = 0;
  }
  var display_hours = Math.floor(((hours * 60) + mins) / 60);
  mins = Math.floor(((hours * 60) + mins) - (display_hours * 60));
  if (mins < 10) {
    mins = '' + '0' + mins;
  }
  $(el).val(display_hours + ':' + mins);
}

<!-- drag and drop script -->

var _startX = 0; // mouse starting positions
var _startY = 0;
var _offsetX = 0; // current element offset
var _offsetY = 0;
var _dragElement; // needs to be passed from OnMouseDown to OnMouseMove
var _oldZIndex = 0; // we temporarily increase the z-index during drag
//var _debug = 0; // makes life easier

function OnMouseMove(e) {
  if (e == null) var e = window.event;
  // this is the actual "drag code"
  _dragElement.style.left = (e.clientX + 1) + 'px';
  _dragElement.style.top = (e.clientY + 1) + 'px';
  //_dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px';
  //_debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')';
}

function OnMouseUp(e) {
  _dragElement.value = null;
  _dragElement.style.display = 'none';
  _dragElement = null;
  document.onmousemove = null;
  document.onmouseup = null;
  report_save_div = null;
  // report_view_div = null;
  // report_params = null;
  // copied_params = null;
  copied_div_id = null;
  // copied_element_type = null;
  // copied_include_type = null;
  // copied_view_div_id = null;
}

function dragaccount(account_id, account_description, event, account_div_id, balance_type) {
  if (event == null) event = window.event;
  var account_copied_element = document.getElementById('account_copied_element');
  account_copied_element.value = account_description;
  account_copied_element.account_div_id = account_div_id;
  account_copied_element.balance_type = balance_type;
  _dragElement = account_copied_element;
  _dragElement.style.left = (event.clientX) + 'px';
  _dragElement.style.top = (event.clientY) + 'px';
  _dragElement.style.position = 'absolute';
  _dragElement.style.display = 'block';
  document.onmouseup = OnMouseUp;
  document.onmousemove = OnMouseMove;
}

var copied_params;
var copied_div_id;
var copied_element_type;
var copied_include_type;
var copied_view_div_id;

function dragelement(div_id, description, element_type, include_type, params, event, view_div_id) {
  if (event == null) event = window.event;
  copied_params = params;
  copied_div_id = div_id;
  copied_element_type = element_type;
  copied_include_type = include_type;
  copied_view_div_id = view_div_id;
  var copied_element = document.getElementById('copied_element');
  copied_element.value = description;
  _dragElement = copied_element;
  _dragElement.style.left = (event.clientX) + 'px';
  _dragElement.style.top = (event.clientY) + 'px';
  _dragElement.style.position = 'absolute';
  _dragElement.style.display = 'block';
  document.onmouseup = OnMouseUp;
  document.onmousemove = OnMouseMove;
}

function pasteelement(element_id, paste_div_id, pasteparams) {
  if (!copied_div_id) {
    return;
  }
  var save_copied_div_id = copied_div_id;

  var new_xbrl_info_xml = '<gl-cor:xbrlInfo ' + document.getElementById('xbrlgl_namespaces').value + '>\
      <gl-cor:summaryReportingElement>' + element_id + '</gl-cor:summaryReportingElement>\
      <gl-cor:detailMatchingElement>' + copied_element_type + '</gl-cor:detailMatchingElement>\
      <gl-cor:xbrlInclude>' + copied_include_type + '</gl-cor:xbrlInclude>\
    </gl-cor:xbrlInfo>';

  if (window.DOMParser) {
    var parser = new DOMParser();
    var xml = parser.parseFromString(new_xbrl_info_xml, "text/xml");
  }
  else {
    // Internet Explorer
    var xml = new ActiveXObject("MSXML2.FreeThreadedDomDocument");
    xml.loadXML(new_xbrl_info_xml);

    if (xml.parseError.errorCode!=0) {
       alert("Error in XML\n\nLine " + xml.parseError.line + ": " + xml.parseError.reason);
       return false
    }
  }

  //var fragment = buildFragment2('clipboard_xslt', copied_params, xml);

  //var xbrlinfoelement = document.getElementById(copied_div_id + '_xbrl_info');

  //if (window.DOMParser) {
    //xbrlinfoelement.appendChild(fragment);
  //}
  //else {
    //xbrlinfoelement.innerHTML += fragment;
  //}
// alert('start paste');
  showXSLT2('clipboard_xslt', save_copied_div_id + '_xbrl_info', copied_params, xml, true, function () {
// alert('paste cb 1 copied id = ' + copied_div_id);
// alert('paste cb 1 copied html = ' + document.getElementById(copied_div_id).innerHTML);
    processtemplate('sa_main', copied_view_div_id, 'clipboard_xslt', copied_params, 'xbrlglprocess', save_copied_div_id, 'html_to_xbrlgl', function (data) {
// alert('paste cb 2');
      processtemplate('sa_main', paste_div_id, 'report_xslt', pasteparams, 'report');
      })
    });
}



var report_save_div;
var report_view_div;
var report_params;

var report_last_account_filter = '';
var report_last_taxes_filter = '';
var report_last_filter_type = 'account';
var report_last_mode = 'view';

function dragreportelement(save_div_id, description, params, event, view_div_id) {
  if (event == null) event = window.event;
  report_params = params;
  report_save_div = save_div_id;
  report_view_div = view_div_id;
  var copied_element = document.getElementById('copied_element');
  copied_element.value = description;
  _dragElement = copied_element;
  _dragElement.style.left = (event.clientX) + 'px';
  _dragElement.style.top = (event.clientY) + 'px';
  _dragElement.style.position = 'absolute';
  _dragElement.style.display = 'block';
  document.onmouseup = OnMouseUp;
  document.onmousemove = OnMouseMove;
}

function deletereportelement() {
  if (report_save_div) {
    // save data by xbrlglprocess and refresh the clipboard but not using this response
    processtemplate('sa_main', 'not_required_response', 'clipboard_xslt', report_params, 'xbrlglprocess', report_save_div, 'html_to_xbrlgl', function () {
      // refresh the report
      processtemplate('sa_main', report_view_div, 'report_xslt', report_params, 'report');
      });
  }
}

<!-- end of drap and drop -->

function update_report_filter(entity_identifier) {
  report_last_account_filter = document.getElementById('account_clipboard_filter').value;
  processtemplate('sa_main', 'account_clipboard', 'clipboard_xslt', {entityIdentifier : entity_identifier, get_accounts_by_search : report_last_account_filter}, 'xbrlglprocess');
}


function loadFriends(entity_id, cont_id) {
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
 
  var viewerFriends = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
  var opt_params = {};
  opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 100;
  opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
    [opensocial.Person.Field.ABOUT_ME];

  req.add(req.newFetchPeopleRequest(viewerFriends, opt_params), 'viewerFriends');
 
  req.send(function (data) {
    onLoadFriends(data, entity_id, cont_id)
    });
}

function onLoadFriends(data, entity_id, cont_id) {
  var viewer = data.get('viewer').getData();
  var viewerFriends = data.get('viewerFriends').getData();
 
  html = new Array();
  viewerFriends.each(function(person) {
    if (person.getId()) {
      html.push('<table><tr><td style="width: 100px; height: 100px;">' +
        '<img src="' + person.getField(opensocial.Person.Field.THUMBNAIL_URL) + '"/>' +
        '</td><td><div style="font-weight: bold;">' + person.getDisplayName() + '</div>' +
        '<div>user id: ' + person.getId() + "</div>" +
        '<div>' + person.getField(opensocial.Person.Field.ABOUT_ME) + "</div></td><td>" +
        "<a href=\"#\" onclick=\"processnewviewer('" + person.getId() + "', '" + entity_id + "', '" + cont_id + "')\">Grant access</a>" +
        "</td></tr></table>");
    }
  });
  document.getElementById(cont_id + '_friends').innerHTML = html.join('');
}

function processnewviewer(newViewerId, entity_id, cont_id) {
  // add a new user to the user list div
  processtemplate('sa_main', cont_id + '_add_users', 'users_list_xslt', {viewerId : newViewerId, scope : 'admin', level : 'write', newtemplate : 'new_user'}, false, false, false, 
    function () {
      // save the user list and update the view
      processtemplate('sa_main', cont_id + '_container', 'users_list_xslt', {get_entity_information_by_entityIdentifier: entity_id, entityIdentifier: entity_id}, 'xbrlglprocess', cont_id + '_add', 'html_to_xbrlgl');
    }, true);
}

function loadUserSummary(user_id, div_id) {
  var req = opensocial.newDataRequest();
  var opt_params = {};
  opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
    [opensocial.Person.Field.ABOUT_ME,
    opensocial.Person.Field.THUMBNAIL_URL];
  req.add(req.newFetchPersonRequest(user_id, opt_params), 'user');
 
  req.send(function (data) {
    onLoadUserSummary(data, div_id)
    });
}

function onLoadUserSummary(data, div_id) {
  var user = data.get('user').getData();

  var div_el = document.getElementById(div_id);

  div_el.innerHTML = "<table><tr><td style=\"width: 100px; height: 100px;\"><img src='" + user.getField(opensocial.Person.Field.THUMBNAIL_URL) + "'/></td><td><div style=\"font-weight: bold;\">" +
    user.getDisplayName() + "</div>" +
    user.getField(opensocial.Person.Field.ABOUT_ME) + "</td></tr></table>";
}




function disablefc() {
  $("input[type='text'].inform").attr("disabled", "true");
  $("input[type='text'].date").attr("disabled", "true");
  $("input[type='text'].time").attr("disabled", "true");
  $("select.inform").attr("disabled", "true");
  $("textarea.inform").attr("disabled", "true");
}



function delete_xbrl_info(savesection, clipboardsection, reportsection, params) {
  // save data by xbrlglprocess and refresh the account clipbaord list
  processtemplate('sa_main', clipboardsection, 'clipboard_xslt', params, 'xbrlglprocess', savesection, 'html_to_xbrlgl', function () {
    // refresh the report
    processtemplate('sa_main', reportsection, 'report_xslt', params, 'report');
    });
}

function calculate_leave(section_id) {

  var section_el = section_id;
  if (typeof(section_id) == 'string') {
    section_el = $('#' + section_id);
  }

  var default_pay_date = section_el.find("*[name='gl-soc:entryPaySlipEndDate']").find("input").val();
  var frequency = section_el.find("*[name='gl-soc:entryPayFrequency']").find("input").val();
  var entryNormalRate = section_el.find("*[name='gl-soc:entryPaySlipNormalRate']").find("input").val();
  var url = server + '?action=calctax';

  section_el.find("*[name='leave_calculation']").each(function() {

    var leavescale = $(this).find("*[name='gl-soc:taxScale']").find("input").val();
    var takenQuantityEl = $(this).find("*[name='takenQuantity']").find("input");
    var takenQuantityElRev = $(this).find("*[name='takenQuantityRev']").find("input");
    var takenAmountEl = $(this).find("*[name='takenAmount']").find("input");
    var takenAmountElRev = $(this).find("*[name='takenAmountRev']").find("input");
    if (leavescale && (leavescale != '') && (leavescale != '-')) {
      if (!$(this).find("input[name='override_leave_calculation']").attr('checked')) {
        var apply_leave_amount = parseFloat(section_el.find("[name='journal_apply_leave_amount']").val());
        var apply_leave_quantity = parseFloat(section_el.find("[name='journal_apply_leave_quantity']").val());
        var pay_date_el = $(this).find("*[name='gl-soc:taxDate']").find("input");
        var pay_date = pay_date_el.val();
        if (pay_date == '') {
          pay_date_el.val(default_pay_date);
          pay_date = default_pay_date;
        }

        // alert('apply leave amt ' + apply_leave_amount + ' apply_leave_quantity ' + apply_leave_quantity + ' date ' + pay_date + ' taxscale ' + leavescale + ' frequency ' + frequency);
        var tqe = $(this).find("*[name='gl-soc:taxQuantity']").find("input");
        var tqeRev = $(this).find("*[name='taxQuantityRev']").find("input");
        var tae = $(this).find("*[name='gl-cor:taxAmount']").find("input");
        var taeRev = $(this).find("*[name='taxAmountRev']").find("input");
        var opening_qty = -parseFloat($(this).find("*[name='taxOpeningQuantityRev']").find("input").val());
        $(this).find("*[name='gl-soc:taxOpeningQuantity']").find("input").val(opening_qty);
        if (isNaN(opening_qty)) {
          opening_qty = 0;
        }
        var opening_amt = -parseFloat($(this).find("*[name='taxOpeningAmountRev']").find("input").val());
        $(this).find("*[name='gl-soc:taxOpeningAmount']").find("input").val(opening_amt);
        if (isNaN(opening_amt)) {
          opening_amt = 0;
        }
        opening_amt = Math.round(opening_amt * 100) / 100;
        var closing_qty_el = $(this).find("*[name='gl-soc:taxClosingQuantity']").find("input");
        var closing_rev_qty_el = $(this).find("*[name='taxClosingQuantityRev']").find("input");
        var closing_amt_el = $(this).find("*[name='gl-soc:taxClosingAmount']").find("input");
        var closing_rev_amt_el = $(this).find("*[name='taxClosingAmountRev']").find("input");
        var closing_payslip_leave_date = $(this).find("*[name='gl-soc:taxClosingDate']").find("input").val();

        var leave_code = $(this).find("*[name='gl-soc:taxLeaveCode']").find("input").val();

        var taken_qty = 0;
        var taken_amt = 0;
        section_el.find("*[name='gl-cor:entryDetail']").each(function() {
          $(this).find("[name='gl-cor:taxes']").each(function() {
            if ($(this).find("[name='gl-soc:taxLeaveCode']").find("input").val() == leave_code) {
              if (taken_qty_tmp = parseFloat($(this).find("*[name='gl-soc:taxQuantity']").find("input").val())) {
                taken_qty += taken_qty_tmp;
              }
              if (taken_amt_tmp = parseFloat($(this).find("*[name='gl-cor:taxAmount']").find("input").val())) {
                taken_amt += taken_amt_tmp;
              }
            }
          });
        });
        // subtract the leave qty and amt from the leave calc section
        if (taken_qty_tmp = parseFloat($(this).find("*[name='gl-soc:taxQuantity']").find("input").val())) {
          taken_qty -= taken_qty_tmp;
        }
        if (taken_amt_tmp = parseFloat($(this).find("*[name='gl-cor:taxAmount']").find("input").val())) {
          taken_amt -= taken_amt_tmp;
        }
        takenQuantityEl.val(-taken_qty);
        takenQuantityElRev.val(taken_qty);
        takenAmountEl.val(-taken_amt);
        takenAmountElRev.val(taken_amt);

        fetchData(url, function(response_xml) {

          var el_tax_amount = 0;
          var el_tax_quantity = 0;
          var tax_amount = $(response_xml).find('tax_amount').text();
          if (!tax_amount) {
            tax_amount = 0;
          }
          var tax_quantity = $(response_xml).find('tax_quantity').text();
          if (!tax_quantity) {
            tax_quantity = 0;
          }

          var orig_ctq = closing_qty_el.val();
          if (!orig_ctq) {
            orig_ctq = 0;
          }
          var orig_cta = closing_amt_el.val();
          if (!orig_cta) {
            orig_cta = 0;
          }

          var tq = Math.round((-tax_quantity) * 100000) / 100000;
          tqe.val(tq);
          tqeRev.val(-tq);
          var ctq = Math.round((tq + opening_qty + taken_qty) * 100000) / 100000;
          closing_qty_el.val(ctq);
          closing_rev_qty_el.val(-ctq);
          var cta = Math.round((ctq * entryNormalRate) * 100) / 100;
          closing_amt_el.val(cta);
          closing_rev_amt_el.val(-cta);
          tae.val(Math.round((cta - opening_amt - taken_amt) * 100) / 100);
          taeRev.val(-Math.round((cta - opening_amt - taken_amt) * 100) / 100);

          // try to find the identifier current leave entitlement and set that value as well
          section_el.find("[name='gl-soc:leaveEntitlement']").each(function() {
            // if this has the same taxCode update the leave balance
            if ($(this).find("[name='gl-soc:leaveCode']").find("input").val() == leave_code) {
              // update the closing balance by the movement in the leave
              var leaveDescription = $(this).find("[name='leaveDescriptionNoSave']").find("input").val();
              var closing_el = $(this).find("[name='gl-soc:leaveEntitlementHours']").find("input");
              var closing_el_rev = $(this).find("[name='leaveEntitlementHoursRev']").find("input");
              var orig_leave_closing = closing_el.val();
              var closing_hours = orig_leave_closing - orig_ctq + ctq;
              closing_el.val(orig_leave_closing - orig_ctq + ctq);
              closing_el_rev.val(orig_ctq - orig_leave_closing - ctq);
              // use nominal method to determine amount - revised - dont use nominal method but simply do a check that it equals nominal. alter user if different
              var closing_leave_amt_el = $(this).find("[name='gl-soc:leaveEntitlementAmount']").find("input");
              var closing_leave_amt_el_rev = $(this).find("[name='leaveEntitlementAmountRev']").find("input");
              var orig_amount_closing = closing_leave_amt_el.val();
              var closing_leave_amt = orig_amount_closing - orig_cta + cta;
              closing_leave_amt_el.val(closing_leave_amt);
              closing_leave_amt_el_rev.val(-closing_leave_amt);
              if (Math.round(closing_leave_amt - (closing_hours * entryNormalRate)) != 0) {
                alert("Warning: Leave calculation for " + leaveDescription + " contains and inconsistency. \n\nLeave calculated using nominal method = " + (closing_hours * entryNormalRate) + "\n\n Leave calculated using incremental method " + closing_leave_amt);
              }
              // if the date is less than the date on the pay slip update it
              var closing_date_el = $(this).find("[name='gl-soc:leaveEntitlementDate']").find("input");
              if (closing_date_el.val() < closing_payslip_leave_date) {
                closing_date_el.val(closing_payslip_leave_date);
              }
            }
          });
        }, 'sa_main', {'gross' : apply_leave_amount, 'gross_quantity' : apply_leave_quantity, 'date' : pay_date, 'taxscale' : leavescale, 'frequency' : frequency});
      }
    }
  });
}

function setdefaultdates() {
  var todaysdate = new Date();
  var thisyear = todaysdate.getYear();
  if (thisyear < 1000) {
    thisyear+=1900;
  }
  var thismonth = todaysdate.getMonth() + 1;

  var by = document.getElementById("beginyear");

  // create the select options for the year elements

  var endyearhtml = '';
  endyearhtml += '<select name="endyear" id="endyear">';
  for (var i = -1; i < 11; i++) {
    if (i == 0) {
      endyearhtml += '<option value="' + (thisyear - i) + '" selected="true">' + (thisyear - i) + '</option>';
    }
    else {
      endyearhtml += '<option value="' + (thisyear - i) + '">' + (thisyear - i) + '</option>';
    }
  }
  endyearhtml += '</select>';
  document.getElementById('endyearspan').innerHTML = endyearhtml;

  var beginyearhtml = '';
  beginyearhtml += '<select name="beginyear" id="beginyear">';
  for (var i = -1; i < 11; i++) {
    if (
      (i == 0 && thismonth > 6) ||
      (i == 1 && thismonth <= 6)
      ) {
      beginyearhtml += '<option value="' + (thisyear - i) + '" selected="true">' + (thisyear - i) + '</option>';
    }
    else {
      beginyearhtml += '<option value="' + (thisyear - i) + '">' + (thisyear - i) + '</option>';
    }
  }
  beginyearhtml += '</select>';
  document.getElementById('beginyearspan').innerHTML = beginyearhtml;

  document.getElementById('endmonth').selectedIndex = (thismonth - 1);
}

function init() {
  var initial_template = '<?php print $wp_initial_template; ?>';
  var template_params = {
    sbps_entity_list : {get_entity_information_by_search : '', template : 'sbps_entity_list' },
    sbps_access_list : {get_entity_information_by_search : '', template : 'sbps_access_list' },
    wp_employee_setup_xslt : {get_entity_information_by_search : '', get_identifier_references_by_search : ''},
    sbps_employee_list : {get_entity_information_by_search : '', get_identifier_references_by_search : '', template : 'sbps_employee_list' },
    wp_employee_setup_timesheet_xslt : {get_entity_information_by_search : '', get_identifier_references_by_search : ''},
    sbps_payslip_list : { get_entity_information_by_search : '', get_identifier_references_by_search : '', get_entry_detail_by_search : '', sourceJournalID : 'pl', postingStatus : 'deferred,proposed', template : 'sbps_payslip_list' },
    sbps_approval_list : { template : 'sbps_approval_list' },
    sbps_account_list : { get_entity_information_by_search : '', get_accounts_by_search : '', template : 'sbps_account_list' },
    sbps_measurable_list : { get_entity_information_by_search : '', get_measurables_by_search : '', template : 'sbps_measurable_list' },
    sbps_taxes_list : { get_entity_information_by_search : '', get_taxes_by_search : '', template : 'sbps_taxes_list' }
  }
  var params = template_params[initial_template];
  if (!params) {
    params = {get_entity_information_by_search : ''};
  }
  processtemplate('sa_main', 'sa_main', initial_template, params, 'xbrlglprocess');
}

function blankme(id, message) {
  if (message) {
    if (!confirm(message)) {
      return;
    }
  }
  document.getElementById(id).innerHTML = "";
  update_tax_amounts();
}

// routines that retrive the data and display a section

var last_entity_identifier = '';
var last_presentation_url = '';
var last_report_concept_id = '';

var server = '/request';

function processtemplate(showsection, viewsection, viewtemplate, params, url, savesection, savetemplate, callback, appendnew) {
  var start = new Date();
  start = start.getTime();

  if (!appendnew) {
    showwaitingimage(viewsection);
  }

  setTimeout(function() {

  var jqtime = 'jqtime';

  if (!appendnew) {
    appendnew = false;
  }

  if (!viewtemplate) {
    if (!showsection) {
      alert('error cannot process template without a show section');
    }
    showOneSection(showsection);
    return;
  }

  if (!url) {
    // no url just show the section
    if (!appendnew) {
//      var toit = setTimeout(function () {
//        showwaitingimage(viewsection);
//      }, 500);
    }
    fetchData(server + '?action=null', function(response_xml) {
      if (!appendnew) {
        clearTimeout(toit);
      }
      var error = $(response_xml).find('error').text();
      if (error) {
        alert('Error: ' + error);
      }
      else {
        if (callback) {
          showXSLT2(viewtemplate, viewsection, params, response_xml, appendnew, function () {
            callback(response_xml);
          });
        }
        else {
          showXSLT2(viewtemplate, viewsection, params, response_xml, appendnew, function () {
          });
        }
        if (params['entityIdentifier']) {
          jqtime = jqueryit(showsection, params['entityIdentifier']);
        }
        else {
          jqtime = jqueryit(showsection);
        }
      }
      $('#'+viewsection).fadeTo(0, 1);
    }, showsection, params);
    showOneSection(showsection);
    return;
  }

  var urls = {
    xbrlglprocess : (server + '?action=xbrlglprocess'),
    ai : (server + '?action=ai'),
    getxbrlgl : (server + '?action=getxbrlgl'),
    presentations : (server + '?action=report_presentations'),
    report : (server + '?action=report'),
    getfiledetails : (server + '?action=fileupload_getfiledetails'),
    getfilereference : (server + '?action=fileupload_getreference'),
    updatefiledetails : (server + '?action=fileupload_updatedetails'),
    getimportreference : (server + '?action=import_getreference')
  }
  var prefix = '?';
  if (urls[url]) {
    url = urls[url];
    prefix = '&';
  }
//  for (var key in params) {
//    url += prefix + key + '=' + params[key];
//    prefix = '&';
//  }
  var ts = new Date().getTime();
  url += prefix + 'nocache=' + ts;
  prefix = '&';

//  if (params['content_type'] == 'csv') {
//    location.href = url;
//    return;
//  }

//  var postdata = {
//    somedata : 'somedata'
//  };

  var prefetcha = new Date();
  prefetcha = prefetcha.getTime();

  if (savesection) {
//    if (!(postdata.xbrlgldata = get_save_xbrlgl(savesection, params))) {
    if (!(params.xbrlgldata = get_save_xbrlgl(savesection, params))) {
      return false;
    }
  }

//  if (!appendnew) {
    //var to = setTimeout(function () {
    //  showwaitingimage(viewsection);
    //}, 500);
// alert('swi');
//    showwaitingimage(viewsection);
//  }

  var prefetch = new Date();
  prefetch = prefetch.getTime();

  fetchData(url, function(response_xml) {

    var presx = new Date();
    presx = presx.getTime();

    // if (!appendnew) {
    //  clearTimeout(to);
    //}
    var error = $(response_xml).find('error').text();
    if (error) {
      alert('Error: ' + error);
    }
    else {
      if (callback) {
        showXSLT2(viewtemplate, viewsection, params, response_xml, appendnew, function () {
          callback(response_xml);
        });
      }
      else {
        showXSLT2(viewtemplate, viewsection, params, response_xml, appendnew);
      }
  
      var prejq = new Date();
      prejq = prejq.getTime();
  
      if (params['entityIdentifier']) {
        jqtime = jqueryit(showsection, params['entityIdentifier']);
      }
      else {
        jqtime = jqueryit(showsection);
      }
  
      var end = new Date();
      end = end.getTime();

//    alert("Performance measurement\n\n" +
//      "total time = " + (end - start) + "\n" +
//      "prefetch a time = " + (prefetcha - start) + "\n" +
//      "prefetch b time = " + (prefetch - prefetcha) + "\n" +
//      "fetch time = " + (presx - prefetch) + "\n" +
//      "showx time = " + (prejq - presx) + "\n" +
//      "jq time = " + (end - prejq) + "\n" +
//      "jq anal = " + jqtime
//      );
    }

    $('#'+viewsection).fadeTo(0, 1);
  }, showsection, params);//postdata);

  }, 100);// set timeout to show waiting image
}

function check_and_submit(divid) {
  var divel = $('#' + divid);
  var xbrlglta = divel.find("textarea[name='xbrlgldata']");
  if (xbrlglta.length > 0) {
    try {
      if (divel.attr('name') != 'xbrli:xbrl') {
        divel = divel.find('[name="xbrli:xbrl"]');
      }
      if (divel.length > 0) {
        xbrlglta.val(divel.xbrlgl('xbrlgl'));
        return true;
      }
    }
    catch(er) {
      alert(er);
      return false;
    }
  }
  alert('Error, could not find xbrl element');
  return false;
}

function showwaitingimage(element_id) {
  var el = $("#" + element_id);
  var height = el.height();
  if (height < 5) {
    height = 32;
  }
  el.fadeTo(1, 0.3);
  // el.css('display', 'none');
  //el.html('<div style="width: 1px; height: ' + height + 'px;"><img src="http://gadgets.socialaccounts.com/img/loading.gif" /></div>');
}

function getexport(params, target) {
  if (document.getElementById('export_transactions').checked) {
    params['get_entry_detail_by_filter'] = '1';
  }
  if (document.getElementById('export_accounts').checked) {
    params['get_accounts_by_search'] = '';
  }
  if (document.getElementById('export_taxes').checked) {
    params['get_taxes_by_search'] = '';
  }
  if (document.getElementById('export_job_info').checked) {
    params['get_job_info_by_search'] = '';
  }
  if (document.getElementById('export_measurables').checked) {
    params['get_measurables_by_search'] = '';
  }
  if (document.getElementById('export_identifier_references').checked) {
    params['get_identifier_references_by_search'] = '';
  }
  processtemplate('sa_main', target, 'export_result_xslt', params, 'xbrlglprocess');
}

//user can use keyboard to select list element
function show_select_process_key(unique_id, event){
  var select_element = document.getElementById(unique_id + '_select');
  if (event.keyCode == 40) {
    if (select_element.options.length == 0) {
      return true;
    }
    if(select_element.selectedIndex == select_element.options.length - 1){
        return true;
    }
    select_element.selectedIndex++;
    return true;
  }
  if (event.keyCode == 38) {
    // up arrow pressed
    if (select_element.options.length == 0) {
      return true;
    }
    if(select_element.selectedIndex == 0){
        return true;
    }	
    select_element.selectedIndex--;
    return true;
  }
  // check some other keys that do not need to refresh the select
  if (event.keyCode >= 9 && event.keyCode <= 46) {
    // tab, enter and more
    return true;
  }
  if (event.keyCode >= 91 && event.keyCode <= 95) {
    // function keys plus
    return true;
  }
  if (event.keyCode >= 112 && event.keyCode <= 145) {
    // function keys plus
    return true;
  }
  return false;
}

var selecttimeout;

function show_select(event, unique_id, viewtemplate, params, attributes) {
// alert('show_select ' + unique_id);
  clearTimeout(selecttimeout);
  var select_element = document.getElementById(unique_id + '_select');
  if (show_select_process_key(unique_id, event)) {
    // set the attributes
    // if up and down arrow update attributes
    if (attributes) {
      for(var i = 0; i < attributes.length; i++) {
        select_element.setAttribute(attributes[i], select_element.options[select_element.selectedIndex].getAttribute([attributes[i]]));
      }
    }
    update_tax_amounts();
    return true;
  }

  selecttimeout = setTimeout(function () {
    processtemplate('sa_main', unique_id + '_select_div', viewtemplate, params, 'xbrlglprocess', false, false,
      function () {
        var select_element = document.getElementById(unique_id + '_select');
        if (select_element.options.length > 0) {
          select_element.selectedIndex = 0;
          // any additional parameters set attributes
          if (attributes) {
            for(var i = 0; i < attributes.length; i++) {
              select_element.setAttribute(attributes[i], select_element.options[select_element.selectedIndex].getAttribute(attributes[i]));
            }
          }
        }
        update_tax_amounts();
      });
    }, 300);
}

var filterhideto;

function filter_hide(unique_id) {
  var filter = document.getElementById(unique_id + '_filter');
  var select = document.getElementById(unique_id + '_select');
  filter.filter_text = filter.value;
  filterhideto = setTimeout(function () {
    if (select.selectedIndex >= 0 && select.options.length > 0) {
      filter.value = select.options[select.selectedIndex].text;
    }
    else {
      filter.value = '';
    }
    select.style.display = 'none';
  }, 200);
}

function filter_unhide(unique_id) {
  var filter = document.getElementById(unique_id + '_filter');
  var select = document.getElementById(unique_id + '_select');
  if (filter.filter_text) {
    filter.value = filter.filter_text;
  }
  else {
    filter.value = '';
  }
  select.style.display = 'block';
}

function delay_hide(unique_id) {
  setTimeout(function () {
    var element = document.getElementById(unique_id);
    element.style.display = 'none';
  }, 500);
}

function unhide(unique_id) {
  var element = document.getElementById(unique_id);
  element.style.display = 'block';
}

function update_confirm(unique_id, attributes) {
  clearTimeout(filterhideto);
  var select_element = document.getElementById(unique_id + '_select');
  if (attributes) {
    for(var i = 0; i < attributes.length; i++) {
      select_element.setAttribute(attributes[i], select_element.options[select_element.selectedIndex].getAttribute([attributes[i]]));
    }
  }
  // focus back to the filter because select is not in the tab order
  var filter_element = document.getElementById(unique_id + '_filter');
  filter_element.focus();
  update_tax_amounts();
}


// routines that build the xml or xblrgl to send to the server

function buildFragment2(xslttxt, params, xml) {

  var xslt, xsltProcessor, resultDocument;
  xslt = xslttxt;
  // alert('xslttxt = ' + xslttxt);
  if (window.DOMParser) {
    if (!xml) {
      var p = new DOMParser();
      xml = p.parseFromString('<div></div>', "text/xml");
    }

    if (xml.documentElement.nodeName=="parsererror") {
      alert("Error in XML\n\n" + xml.documentElement.childNodes[0].nodeValue);
      return false;
    }
    if (xslt.documentElement.nodeName=="parsererror") {
      alert("Error in XSLT");
      return false;
    }
    xsltProcessor = new XSLTProcessor();
    for (var key in params) {
      if (params[key]) {
        xsltProcessor.setParameter("", key, params[key]);
      }
    }
    xsltProcessor.importStylesheet(xslt);
    // alert('after import style sheet');
    // var serializer = new XMLSerializer();
    // var tmp_xml = serializer.serializeToString(xml);
    // alert("data xml = " + tmp_xml);
    resultDocument = xsltProcessor.transformToFragment(xml, document);
    // alert('after transform');
    // var serializer = new XMLSerializer();
    // var calc_xml = serializer.serializeToString(resultDocument);
    // alert("html = " + calc_xml);
    return resultDocument;
  }
  else {
    // Internet Explorer
    if (!xml) {
      //xml = new ActiveXObject("Microsoft.XMLDOM");
      var xml = new ActiveXObject("MSXML2.FreeThreadedDomDocument");
      //XML.load("");
    }
    if (xml.parseError.errorCode!=0) {
      alert("Error in XML\n\nLine " + xml.parseError.line + ": " + xml.parseError.reason);
      return false
    }

    // xslt=new ActiveXObject("Microsoft.XMLDOM");
    if (xslt.parseError.errorCode!=0) {
      alert("Error in XSLT\n\nLine " + xsl.parseError.line + ": " + xsl.parseError.reason);
      return false
    }

    var XSLTCompiled = new ActiveXObject("MSXML2.XSLTemplate");
    XSLTCompiled.stylesheet = xslt.documentElement;
    // create XSL-processor
    var XSLTProc = XSLTCompiled.createProcessor();
    XSLTProc.input = xml;
 
    //Set the parameters
    for (var key in params) {
      if (params[key]) {
        XSLTProc.addParameter(key, params[key]);
      }
    }
 
    XSLTProc.transform();
 
    return XSLTProc.output;

  }

    //var resultDocument = xml.transformNode(xslt);
    //return resultDocument;

//$("#" + sectionId).getTransform(
//xslttxt,              // path or xsl document in javascript variable
//xml,              // path or xml document in javascript variable
//{
// params: x_params, // object for your own xsl parameters
//// xpath: '/test/inside',        // trims your xml file to that defined by this xpath
//eval: true                   // evaluates any <script> blocks it finds in the transformed result
//// callback: function(){}        // getTransform evaluates this function when transformation is complete
//}
//);

}

var gadget_server = 'http://www.smallbusinesspayrollservices.com.au';

var templates = new Object();

function showXSLT2(xsltContainerId, sectionId, params, xml, appendnew, callback) {
  if (!appendnew) {
    document.getElementById(sectionId).innerHTML = xml;
  }
  else {
    var section = $("#" + sectionId);
    section.append(xml);
  }

  if (callback) {
    callback();
  }
}

<!--Merge xml and xslt and return HTML. Required parameters xml, xslt container id,display section Id-->
function showXSLT2oldpart1(xsltContainerId, sectionId, params, d_xml, appendnew, callback) {
  // changed to xsl transform on server
  showXSLT2part2(null, sectionId, params, d_xml, appendnew, callback);
  return;

  var r_url = encodeURI(gadget_server + '/templates/' + xsltContainerId + '.xml');

  var ts = new Date().getTime();
  r_url += '?nocache=' + ts;
  
  if (templates[xsltContainerId]) {
    showXSLT2part2(templates[xsltContainerId], sectionId, params, d_xml, appendnew, callback);
  }
  else {
    $.ajax({
      type: "GET",
      url: r_url,
      success: function(xml) {
        if (xml) {
          var xslttext = xml;
          showXSLT2part2(xslttext, sectionId, params, d_xml, appendnew, callback);
          templates[xsltContainerId] = xslttext;
        }
        else {
          alert('No template found at ' + r_url);
        }
        if (callback) {
          callback();
        }
      }
    });
  }
}

<!--Fetch data -->
function fetchData(r_url, callback_function, one_section, postdata) {
  var params = {};
  r_url = encodeURI(r_url);

  $.ajax({
    type: "POST",
    url: r_url,
    data: postdata,
    dataType : 'xml',
    success: function(xml){
      var response_html = '';
      var has_html = false;
      $(xml).find('response_html').each(function() {
        has_html = true;
        response_html += $(this).text();
      });
      
      var response_request = '';
      $(xml).find('response_request').each(function() {
        response_request += $(this).text();
      });
      
      // $('#response_tmp').html(xml);
      // $('#response_all').val(xml);
      // var response_html = $("#response_tmp").find("#response_html").children("textarea").val();
      // var response_xml = $("#response_tmp").find("#response_xml").children("textarea").val();
      // var response_request = $("#response_tmp").find("#response_request").children("textarea").val();
      // $('#response_tmp').html('');
      // $('#response_xml').val(response_xml);
      $('#response_request').val(response_request);
      if (has_html) {
        callback_function(response_html);
      }
      else {
        callback_function(xml);
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert(XMLHttpRequest.status);
      alert(XMLHttpRequest.responseText);
    }
  });
  
}

<!-- the sections -->

function showOneSection(toshow) {
  var sections = [
    'sa_main'
    ];

  for (var i=0; i < sections.length; ++i) {
    var s = sections[i];
    var el = document.getElementById(s);
    if (s === toshow) {
      el.style.display = "block";
    }
    else {
      el.style.display = "none";
    }
  }
}

function showOneClipboard(toshow) {
  var sections = [
    'account_clipboard_ctl',
    'taxes_clipboard_ctl'
    ];

  for (var i=0; i < sections.length; ++i) {
    var s = sections[i];
    var el = document.getElementById(s);
    if (s === toshow) {
      el.style.display = "block";
    }
    else {
      el.style.display = "none";
    }
  }
}

var defaultable = ['gl-cor:identifierCode', 'gl-cor:postingDate', 'gl-cor:documentDate', 'gl-cor:documentNumber', 'gl-cor:postingStatus', 'gl-cor:documentReference'];
var checkparams = ['gl-cor:postingStatus'];
var format_hours_decimal = ['gl-bus:measurableQuantity'];

function in_array(needle, haystack) {
  for (key in haystack) {
    if (haystack[key] == needle) {
      return true;
    }
  }
  return false;
}

var extract_times = {};

function validate_join() {
  if (
    ($("#register_email").val() == '') ||
    ($("#register_password").val() == '') ||
    ($("#register_first_name").val() == '') ||
    ($("#register_last_name").val() == '') ||
    ($("#real_email").val() == '')
    ) {
    alert("You must complete all fields");
    return false;
  }
  if ($("#agree_to_terms:checked").length < 1) {
    alert("You must agree to the terms and conditions");
    return false;
  }
  return true;
}

var adnumber = 0;

function getad(adnumber) {
  adnumber++;
  $.ajax({
    type: "GET",
    url: ("/home/getad/" + adnumber),
    async: false,
    success: function(msg){
      $("#promotion1").html(msg);
    }
  });
  return adnumber;
}

function setTaxDates(section_id) {
  var section_el = $('#' + section_id);
  var taxDate = section_el.find("[name='gl-soc:entryPaySlipEndDate']").find("input").val();
  section_el.find("[name='gl-soc:taxDate']").find("input").val(taxDate);
  section_el.find("[name='gl-soc:taxClosingDate']").find("input").val(taxDate);
}

$(function() {
  jqueryit('contentDiv');
});

tfn_weights = new Array(1, 4, 3, 7, 5, 8, 6, 9, 10);
function checktfn(tfn) {
  total = 0;
  for (i = 0; i < 9; i++) { 
    total += tfn_weights[i] * tfn.charAt(i);
  }
  return total % 11 == 0;
}

function calc_minutes(hoursstr) {
  var parts = hoursstr.split(':');
  var hours = parseFloat(parts[0]);
  if (isNaN(hours)) {
    hours = 0;
  }
  var minutes = 0;
  if (parts.length > 1) {
    minutes = parseFloat(parts[1])
    if (isNaN(minutes)) {
      minutes = 0;
    }
  }
  minutes += hours * 60;
  return Math.floor(minutes);
}

function format_hours(hoursstr) {
  var minutes = calc_minutes(hoursstr);
  var hours = Math.floor(minutes / 60);
  minutes = minutes - (hours * 60);
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  return hours + ':' + minutes;
}

function format_minutes_as_hours(minutes) {
  var hours = Math.floor(minutes / 60);
  minutes = minutes - (hours * 60);
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  return hours + ':' + minutes;
}

function get_new_date(datestr, dayinc) {
  var dtparts = datestr.split('T');
  var dateonlystr = dtparts[0];
  var dateparts = dateonlystr.split('-');
  if (dateparts.length != 3) {
    throw "Error, incorrect date format. Use yyyy-mm-dd";
  }
  if (!dayinc) {
    dayinc = 0;
  }
  // time section
  var hours = 0;
  var minutes = 0;
  if (dtparts.length == 2) {
    minutes = calc_minutes(dtparts[1]);
    hours = Math.floor(minutes / 60);
    minutes = minutes - (hours * 60);
  }
  return new Date(dateparts[0], parseFloat(dateparts[1]) - 1, parseFloat(dateparts[2]) + dayinc, hours, minutes);
}

function check_format_date(datestr, dayinc) {
  var dateparts = datestr.split('-');
  if (dateparts.length != 3) {
    throw "Error, incorrect date format. Use yyyy-mm-dd";
  }
  if (!dayinc) {
    dayinc = 0;
  }
  var date = new Date(dateparts[0], parseFloat(dateparts[1]) - 1, parseFloat(dateparts[2]) + dayinc);
  var month = date.getMonth() + 1;
  if (month < 10) {
    month = '0' + month;
  }
  var day = date.getDate();
  if (day < 10) {
    day = '0' + day;
  }
  return date.getFullYear() + '-' + month + '-' + day;
}

function check_format_date_time(datetimestr) {
  var parts = datetimestr.split('T');
  if (parts.length == 1) {
    return check_format_date(parts[0]);
  }
  else if (parts.length == 2) {
    return check_format_date(parts[0]) + 'T' + format_hours(parts[1]);
  }
  throw "Error, incorrect date time format";
}

function xbrlgl_format_date_time(date) {
  var month = date.getMonth() + 1;
  if (month < 10) {
    month = '0' + month;
  }
  var day = date.getDate();
  if (day < 10) {
    day = '0' + day;
  }
  var hours = date.getHours();
  if (hours < 10) {
    hours = '0' + hours;
  }
  var minutes = date.getMinutes();
  if (minutes < 10) {
    minutes = '0' + minutes;
  }
  var seconds = date.getSeconds();
  if (seconds < 10) {
    seconds = '0' + seconds;
  }
  return date.getFullYear() + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
}

function fetchHTML(r_url, callback_function, postdata) {
  var params = {};
  r_url = encodeURI(r_url);

  $.ajax({
    type: "POST",
    url: r_url,
    data: postdata,
    dataType : 'html',
    success: function(response_html){
      callback_function(response_html);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      alert(XMLHttpRequest.status);
      alert(XMLHttpRequest.responseText);
    }
  });
  
}

