function doRequest(where, post, doFunction, error) {
  this.Display = function (result) { doFunction(result.responseText); }
  this.Fail = function (result) { if (error) alert(error); }
  YAHOO.util.Connect.asyncRequest('POST', where, { success: this.Display, failure: this.Fail }, post);
}
function generateNumber() {
  if (document.getElementById('template_id').value == '') { alert('There are no DocumentTemplates in data base!'); return; }
  doRequest(
    'index.php',
    'to_pdf=1&generate=1&module=EcmPrepaymentInvoices&action=generateNumber&template_id=' + document.getElementById('template_id').value + '&record=' + document.forms.EditView.record.value,
    function (result) {
      var arr = eval(result)[0];
      document.getElementById('number').value = arr.number;
      document.getElementById('document_no').value = arr.document_no;
    },
    ''
  );
};

function addEvent(object, eventName, do_function) {
  if (typeof (object) == "string") object = document.getElementById(object);
  if (!object) { alert('No object in function addEvent!'); return; }
  if (object.addEventListener) {
    object.addEventListener(eventName, do_function, false);
  } else {
    object.attachEvent('on' + eventName, do_function);
  }
}
function changer() {
  this.list = new Object();
  this.add = function (object, type, do_function, start_value) {
    if (typeof (object) == "string") object = document.getElementById(object);
    if (!object) return;
    this.list[object.id] = new Object();
    this.list[object.id].object = object;
    this.list[object.id].type = type;
    this.list[object.id].do_function = do_function;
    this.list[object.id].start_value = start_value;
    this.list[object.id].value = '';
  }
  this.getValue = function (element) {
    var value = null;
    if (element.object) {
      if (element.type == "innerHTML") value = element.object.innerHTML;
      if (element.type == "value") value = element.object.value;
      if (element.type == "checked") value = element.object.checked;
    }
    return value;
  }
  this.interval = 1000;
  this.timer = null;
  this.startTimer = function () {
    var cc = this;
    this.timer = setInterval(
      function () {
        var list = cc.list;
        for (x in list) {
          if (list[x].start_value) {
            list[x].value = cc.getValue(list[x]);
            list[x].start_value = false;
          }
          else {
            var value = cc.getValue(list[x]);
            if (list[x].value !== value)
              if (list[x].do_function)
                list[x].do_function(list[x].object);
            list[x].value = value;
          }
        }
      },
      this.interval
    );
  }
  this.stopTimer = function () {
    clearInterval(this.timer);
    this.timer = null;
  }
}

function ShowLoadingView() {
  var slv = document.getElementById('ShowLoadingView');
  if (!slv) {
    slv = document.createElement('div');
    slv.id = 'ShowLoadingView';
    slv.className = 'transparent_class_loading';
    slv.style.width = '100%';
    slv.style.height = '500%';

    var sli = document.createElement('img');
    sli.className = 'transparent_class_loading_image';
    sli.src = 'themes/default/images/loading.gif';
    slv.appendChild(sli);

    document.body.appendChild(slv);
  }
  slv.style.display = '';
}

function HideLoadingView() {
  var slv = document.getElementById('ShowLoadingView');
  if (slv) slv.style.display = 'none';
}


function SaveForm() {
  ShowLoadingView();
  setTimeout(function () {
    if (OPT['checkbox_demo'] == 1 && document.forms.EditView.record.value == '') { alert(MOD.LBL_DEMO_VERSION_INFORMATION); return; }
    ERROR = false;
    if (ERROR) { alert(MOD['LBL_SAVE_FORM_ERROR']); HideLoadingView(); return false; }
    document.forms.EditView.action.value = 'Save';

    if (check_form('EditView')) {
      doRequest('index.php', getFormPost('Save'), function (result) {
        document.forms.EditView.record.value = result.substring(result.length - 36);
        alert(MOD['LBL_SAVED']);
        window.onbeforeunload = '';
        if (OPT['setEmailTab']) setEMAIL(true); else window.location = 'index.php?module=' + document.forms.EditView.module.value + '&action=DetailView&record=' + document.forms.EditView.record.value;
        HideLoadingView();
      },
        MOD['LBL_NOT_SAVED']
      );
    } else { alert(MOD['LBL_NOT_SAVED']); HideLoadingView(); return false; }
  }, 200);
}




function getFormPost(action) {
  if (!action) action = 'previewPDF';
  var pd = 'to_pdf=1' + '&module=EcmPrepaymentInvoices&action=' + action + '&record=' + document.forms.EditView.record.value;
  pd += '&cache=fromJava';
  //alert(pd);
  var record = document.forms.EditView.record.value;
  var pd2 = new Object();

  pd2['module'] = 'EcmPrepaymentinvoices';
  pd2['action'] = action;
  pd2['record'] = document.forms.EditView.record.value;
  pd2['to_pdf'] = '1';
  pd2['cache'] = 'fromJava';

  document.forms["EditView"].action.value = action;
  var tmp;
  for (var i = 0; i < document.forms["EditView"].elements.length; i++) {
    tmp = document.forms["EditView"].elements[i];
    if (tmp.name != '') {
      if (tmp.type == "checkbox")
        pd2[document.forms["EditView"].elements[i].name] = (document.forms["EditView"].elements[i].checked ? '1' : '0');
      else
        pd2[document.forms["EditView"].elements[i].name] = document.forms["EditView"].elements[i].value;
    }
  }

  console.log(pd2);

  pd += '&otherFormData=' + JSON.stringifyNoSecurity(pd2);

  return pd;
}

/*
function sendFormPostToPdf() {
  ERROR = false;
  if (ERROR) { alert('There are some errors on list'); return false; }
  doRequest("index.php", getFormPost(), function (result) {
    if (SHOW_PDF_IN_DIV == 1) {
      HideLoadingView();
      //SetTab('PREVIEW');
      EcmPreviewPDF('index.php?module=EcmInvoiceOuts&action=previewPDF&to_pdf=1&from=EcmInvoiceOuts', { zoom: 75 });
    }
    else {
      SetTab('PREVIEW');
      document.getElementById('previewPDF').innerHTML = "<iframe style='border:none;width:100%;height:1200px;' frameborder='no' src='index.php?module=EcmInvoiceOuts&action=previewPDF&to_pdf=1&from=EcmInvoiceOuts#zoom=75'>Yours browser not accept iframes!</iframe>";
    }
  }
  );
}

function canConfirm() {
  if (document.forms.EditView.status.value == "accepted" && !OPT.user.confirm_receipts) {
    alert('This option is disabled for You.');
    document.forms.EditView.status.value = ((OPT.old_status) ? OPT.old_status : '');
  }
  OPT.old_status = document.forms.EditView.status.value;
}

*/

addEvent(
  window,
  'load',
  function () {

    if (document.getElementById("isSale").value == true) {
      generateNumber();
    }

    //initialize table

    var CHANGER = new changer();
    CHANGER.interval = 500;

    /*
    function setToAddrEmail(str) {
      if (str && str != '') str = eval(str); else str = '';
      if (typeof (str) == "object") str = str[0]; else str = '';
      //= document.getElementById('to_addrs_field'); if(tmp) tmp.value = (str=='')?'':(((str.name)?str.name:'')+' <'+((str.email1)?str.email1:'')+'>; ');
      tmp = document.getElementById('parent_address_street'); if (tmp) tmp.value = (str.billing_address_street) ? str.billing_address_street : '';
      tmp = document.getElementById('parent_address_city'); if (tmp) tmp.value = (str.billing_address_city) ? str.billing_address_city : '';
      tmp = document.getElementById('parent_address_postalcode'); if (tmp) tmp.value = (str.billing_address_postalcode) ? str.billing_address_postalcode : '';
      tmp = document.getElementById('parent_address_country'); if (tmp) tmp.value = (str.billing_address_country) ? str.billing_address_country : '';
      //        tmp = document.getElementById('to_nip'); if(tmp) tmp.value = (str.sic_code)?str.sic_code:'';
      tmp = document.getElementById('to_nip'); if (tmp) tmp.value = (str.vatid) ? str.vatid : '';
      tmp = document.getElementById('to_nip'); if (tmp) tmp.value = (str.sic_code) ? str.sic_code : '';
      tmp = document.getElementById('ecmlanguage'); if (tmp && str.ecmlanguage) { if (tmp.value != str.ecmlanguage) { tmp.value = str.ecmlanguage; setTexts(); } }
      tmp = document.getElementById('currency_id'); if (tmp) tmp.value = (str.currency_id) ? str.currency_id : '';
      tmp = document.getElementById('ecmpaymentcondition_id'); if (tmp) tmp.value = (str.ecmpaymentcondition_id) ? str.ecmpaymentcondition_id : '';
      tmp = document.getElementById('ecmpaymentcondition_name'); if (tmp) tmp.value = (str.ecmpaymentcondition_name) ? str.ecmpaymentcondition_name : '';
    }
*/
    generateNumber();
    function ParentIdChange(obj) {
      var list = '';
      list = 'gdModule=Accounts&gdData=sic_code|name|email1|billing_address_street|billing_address_city|billing_address_postalcode|billing_address_country|sic_code|sic_code|vatid|is_vat_free|ecmlanguage|currency_id|ecmpaymentcondition_name|ecmpaymentcondition_id|supplier_code';
      if (obj.value == '') setToAddrEmail(''); else doRequest('index.php', 'module=EcmInvoiceOuts&action=getData&' + list + '&gdId=' + obj.value + '&to_pdf=1', setToAddrEmail);
    }

    CHANGER.add('parent_id', 'value', ParentIdChange, true);

    document.getElementById('description').rows = 1;

    document.getElementById('template_name').value = document.getElementById('template_id').options[document.getElementById('template_id').selectedIndex].text;
    document.getElementById('ecmvat_name').value = document.getElementById('ecmvat_id').options[document.getElementById('ecmvat_id').selectedIndex].text;

    CHANGER.startTimer();
  }

);



