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;
  }
}

var ItemListSave = function(json) { 
      var data = '';
	  var j = 0;
	  for(var i=0; i<N.rowCount(); i++) {
		if (N.row(i).getData().checked ==1) { 
			data = data + '&p_' + j.toString() + '=' + JSON.stringifyNoSecurity(N.row(i).getData());
			j++;
			}
      }	  
      return data;
}

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;
	  //document.getElementById('position_list').value = ItemListSave(true);
	  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 ItemListClear(noNew) {
  while(N.rowCount()>0) N.row(0).deleteRow(noNew);
}




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'+ItemListSave(true);
  //alert(pd);
  var record = document.forms.EditView.record.value;
  var pd2 = new Object();
  
  pd2['module'] = 'EcmInvoiceOuts';
  pd2['action'] = action;
  pd2['record'] = document.forms.EditView.record.value;
  pd2['to_pdf'] = '1';
  pd2['cache'] = 'fromJava';
  
  document.forms.EditView.position_list.value = '';
  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;
    }
  }

  pd2['module'] = 'EcmPrepaimentInvoices';
  pd2['action'] = action;
  pd2['record'] = record;
  pd2['to_pdf'] = '1';
  pd2['cache'] = 'fromJava';
  
  pd += '&otherFormData='+JSON.stringifyNoSecurity(pd2);
 
  return pd;     
}
  

/*
function sendFormPostToPdf() {
  ShowLoadingView();
  setTimeout( function() {

	  ERROR = false;
	  //document.getElementById('position_list').value = ItemListSave(true);
	  if(ERROR) { alert('There are some errors on list'); HideLoadingView(); return false; }
	  doRequest("index.php",getFormPost(),function(result){
		  HideLoadingView();
		  EcmPreviewPDF('index.php?module=EcmInvoiceOuts&action=previewPDF&to_pdf=1&from=EcmInvoiceOuts',{zoom:75});
		}
	  );

  },200);
}*/
function sendFormPostToPdf() {
  ERROR = false;
  document.getElementById('position_list').value = ItemListSave(true);
  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 () {
  
     //initialize table
    N = new MyTable('itemsTable');
	
	N.divParent = document.getElementById('itemsTableDIV');


    N.onCreateRow = function(row) {
      row.newPos = false;

      row.onSelect = function() {
        for(var i=0; i<this.myTable.colCount(); i++) {
		  this.cells.item(i).style.height = OPT['row_item_height_selected'];
          this.cells.item(i).change(!this.newPos);
		}
      }
      row.onDeselect = function() {
        for(var i=0; i<this.myTable.colCount(); i++) {
		  this.cells.item(i).style.height = OPT['row_item_height'];
          this.cells.item(i).change(false);
		}
      }
    }
	
	var itd = document.getElementById('itemsTableDIV');
	
    N.onCreateCell = function(cell) {
      
      var i = cell.index;
      cell.change = function(select) {};
	  cell.style.height = OPT['row_item_height'];
	  
      if(i == 0) {
      
        cell.setData = function(data) {
          if(data.checked) cell.firstChild.checked = data.checked;
        };
        cell.getData = function(data) {
          data.checked = cell.firstChild.checked;
        }
        cell.select = function() { this.selectNext(); }
  
        var edit = document.createElement('input');
        edit.setAttribute('type','checkbox');
        edit.setAttribute('tabIndex',1);
        edit.setAttribute('checked',true);
        edit.className = 'inputs';
        cell.appendChild(edit);
      }
  
      if(i == 1) {
        cell.change = function(select) {
                    
          var cn = this.getElementsByTagName('input');
          var c;
          if(select) {
            c = cn[0]; c.name = 'code_p'; c.id = 'code_p'; c.className = 'inputs';// sqsEnabled';
			c = cn[1]; c.name = 'id_p'; c.id = 'id_p';
			c = cn[2]; c.name = 'iid_p'; c.id = 'iid_p';
	                  }
           else {
            c = cn[0]; c.name = ''; c.id = ''; c.className = 'inputs';
            c = cn[1]; c.name = ''; c.id = '';
            c = cn[2]; c.name = ''; c.id = '';
          }		  
        }

        cell.getData = function(data) {
          var cn = this.getElementsByTagName('input');
          data.code = cn[0].value;
          data.id = cn[1].value;
		  data.iid = cn[2].value;
        }
        cell.setData = function(data) {
          var cn = this.getElementsByTagName('input');
          cn[0].value = ((data.code)?data.code:'');
          cn[1].value = ((data.id)?data.id:'');
          cn[2].value = ((data.iid)?data.iid:'');
		}
        var edit = '<input type="text" onFocus="this.parentNode.select();" tabindex="1" class="inputs" style="height:16px;" autocomplete="off" readonly="readonly"><br>';
        cell.innerHTML = edit;
        cell.align = 'right';
        var id = document.createElement('input');
        id.setAttribute('type','hidden');
        cell.appendChild(id);
	
		var iid = document.createElement('input');
        iid.setAttribute('type','hidden');
        cell.appendChild(iid);
      }
      //nazwa
      if(i == 2) {
        cell.change = function(select) {
          var c;
          if(select) {
            c = this.childNodes[0]; c.name = 'name_p'; c.id = 'name_p'; //c.className = 'sqsEnabled';
          }
           else {
            c = this.childNodes[0]; c.name = ''; c.id = ''; c.className = '';
          }
        }    
        cell.getData = function(data) {
          var cn = this.getElementsByTagName('textarea');
          data.name = cn[0].value;      
        }
        cell.setData = function(data) {
          var cn = this.getElementsByTagName('textarea');
			  cn[0].value = ((data.name)?data.name:'');
        }           
        var textarea = '<textarea tabindex="1" onFocus="this.parentNode.select();" style="width:100%;height:100%;" readonly="readonly" class="inputs" onKeyDown="return this.parentNode.myTable.KeyPressed(event,this.parentNode,null,true);"></textarea>';
        cell.innerHTML = textarea;      
      }
    }
    N.onSetCellData = function(row,cell,data) {
      if(cell.innerHTML == '') cell.innerHTML = '&nbsp;';
    }

    var pl = document.getElementById('position_list').value;
    if(pl && pl != '') {
      try {
        pl = eval(pl);
        for(x in pl) { 
		var pl_row = pl[x]; if(!pl[x].code || pl[x].code == '') {} else N.addRow().setData(pl_row); }
      } catch(err) { pl = null; };
    }
  
    if(N.rowCount() == 0) N.addRow();

    ItemsList = function(json) { 
      var data = '';
	  for(var i=0; i<N.rowCount(); i++) {
        data = data + '||||' + JSON.stringifyNoSecurity(N.row(i).getData());
      }
	  
      return data;
    } 
    
    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').value="PRZEDPŁATA";
	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;
	//if (document.getElementById('template_name')=='')
		


    CHANGER.startTimer();
  }

);



